For Loop Desugaring (was: return when desugaring to closures)
Mark S. Miller
erights at google.com
Mon Oct 13 19:48:01 PDT 2008
On Mon, Oct 13, 2008 at 5:00 PM, Jon Zeppieri <jaz at bu.edu> wrote:
>>> Mark said that there was a desugaring for 'for' to 'lambda,' without
>>> special cases, where this all works out, but I haven't been able to
>>> figure out what rewrite he had in mind.
>
> That's not the point. 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. However, in contradiction
to my original claim, one couldn't usefully say "const" instead of
"let" with a for(;;) loop.
--
Cheers,
--MarkM
More information about the Es-discuss
mailing list