return when desugaring to closures

Brendan Eich brendan at
Mon Aug 25 16:33:47 PDT 2008

On Aug 25, 2008, at 4:10 PM, Mark S. Miller wrote:

> are shallow generators
> implementable by a local cps transform?

Yes, the local evaluation (inside the generator function) is the only  
place that needs to be CPS'ed to allow yield in any expression or  
statement context.

> This approach would seem relevant to adding generators by adding new
> semantic state. But would it help us understand how to add generators
> by a local code transformation?

Why does this matter? Changing any future ES spec to use CPS is a  
semantic state shift, and a very big one. The plan (designed and  
implemented by Dave) for specifying generators in ES4 was to use  
delimited continuations in the SML reference implementation.

It's not pretty, but you can CPS-convert generators. Here's a  
concrete "desugaring" ("souring"? :-P) example based on JS1.7, not  
ES4 (no iterator namespace, ugly __iterator__ name instead):

function simple_range(n) {
     for (let i = 0; i < n; i++)
         yield i;

function simple_range(n) {
     let i = 0;
     return {
         __iterator__: function () {
             return {
                 next: function () {
                     if (i == n)
                         throw StopIteration;
                     return i++;

Object.freeze on the returned iterator object omitted ;-). Adding  
send, throw, and close also left as an exercise.


More information about the Es-discuss mailing list