Where are the shift/reduce conflicts in this Bison code coming from?

依然范特西╮ 提交于 2019-12-01 08:15:15

The problem is with your definition of term:

term: NUMBER | term op term ;

When parsing this, at each number, the question is: should I read another token to know if I have the first, or the second form.

A solution could be to define:

term: NUMBER reminder;
reminder: /* empty */ | op term;

The grammar, once adapted, looks like the following:

%token NUMBER
%token COMMA
%token OPERATOR
%left OPERATOR
%left COMMA
%%

term: NUMBER reminder;
reminder: /* empty */ | op term;
op: OPERATOR | COMMA;
%%

compiles without warnings with bison (GNU Bison) 2.4.1.

To find where the conflicts are, use the --verbose option and look at the file example.output where your input file is example.y. Here is the file I got from your input:

State 7 conflicts: 2 shift/reduce

(omitted)

state 7

    2 term: term . op term
    2     | term op term .

    COMMA     shift, and go to state 4
    OPERATOR  shift, and go to state 5

    COMMA     [reduce using rule 2 (term)]
    OPERATOR  [reduce using rule 2 (term)]
    $default  reduce using rule 2 (term)

    op  go to state 6

You might not have specified the priority of the operators like,

%left '+' '-'

%left '*' '/'

(in definition section)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!