return when desugaring to closures

Waldemar Horwat waldemar at google.com
Thu Aug 21 11:19:06 PDT 2008


Lex Spoon wrote:
>>> (function(x, y) {
>>>   print(y);
>>> })(2, x)
>> We've been over this. What if you replace print(y) with return y?
> 
> Desugaring to closures is highly worthwhile, so it looks worth solving
> these.  Defining good variable-definition semantics is hard, as the
> experience with var shows, so it's good to reuse function literals if
> at all possible.
> 
> The problems you describe are actually not hard to fix.  All that has
> to happen is that return is labeled with the function it applies to.
> If at parse time no label is supplied, then the parser can manufacture
> a label to use.
> 
> The simplest implementation is that if whenever you create a function
> object with a return in it, you record in the object the stack frame
> that that return would apply to.  This stack frame will always be
> either the current stack frame, or one that was passed in from a
> surrounding frame.  When a return actually happens, you can then pop
> the stack until you get to that frame, or else signal an error if that
> frame has already popped.
> 
> Common Lisp works this way, and as far as I know it has worked out
> nicely.  Scala faced this exact problem, and it added non-local
> returns to address them.  Smalltalk has non-local returns, presumably
> because it, too, uses a lot of nested anonymous functions, and they
> work well there, too.
> 
> So, I agree that return, etc., need to be fixed up if you desugar to
> closures, but they can indeed be fixed up.  Further, you probably want
> non-local return anyway if people are going to use a lot of function
> literals in their code.
> 
> Likewise for break and continue (which are already labeled), and
> arguments (which could certainly be labeled).

and 'var'?  (See the discussion of let-statements in the other thread.)

    Waldemar


More information about the Es-discuss mailing list