BRAINSTORM: Exceptions using delegates, goto: out of a delegate literal?
Russell Lewis
webmaster at villagersonline.com
Sun Jan 20 21:15:21 PST 2008
Imagine that you could goto: out of a delegate literal into the original
function. This would allow you to perform a language-friendly, compiler
directed longjmp(). Moreover, since it uses the existing delegate
literal mechanisms, it should be a lot faster than setjmp/longjmp. You
don't have the runtime cost of a setjmp (no need to do any snapshotting
other than what the function would do anyway), and the goto itself would
(presumably) be much less costly than a longjmp, since the compiler
knows exactly what registers to restore (presumably few, since the
function's locals would reside on the stack or heap already).
Now imagine that you used this facility to build an elegant alternative
to exceptions: exception-safe functions would have an implicit argument
which was the exception handler delegate. To define a new exception
handler, you write a new delegate and pass it as the current handler to
any functions you call. (Your new delegate can chain to the old if you
desire to implement catch-and-throw or catching of only certain types.)
Ofc, this means that each exception-safe function has the added cost of
an implicit delegate parameter, which I don't want to ignore, but I will
neglect it for a bit.
The big downside of the above idea (other than the runtime cost I'm
neglecting) is that the syntax is nontrivial. A exception handler would
be something like this:
void func() {
SomeOtherFunc(delegate void(Exception e) { <handler code>
goto _out; },
<some other, normal parameters);
_out:
return;
}
Is there some way that we could leverage or alter the exception syntax
in D to give us some syntax sugar? This is very akin to how foreach
works: the compiler adds magic to make a common paradigm easy to code
and easy to read. What about something like:
void func() {
keyword1 {
SomeOtherFunc(<normal params>);
}
keyword2(Exception e) {
<handler code>
goto _out;
}
_out:
return;
}
The cool thing is that if we get this syntax right, then it becomes a
general-purpose language feature which would provide exception handling
as just one special case.
Thoughts?
More information about the Digitalmars-d
mailing list