What do you think of this generator syntax?

Posted by ChaosPandion on Programmers See other posts from Programmers or by ChaosPandion
Published on 2011-01-29T23:30:40Z Indexed on 2011/01/30 7:31 UTC
Read the original article Hit count: 609

Filed under:
|
|

I've been working on an ECMAScript dialect for quite some time now and have reached a point where I am comfortable adding new language features. I would love to hear some thoughts and suggestions on the syntax.

Example

generator {
    yield 1;
    yield 2;
    yield 3;
    if (true) {
        yield break;
    }
    yield continue generator {
        yield 4;
        yield 5;
        yield 6;
    };
}

Syntax

GeneratorExpression:
    generator  {  GeneratorBody  }

GeneratorBody:
    GeneratorStatementsopt

GeneratorStatements:
    StatementListopt GeneratorStatement GeneratorStatementsopt

GeneratorStatement:
    YieldStatement
    YieldBreakStatement
    YieldContinueStatement

YieldStatement:
    yield  Expression  ;

YieldBreakStatement:
    yield  break  ;

YieldContinueStatement:
    yield  continue  Expression  ;

Semantics

The YieldBreakStatement allows you to end iteration early. This helps avoid deeply indented code. You'll be able to write something like this:

generator {
    yield something1();
    if (condition1 && condition2) 
        yield break;
    yield something2();
    if (condition3 && condition4) 
        yield break;
    yield something3();
}

instead of:

generator {
    yield something1();
    if (!condition1 && !condition2) {
        yield something2();
        if (!condition3 && !condition4) {
            yield something3();
        }
    }
}

The YieldContinueStatement allows you to combine generators:

function generateNumbers(start) {
    return generator {
        yield 1 + start;
        yield 2 + start;
        yield 3 + start;
        if (start < 100) {
            yield continue generateNumbers(start + 1);
        }
    };
}

© Programmers or respective owner

Related posts about syntax

Related posts about iterator