Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bison - operator precedence

I have a question about operator precedence and associativity in Bison.

In every example I see the productions are like expr 'op' expr, for example :http://dinosaur.compilertools.net/bison/bison_8.html

But if I would use bison %leftand others associativity tools, and I would use grammar like:

  expr|     expr binop expr
      |     expr relop expr
      |     expr logical_op expr

and

 binop: '+' 
      | '-' 
      | '*' 
      | '/' 
      ;
 relop: EE
      | NE
      | LE
      | '<'
      | GE
      | '>'
      ;
 logical_op: AND
           | OR
           ;

would associativity and precedence rules be used?

Or do I need to write explicite expr 'op' expr for every operator?

I am asking, because when I try to use the grammar like the one I posted I get warnings about conflicts.

But when by hand I write productions like expr '+' expr I am not getting any warnings.

like image 421
Andna Avatar asked Mar 07 '26 17:03

Andna


2 Answers

For precedence rules to work, the terminal itself must appear in the ambiguous production. So you cannot group terminals into non-terminals and retain the ability to use precedence rules.

like image 53
rici Avatar answered Mar 09 '26 19:03

rici


I prefer to add grammar rules (productions) to account for operator precedence. See my answer here.

like image 35
David Gorsline Avatar answered Mar 09 '26 18:03

David Gorsline