上下文无关语法定义中的可选终止符与强制终止符
在有关编译器的书籍章节中,有以下语法定义和示例代码。
...
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;
}
}
如果没有 {
}
,代码最内部的 while
循环如何有效?在我看来,语句定义需要它们。这是书中的错误还是我误解了语法?
[编辑] 对于任何含糊之处,我深表歉意。上面输入的所有内容都是逐字逐句摘自书中的。这些遗漏不是我造成的。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
再次考虑您的示例代码:
为什么您担心第 6 行缺少大括号,但不关心第 2、3 和 7 行也缺少大括号?语法说
while
循环以statement
结束,而statementSequence
及其所需的大括号只是许多替代方案之一一个声明
。第 5 行和第 6 行与该规则完全匹配,但';'
除外,它在规则中没有位置。Consider your example code again:
Why are you concerned that line 6 lacks braces, but don't care that lines 2, 3, and 7 are missing them too? The grammar is saying that a
while
loop ends with astatement
, and astatementSequence
, with its required braces, is just one of many alternatives for astatement
. Lines 5 and 6 match that rule exactly—except for the';'
, which doesn't have a place in the rule.您的 while 语句表示在
)
之后是一个语句。您的语法没有完全指定statement
,但它不需要大括号。仅语句序列需要大括号。Your while statement says that after the
)
comes a statement. Your grammar doesn't fully specifystatement
, but it doesn't require braces. Braces are only needed for a statement sequence.