For Loop Desugaring (was: return when desugaring to closures)

Jon Zeppieri jaz at bu.edu
Mon Oct 13 23:38:50 PDT 2008


On Mon, Oct 13, 2008 at 10:48 PM, Mark S. Miller <erights at google.com> wrote:
> On Mon, Oct 13, 2008 at 5:00 PM, Jon Zeppieri <jaz at bu.edu> wrote:
>> I'm talking about a rewrite from 'for' to
>> 'lambda' that satisfies the following properties:
>>
>> 1) for (var i = 0; i < len; i++) ... continues to mean what it means in ES3.
>> 2) for (let i = 0; i < len; i++) ... has the proper scope for 'i'
>> (which you reiterated above), *and* 'i' is rebound -- not mutated --
>> on each iteration.
>> 3) The rewrite rules are the *same,* regardless of whether it's a "for
>> (var ...)" or a "for (let ...)" loop.
>>
>> At least, that's what I took Mark to mean.  He can correct me if I'm wrong.
>
>
> You're right. However, the desugaring is more complex than I expected.
> Thanks for asking me to write it down.
>
>  for (<keyword> <varName> = <initExpr>; <testExpr>; <updateExpr>) { <body> }
>
> desugars to (hygienic  renaming aside):
>
> breakTarget: {
>  const loop = lambda(iter = <initExpr>) {
>    <keyword> <varName> = iter;
>    if (! <testExpr>) { break breakTarget; }
>    continueTarget: { <body> }
>    lambda(iter2 = <varName>) {
>      <keyword> <varName> = iter2;
>      <updateExpr>;
>      loop(<varName>);
>    }();
>  };
>  loop();
> }
>
> I believe this meets all your requirements.

I believe it does.  Very cool.  It won't handle the fully general
for(;;).  E.g.,

for (let fn = lambda(n) { ... fn(...) ... }; <testExpr>; <updateExpr>) ...

Also,

for (let i = 0, j = i + 1; ...) ...

But the modifications needed to make these work are pretty straightforward.


Then again, I'm not sure it matters.  I think the real problem here is
that the <updateExpr>, as written by the user, is (or, rather, usually
is) an assignment, and you should give the user what the user asked
for.

I also find it odd that

{
    let x = 0;
    for (; x < n; x++) ...
}

should have different behavior than

for (let x = 0; x < n; x++) ...


-Jon


More information about the Es-discuss mailing list