views:

321

answers:

2

Hi

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.

A: 

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

Marcus Lindblom
+1  A: 

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