Re: Implementing Closures

Tony Finch <dot@dotat.at>
26 Apr 2009 01:15:58 +0100 (BST)

          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)
Re: Implementing Closures torbenm@pc-003.diku.dk (2009-04-29)
Re: Implementing Closures dot@dotat.at (Tony Finch) (2009-04-29)
[3 later articles]
| List of all articles for this month |

From: Tony Finch <dot@dotat.at>
Newsgroups: comp.compilers
Date: 26 Apr 2009 01:15:58 +0100 (BST)
Organization: dotat labs
References: 09-04-056
Keywords: storage, interpreter
Posted-Date: 27 Apr 2009 05:54:45 EDT
X-Attribution: fanf hates supercite

Andrew Tomazos <andrew@tomazos.com> wrote:
>
>What are some of the approaches a compiler author could use to
>implement such a language feature?


The Lua interpreter has an interesting implementation. See
http://www.tecgraf.puc-rio.br/~lhf/ftp/doc/jucs05.pdf


>[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]


A naive implementation of this technique is vulnerable to nasty space
leaks. For example, function foo's activation frame contains a
reference to a large data structure. Foo returns an inner function bar
whose closure refers to a small variable in foo's activation frame. If
bar's closure keeps foo's whole activation frame live, instead of just
the small variable, then the garbage collector will not reclaim the
large data structure. Andrew Appel's book "Compiling With
Continuations" discusses various optimisations for closure
represenation.


Tony.
--
f.anthony.n.finch <dot@dotat.at> http://dotat.at/
ROCKALL: SOUTHWESTERLY 5 TO 7, OCCASIONALLY GALE 8 IN NORTH. ROUGH OR VERY
ROUGH, OCCASIONALLY HIGH IN NORTH. SQUALLY SHOWERS. MODERATE OR GOOD.



Post a followup to this message

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