Implementing Closures

Andrew Tomazos <andrew@tomazos.com>
Fri, 24 Apr 2009 04:50:05 -0700 (PDT)

          From comp.compilers

Related articles
Implementing Closures andrew@tomazos.com (Andrew Tomazos) (2009-04-24)
Re: Implementing Closures armelasselin@hotmail.com (Armel) (2009-04-24)
Re: Implementing Closures dot@dotat.at (Tony Finch) (2009-04-26)
Re: Implementing Closures barry.j.kelly@gmail.com (Barry Kelly) (2009-04-26)
Re: Implementing Closures cr88192@hotmail.com (cr88192) (2009-04-26)
Re: Implementing Closures torbenm@pc-003.diku.dk (2009-04-28)
Re: Implementing Closures pertti.kellomaki@tut.fi (Pertti Kellomaki) (2009-04-29)
[5 later articles]
| List of all articles for this month |
From: Andrew Tomazos <andrew@tomazos.com>
Newsgroups: comp.compilers
Date: Fri, 24 Apr 2009 04:50:05 -0700 (PDT)
Organization: Compilers Central
Keywords: storage, design, question, comment
Posted-Date: 24 Apr 2009 08:51:00 EDT

Please consider the following pseudocode...


typedef (int (*)(int)) int2int; // int2int: type of function taking an
int and returning an int


int2int f()
{
        int x = 3;


        int g(int y) // local function
        {
                x = x + y; // modifies local variable from enclosing scope.
                return x * y;
        }


        return g;
}


int2int h = f();
print(h(2)); // prints 10
print(h(2)); // prints 14
h = f();
print(h(2)); // prints 10


Here f is a function that takes no parameters and returns a function
of type (int -> int).


g is a local function that makes use of a local variable from a
containing scope.


A compiler (such as a C/C++ compiler) would normally implement x by
allocating space in f's stack frame.


The problem is that when f returns the closure g still needs access to
that instance of x for its lifetime, but the stack frame is deleted.


Also it is not sufficient to implement the function pointer of g as
simply pointing to static code. Each instance of int2int, must also
have some kind of reference to the x instance it modifies.


What are some of the approaches a compiler author could use to
implement such a language feature?


Thanks,
Andrew.
[This issue is well understood in the Lisp community. You basically need
to implement the activation records in a heap and garbage collect them,
keeping them live as long as there are any references to the closure. If
the closure can refer to variables in enclosing scopes, you need to keep
those scopes active as well, in what's known as a spaghetti or cactus
stack. -John]


Post a followup to this message

Return to the comp.compilers page.
Search the comp.compilers archives again.