Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bison precedence is useless? it doesn't work

I have declared such precedence for bison :

    %left '+' '-'
    %left '*' '/'

Recursive rules for arithmetic:

exp:       exp binary_op exp { .. }
           | literal_exp     { .. }
           | ID              { .. }

binary_op: '+'               { .. }
           | '-'             { .. }
           | '*'             { .. }
           | '/'             { .. }

I have an arithmetic expression: 10 * 3 + 5

My program calculates the sum, and it's 80! I still don't know why precedence doesn't work.

like image 554
inaumov17 Avatar asked Dec 20 '13 20:12

inaumov17


1 Answers

It should work if you define the expressions like this:

exp:       exp '+' exp       { .. }
           exp '-' exp       { .. }
           exp '*' exp       { .. }
           exp '/' exp       { .. }
           | literal_exp     { .. }
           | ID              { .. }

The precedence only works when the operators are present as terminals in the rule.

See the documentation on How precedence works:

each rule gets its precedence from the last terminal symbol mentioned in the components

Your rule for exp has no terminals, hence no precedence is applied.

like image 80
Peter de Rivaz Avatar answered Nov 10 '22 19:11

Peter de Rivaz