Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top