Bison shift / reduce the problem by moving add op to subexpr

The original example was this

expr:
        INTEGER
        | expr '+' expr           { $$ = $1 + $3; }
        | expr '-' expr           { $$ = $1 - $3; }
        ;

I wanted this to be “simpler,” so I wrote this (I understand that it will do a “+” to add and subtract. But this is an example)

expr:
        INTEGER
        | expr addOp expr           { $$ = $1 + $3; }
        ;

addOp:
          '+' { $$ = $1; }
        | '-' { $$ = $1; }
        ;

Now I get a shift / decrease error. It should be the same -_- (for me). What do I need to do to fix this?

edit: To make everything clear. In the first case, there are no warnings / errors. I use% left to set priority (and I will use% right for = and other ops rights). However, this does not seem to apply to the transition to subexpressions.

+3
source share
2 answers

, ? , . , addOp .

( , ...: -):

$ cat q2.y
%% expr: '1' | expr '+' expr | expr '-' expr;
$ cat q3.y
%%  expr: '1' | expr addOp expr;
    addOp: '+' | '-';
$ yacc q2.y
conflicts: 4 shift/reduce
$ yacc q3.y
conflicts: 2 shift/reduce

, yacc- , , , , /. , , , , , .

, yacc, . :

$ cat q4.y
%% expr: expr addOp '1' | '1';
  addOp: '+' | '-';
$ yacc q4.y
$ 

: . , , :

 %expect 2
%%  expr: '1' | expr addOp expr;
    addOp: '+' | '-';
+1

,

expr: expr addOp expr { ..action.. }

. RHS, RHS. % prec:

expr: expr addOp expr %prec '+' { ..action.. }

.

, shift/reduce, . , , . , , , , - , .

.

+1

Source: https://habr.com/ru/post/1719184/


All Articles