To resolve shift/reduce conflicts in expression grammars, define a precedence variable in your grammar file. This allows you to assign precedence levels and associativity (left, right, or nonassoc) to tokens.
Tokens are ordered from lowest to highest precedence within the declaration. The precedence of a grammar rule is determined by the precedence of its right-most terminal symbol.
Associativity rules:
- left: The rule is reduced if the current token and the rule have the same precedence.
- right: The token is shifted if the current token and the rule have the same precedence.
- nonassoc: Prevents chaining of operators (e.g.,
a < b < c will trigger a syntax error).
precedence = (
('nonassoc', 'LESSTHAN', 'GREATERTHAN'),
('left', 'PLUS', 'MINUS'),
('left', 'TIMES', 'DIVIDE'),
('right', 'UMINUS'),
)