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

后端 未结 3 507
旧时难觅i
旧时难觅i 2021-01-14 14:39

I\'m trying to parse this syntax:

34 + 1 − 8, 32 * 87 + 6 / 4, 34 / 8

I\'m expecting to ground it like this:

(, (- (+ 34 1)         


        
相关标签:
3条回答
  • 2021-01-14 15:16

    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
    
    0 讨论(0)
  • 2021-01-14 15:38

    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.

    0 讨论(0)
  • 2021-01-14 15:41

    You did not specify the priority of the operators like,

    %left '+' '-'
    
    %left '*' '/'
    
    (in definition section)
    

    Which can be the reason.

    0 讨论(0)
提交回复
热议问题