4

My grammar has these two token declarations:

%token RP
%token ELSE

And these two rules:

Statement  : IF LP Exp RP Statement;

Statement  : IF LP Exp RP Statement ELSE Statement;

From what I understand, a rule's priority is determined by the priority of its last nonterminal. Therefore, the first rule has RP priority and the second rule has ELSE priority which is higher than RP. Below is bison's output:

state 73

   11 Statement: IF LP Exp RP Statement .
   12          | IF LP Exp RP Statement . ELSE Statement

    ELSE  shift, and go to state 76

    ELSE      [reduce using rule 11 (Statement)]
    $default  reduce using rule 11 (Statement)

Shouldn't this conflict be solved by shifting since ELSE has higher priority ?

4

2 回答 2

7

不,因为%token没有设置令牌的优先级(你称之为优先级)——它声明令牌以无优先级存在。如果要声明令牌的优先级,则需要使用%left%right%nonassoc所有这些都声明令牌并设置其优先级。如果您将代码更改为

%nonassoc RP
%nonassoc ELSE

thenRPELSE将有它们的优先级,并且ELSE将具有更高的优先级,并且 shift/reduce 冲突将按优先级解决。

于 2013-06-09T19:35:33.153 回答
1

你应该看看这个答案,if/else 歧义是一种非常常见的语言模式,它在 Bison 和 Yacc 的手册、龙书和互联网上的几个教程中都有处理,比如这个

由于 ELSE 具有更高的优先级,不应该通过转移来解决这个冲突吗?

正如另一个答案中所说,确实如此。野牛自动换档解决了冲突,它会告诉你。它确实选择了 IF ELSE,如果你添加%expect声明,它不会警告你它“自动”做了一些事情。

于 2013-06-09T14:04:06.687 回答