views:

238

answers:

2

In a book chapter about compilers, there's the following grammar definition and example code.

...
statement: whileStatement
           | ifStatement
           | ... // Other statement possibilities
           | '{' statementSequence '}'
whileStatement: 'while' '(' expression ')' statement
ifStatement: ... // Definition of "if"
statementSequence: '' // empty sequence (null)
                   | statement ';' statementSequence
expression: ... // Definition of "expression"
...             // More definitions follow

 

while (expression) {
 statement;
 statement;
 while (expression) {
  while(expression)
     statement;
  statement;
 }
}

How is the code's inner-most while loop valid without { }? It looks to me that the statement definition requires them. Is this a mistake in the book or am I misunderstanding the syntax?


[Edit] My apologies for any ambiguity. Everything typed above is verbatim from the book. The omissions were not my doing.

+2  A: 

Your while statement says that after the ) comes a statement. Your grammar doesn't fully specify statement, but it doesn't require braces. Braces are only needed for a statement sequence.

Ned Batchelder
Never the less it appears to be a small mistake in the book. The missing possibilities for 'statement' could not include 'statement' itself, it would have to be 'simple_statement' or the like the example would have to use this rather that just 'statement'.
mjv
Well, there's a huge ambiguity here in the first place: In the code sample, what does the token "statement" even mean? I assumed it meant: some uninteresting line that matches statement.
Ned Batchelder
You're absolutely correct. Thanks!
Dinah
+1  A: 
erickson
Ah! You're so right. I was focused on the fact that the only statement other than if and while used { } and ignoring that if "statement;" can be a self-contained placeholder in lines 2, 3, 7 then why not 6?
Dinah