0

我正在 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 ;

可悲的是,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. 

为什么这不起作用?我如何解决它?

4

1 回答 1

1

if这里的问题是语句和语句之间的交互while,如果whilenon-if-statement.

问题是语句的目标while可以是一个if语句,然后该while语句可能在then另一个if语句的子句中:

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循环),您将不得不对它们中的每一个执行相同的操作。

于 2018-04-30T17:22:42.363 回答