logoalt Hacker News

WalterBrightyesterday at 11:33 PM3 repliesview on HN

The 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.


Replies

yvdriesstoday at 10:13 AM

I really like languages that embrace the duality of "closures are a poor man's object, objects are a poor man's closure".

ack_completetoday at 7:03 AM

Sadly, I've never seen a C++ compiler use this (old) technique for lambda reference captures. The main compilers all seem to just use individual references for each capture instead of a single reference to the stack frame, which makes the lambdas with a lot of reference captures more expensive.

show 1 reply
hirvi74today at 4:15 AM

Isn't it RBP the 64-bit register?