Generator issue: exceptions while initializing arguments

Allen Wirfs-Brock allen at wirfs-brock.com
Sat Sep 8 16:36:22 PDT 2012


On Sep 8, 2012, at 3:59 PM, Brendan Eich wrote:

> Here's an attempt at a crucial experiment:
> 
> js> var g = 'now'
> js> function f(a = g) { yield a; }
> js> var it = f()
> js> g = 'later'
> "later"
> js> it.next()
> "later"
> 
> So I'm wrong, SpiderMonkey inserts the impliciti |yield;| before parameter defaulting. Rats.
> 
> It may not matter, but I still think early beats late. That Python binds in the definition context may still be relevant, even though Python evaluates parameter default values at function definition evaluation time (way early), insofar as translating the above to Python:
> 
> Python 2.6.6 (r266:84292, May 28 2011, 19:08:00)
> [GCC 4.2.1 (Apple Inc. build 5664)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
> >>> g = 'now'
> >>> def f(a = g):
> ...   yield a
> ...
> >>> it = f()
> >>> g = 'later'
> >>> it.next()
> 'now'
> 
> does indeed result in 'now'.

I think early beats late and that this concept extends to include any code within the generator function that is involved in setting up the initial state of the generator.   For example, it seems quite reasonable for somebody to try to write something like:

function *dataSnapshot(aCollection) {
   snapshot = aCollection.captureCurrentState();
   //initialization complete
   for (let i=0; i<snapshot.length; i++) yield snapshot[i]
   throw StopIteration;
}
...

lets snappedItr= dataSnapshot(myData);
...
...
myData.doABunchOfUpdates();
...
...
for (let d of snappedItr)  {/* look at old data */}
...

Unfortunately, they will see the new updated data not the old data when they iterate.
What they need is the ability to move the implicit "initialization is complete" yield from the beginning of the body  to the point of the comment I provided.  We don't have a way to do that and , of course, if we did it would complicate things and probably create other ways to mess things up.  The only reason approach that I've come up would be to treat a yield without an associated expression as the initialization complete marker:

function *dataSnapshot(aCollection) {
   snapshot = aCollection.snapState();
   yield;
   //initialization complete
   for (let i=0; i<snapshot.length; i++) yield snapshot[i]
   throw StopIteration;
}


The semantics would probably be if the body does not contain such a yield, then one is auto generated at the top of the function body. So the default would be "late" (possibly include the arguments) but it could be explicitly make "early" to an arbitrary point in the body. 

Allen




More information about the es-discuss mailing list