简体   繁体   English

无上下文语法定义中的可选与强制终止符

[英]Optional vs. mandatory terminators in context-free grammar definition

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 { } ? 如何为代码的最内侧while循环有效,而不{ } 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. 遗漏不是我的行为。

Your while statement says that after the ) comes a statement. 你同时声明说,以后)来声明。 Your grammar doesn't fully specify statement , but it doesn't require braces. 您的语法没有完全指定statement ,但它不需要大括号。 Braces are only needed for a statement sequence. 只有语句序列才需要大括号。

Consider your example code again: 再次考虑您的示例代码:

1 while (expression) {
2  statement;
3  statement;
4  while (expression) {
5   while(expression)
6      statement;
7   statement;
8  }
9 }

Why are you concerned that line 6 lacks braces, but don't care that lines 2, 3, and 7 are missing them too? 你为什么担心第6行没有括号,但是不在乎第2,3和7行也缺少它们? The grammar is saying that a while loop ends with a statement , and a statementSequence , with its required braces, is just one of many alternatives for a statement . 语法是说while循环以statement结束,而statementSequence及其必需的大括号只是statement的许多替代方案之一。 Lines 5 and 6 match that rule exactly—except for the ';' 第5行和第6行完全匹配该规则 - 除了';' , which doesn't have a place in the rule. ,在规则中没有位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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