我正在使用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
的定义含糊不清。
我发现this article描述了如何在不引入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 ;
可悲的是,CUP抱怨如下:
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.
为什么这不起作用?我该如何解决?
答案 0 :(得分:1)
此处的问题是if
语句与while
语句之间的互动,如果您从while
删除non-if-statement
语句,则可以看到。
问题是while
语句的目标可以是if
语句,而while
语句可以在另一个then
语句中if
。 1}}声明:
IF expression THEN WHILE expression IF expression THEN statement ELSE ...
现在我们对原始问题的表现略有不同:最后的else
可能是嵌套if
或外if
的一部分。
解决方案是扩展受限语句(链接条款中的“then-statements”)之间的区别,还包括两种不同的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
循环),则必须为每个语句执行相同的操作。