lexical for-in/for-of loose end

Grant Husbands esdiscuss at grant.x43.net
Tue Feb 7 11:38:34 PST 2012

Andreas Rossberg wrote:
>>> let a = [], b = [], c = [], d = []
>>> for (int i = 0, f = function(){ return function() { ++i } }; i < 10;
>>> d[i] = function() { return i }, ++i) {
>>>  a[i] = f;
>>>  b[i] = f();
>>>  c[i] = function(){ return i }
>>> }
> But note that the environment in b's closures is not the for-loop
> environment. Instead, it is a local environment, whose parent is the
> for-loop environment. To make that case work, it is not enough to be
> able to modify the [[Scope]] environment of closures -- in general,
> you'd need to swap out arbitrary parts of an environment chain.

Indeed. I specified that operation as a recursive, constructive
operation, in something like spec-lingo, in one of my emails, and
pointed out that it is likely to introduce an extra indirection in
most JS engines, for at least some scopes, due to its assumptions
about envRec; I noted (and Brendan agreed) that such could be a major
problem. To recap, it looked like this (this time writing it as JS):
function ReplaceEnvInEnv(E, C) {
  if (E==C) return new Env(E.outer, E.envRec.clone());
  else return new Env(ReplaceEnvInEnv(E.outer, C), E.envRec);
(You would pass it the [[Scope]] of a closure in E and the loop
iteration scope in C and it would give you a new [[Scope]] for that

I'm hoping that someone knowledgeable about Chez Scheme's flat
closures will let us know about the similar detail of that and the

> This is not merely a question of complexity, though. It's more
> fundamental. Environments are immutable mappings from names to
> locations -- that's a basic axiom of lexical scoping.

Well, lexical scoping is scoping in which names refer to (more or
less) the local lexical environment. That is still true under the
proposal. It might indeed be desirable for the mapping to be
immutable, but I don't think that's a given. The above recursive
design does not require direct alteration of mappings.

> Breaking it will have unforeseeable consequences.

I'd agree with a phrasing like "Breaking it may have unforeseen consequences".

> That may be vague, I agree, but I
> prefer not to find out concretely. :)  Subtle combinations of
> higher-orderness and state rarely let you down in terms of nasty
> surprises.

I agree that this proposal may run up against some of the core values
and idioms of javascript and may want to be rejected for that reason;
in fact, I would probably currently vote against it, if I were asked
to participate in a vote. However, I'll continue to try to make sure
we're all on the same page as regards the potential design details and
workarounds, and hope not to bother people too much.


More information about the es-discuss mailing list