10.4. Precedence and Associativity


Precedence and associativity of tokens

Use %left, %right and %nonassoc instead of %token to declare precedence and associativity of tokens. Lines

%left     TOK_FROG
%right    TOK_TOAD
%nonassoc TOK_SALAMANDER
tell Bison that

Precedence is from low to high, in the order written. So the above lines indicate that TOK_SALAMANDER has highest precedence, then TOK_TOAD, and TOK_FROG has the lowest precedence.

You can declare a few tokens to have the same precedence and associativity. For example,

%left '+' '-'
defines '+' and '-' to have the same precedence, and left-associativity.


Precedence and associativity of productions

By default, the precedence of a production is the same as the precedence of the first token on its right-hand side, if there is one.

If you want to choose your own precedence, follow the production by

  %prec t
where t is a token. For example,
expression : expression '-' expression
             %prec '+'
defines a production whose precedence and associativity are the same as for token '+'.