Search code examples
javascriptparsingbnf

JavaScript for-loop in BNF


I'm writing BNF for JavaScript which will be used to generate a lexer and a parser for the language. However, I'd like some ideas on how to design the for-loop. Here is the simplified version of my current BNF:

[...]
VarDecl. Statement ::= "var" Identifier "=" Expr ";"
ForLoop. Statement ::= "for" "(" Expr ";" Expr ";" Expr ")"
[...]

So as you can see, there are two statements in the example, variable declarations and for-loops. There are a bunch of different expressions, but none of the expressions are also statements.

The problem now is that this JavaScript code will not pass through the parser:

for (var x = 3; [...]; [...])

This is because a variable declaration is not an expression.

What are your ideas on how to solve this? I can think of a few ways, but I don't want to get in the way of your own thoughts, so I won't mention them here.


Solution

  • There are a few examples over the net, in an ANTLR ECMAScript grammar you can find this structure:

    iterationStatement:
    'do' statement 'while' LPAREN expression RPAREN SEMI
    | 'while' LPAREN expression RPAREN statement
    | 'for' LPAREN (
        (expressionNoln)? SEMI (expression)? SEMI (expression)? RPAREN statement
        | 'var' variableDeclarationListNoln SEMI (expression)? SEMI (expression)? RPAREN statement
        | leftHandSideExpression 'in' expression RPAREN statement   
        | 'var' variableDeclarationNoln 'in' expression RPAREN statement
        )
    ;