If statement 如果是,那么杯子里的模棱两可
我正在CUP中构建语法,在定义IF-THEN-ELSE语句时遇到了障碍 我的代码如下所示:If statement 如果是,那么杯子里的模棱两可,if-statement,grammar,ambiguous-grammar,cup,If Statement,Grammar,Ambiguous Grammar,Cup,我正在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 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_声明定义的模糊性
我发现了如何在不引入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.
为什么这不起作用?如何修复它?这里的问题是if语句和while语句之间的交互,如果从非if语句中删除while语句,您可以看到这一点 问题在于while语句的目标可以是if语句,而while语句则可以位于另一个if语句的then子句中:
IF expression THEN WHILE expression IF expression THEN statement ELSE ...
现在我们对原始问题有了一个稍微不同的表现形式:末尾的else可能是嵌套if或外部if的一部分
解决方案是扩展链接中受限语句与非受限语句之间的区别,以包括两种不同类型的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循环,那么您将不得不对它们中的每一个执行相同的操作