[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Operator precedence

> Has anyone got any quick tips on implementing several layers
> of operator precedence?

Yep. In fact, the LALR(1) Java grammar is a very good example of this. It
shows you how to specify (1) multiple layers of precedence and (2) left
precedence of an operator.

Here's the general pattern for binary operators.

Assume that you want the following:

Lowest precedence:
  op1 and op2. Left associative.
  (e.g. exp op1 exp op1 exp = (exp op1 exp) op1 exp.
Intermediate precedence:
  op3 and op4. Right associative.
  (e.g. exp op3 exp op4 exp = exp op3 (exp op4 exp).
Highest precedence:
  op5 and op6. Left associative.

low/high: exp op1 exp op5 exp = exp op1 (exp op5 exp)

Then you can use the following grammar:

primary =
  {id} identifier |
  {const} constant |
  {parentheses} l_par lowest r_par;

lowest =
  {intermediate } intermediate |
  {left_op1} lowest op1 intermediate |
  {left_op2} lowest op2 intermediate;

intermediate =
  {highest} highest |
  {right_op3} highest op3 intermediate |
  {right_op4} highest op4 intermediate;

highest =
  {primary} primary |
  {left_op5} highest op5 primary |
  {left_op6} highest op6 primary;

I hope this answers your question.