我正在用CUP构建语法,我在定义IF-THEN-ELSE语句时遇到了障碍。
我的代码看起来像这样:
start with statements;
/* Top level statements */
statements ::= statement | statement SEPARATOR statements ;
statement ::= if_statement | block | while_statement | declaration | assignment ;
block ::= START_BLOCK statements END_BLOCK ;
/* Control statements */
if_statement ::= IF expression THEN statement
| IF expression THEN statement ELSE statement ;
while_statement ::= WHILE expression THEN statement ;
但是CUP工具抱怨if_statement
定义的歧义。
我发现这篇文章描述了如何在不引入endif
令牌的情况下消除歧义。
所以我尝试调整他们的解决方案:
start with statements;
statements ::= statement | statement SEPARATOR statements ;
statement ::= IF expression THEN statement
| IF expression THEN then_statement ELSE statement
| non_if_statement ;
then_statement ::= IF expression THEN then_statement ELSE then_statement
| non_if_statement ;
// The statement vs then_statement is for disambiguation purposes
// Solution taken from http://goldparser.org/doc/grammars/example-if-then-else.htm
non_if_statement ::= START_BLOCK statements END_BLOCK // code block
| WHILE expression statement // while statement
| declaration | assignment ;
可悲的是,银联抱怨如下:
Warning : *** Reduce/Reduce conflict found in state #57
between statement ::= non_if_statement (*)
and then_statement ::= non_if_statement (*)
under symbols: {ELSE}
Resolved in favor of the first production.
为什么这不起作用?我该如何解决?
这里的问题是if
语句和while
语句之间的交互,如果从non-if-statement
中删除while
语句生成,您可以看到这一点。
问题在于,while
语句的目标可以是if
语句,并且该语句while
可以在另一个if
语句的then
子句中:
IF expression THEN WHILE expression IF expression THEN statement ELSE ...
现在我们对原始问题的表现略有不同:末尾的else
可能是嵌套if
或外部if
的一部分。
解决方案是扩展受限语句(链接术语中的"then-statement"(之间的区别,以包括两种不同类型的while
语句:
statement ::= IF expression THEN statement
| IF expression THEN then_statement ELSE statement
| WHILE expression statement
| non_if_statement ;
then_statement ::= IF expression THEN then_statement ELSE then_statement
| WHILE expression then_statement
| non_if_statement ;
non_if_statement ::= START_BLOCK statements END_BLOCK
| declaration | assignment ;
当然,如果您扩展语法以包含其他类型的复合语句(例如for
循环(,则必须对它们中的每一个执行相同的操作。