<- Back
Comments (14)
- alexey-salminThis article somehow omits the 80% of both the complexity and the benefits of the GCC nested functions which makes them pointless. Namely you can cast them to function pointers and pass them e.g. as a comparator to the sort() routine. Substituting the right parent frame parameter at the time the nested function is called down the stack is tricky and requires either an explicit support in the ABI (ia-64) or an executable stack to build a trampoline or a special logic to wrap function pointers with a special but set [1].Without all this nested functions are as useful as the "rewritten" examples in the article, one can easily do that by hand without any compiler or language support.This problem doesn't arise with C++ lambdas because you pass them around as special objects, not as bare function pointers.[1] https://gcc.gnu.org/onlinedocs/gccint/Trampolines.html
- WalterBrightThe D language's nested functions are implemented with a static link and a dynamic link. You're all familiar with the dynamic link, which is a pointer to the calling function's stack frame (EBP on x86_64 processors). The static link is the interesting one, it is a pointer to the statically enclosing stack frame.Thus, to access stack variables two enclosing functions up, the static link is walked twice.A reference to a nested function in D is represented by a pair - a pointer to the function, and the static link. (Called a "delegate" in D parlance.) Interestingly, this is the same layout as taking a reference to a member function, where the "this" pointer takes the place of the static link.This means that references to nested functions are ABI compatible with references to member functions.Lambdas in D are just a more compact syntax for nested functions.
- torginus> In GCC, nested functions are lowered in an early middle-end pass. During this pass, all variables of the parent that are accessed by the nested function are collected into a single synthetic structure, and a pointer to this structure is passed to the nested function in a hidden argumentGenerally this is a bit nicer than having explicit lambdas, but I thought the 'best-case' scenario would be if GCC saw into the stack layout of the calling function and could manipulate the calling functions stored stack variables (and saved registers). After all, a debugger can track what variable goes where at every line of code, so this can be done.Not sure if this would be useful or practical, but would be a nice bit of nerd cred.