冲突野牛解析器

Conflict Bison parser

我是 Bison 的新手,我遇到了 shift/reduce 冲突问题...

我在写C语言的语法规则:ID是标识一个变量的token,我写这个规则是为了保证标识符即使写在括号里也能被考虑。

id              : '(' ID ')'    {printf("(ID) %s\n", );}
                |     ID        {printf("ID %s\n", );}
                ;

Bison 冲突的输出是:

State 82

   12 id: '(' ID . ')'
   13   | ID .

    ')'  shift, and go to state 22

    ')'       [reduce using rule 13 (id)]
    $default  reduce using rule 13 (id)

我该如何解决这个冲突?

希望我说清楚了,感谢您的帮助。

您的 id 规则本身不会导致 shift/reduce 错误。在您的语法中必须有一些其他规则使用 ID。例如,您有一个表达式规则,例如:

expr: '(' expr ')'
    | ID
    ; 

在上面的示例中,ID 可以缩减为 idexpr 并且解析器不知道要进行哪种缩减。检查状态 22 中的内容。


编辑:你问“我能做些什么来解决冲突?

I'm writing the rules for grammar for the C language: ID is a token that identifies a variable, and I wrote this rule to ensure that the identifier can be considered even if it is written in parentheses

括号中作为左边的变量在C中是无效的,只能出现在右边。然后你可以认为它是一个表达式,所以只需删除你的规则,并将你使用 id 的地方替换为 expr.