简体   繁体   中英

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.

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
    )
;

You should be able to put any "simple" statement there (ie vardecl, expression, void function call, etc) there. By simple I mean anything that isn't a compound statement (ie with additional curly-braces, such as if/else/for/function, etc).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM