How Nested Functions Work, part 1

Jeremie Pelletier jeremiep at gmail.com
Sun Aug 30 19:54:36 PDT 2009


Jarrett Billingsley Wrote:

> On Sun, Aug 30, 2009 at 9:00 PM, Jeremie Pelletier<jeremiep at gmail.com> wrote:
> > Walter Bright Wrote:
> >
> >> http://www.reddit.com/r/programming/comments/9fk6g/how_nested_functions_work_part_1/
> >
> > I really like the way nested functions and closures are done in D. Especially because they are the same thing as delegate and closures.
> >
> > But speaking of closures, I did notice something that could be optimized:
> >
> > void foo {
> >    int a;
> >    void foo2() { a++;}
> >    bar(&foo2);
> > }
> > void bar(in void delegate() dg) { dg(); }
> >
> > Here foo() is using _d_allocmemory to get storage for the stack frame. I understand it is for cases where the closure is executed long after the owner method has returned, but if the delegate has a scope storage class it could use the thread's stack instead.
> 
> It already is optimized if you use "void bar(scope void delegate()
> dg)". If it doesn't optimize it when you use 'in', it's probably a
> bug. :)

I need to try that out, its most likely a bug since 'in' means 'const scope' now. 

Check my second code bit, the delegate is declared as scope and it doesn't optimize, maybe the compiler only checks if the closure is being dereferenced and if so switches to memory storage instead of stack storage without checking the storage class of the closure's delegate. And even without 'scope' in this case the compiler could detect that the delegate doesn't leave the function scope and optimize away.

Better yet, allow forward references for nested functions. The need to assign closures to delegates to get a nested function is so C# ;)



More information about the Digitalmars-d mailing list