Full closures for D
Walter Bright
newshound1 at digitalmars.com
Fri Nov 2 17:35:52 PDT 2007
How do D closures work?
1) The compiler makes a distinction between a nested function that
'escapes' the scope, and one that does not. It uses a very simple, but
conservative, heuristic - did someone take the address of the function?
If yes, it assumes the function escapes.
2) The compiler logs all local variables that are referenced by any
nested function.
3) If any of those variables are referenced by an escaping nested
function, or a nested function that encloses an escaping function, then
upon function entry all the referenced variables are allocated on a
heap-allocated chunk of memory rather than on the stack. Any referenced
parameters are copied into that chunk. That chunk is linked into the
nested context frames rather than the stack frame.
4) Variables not referenced by nested functions are still allocated on
the stack.
Note you can see this at work by running obj2asm on the test code I posted.
It's not an optimal solution because the "does the function escape"
heuristic captures too many functions.
More information about the Digitalmars-d
mailing list