Operator Precedence Parsing
Operator precedence parsing is easily
done using auxiliary stacks for
operands and operators. Tokens are read and processed as follows:
reduce combines the two top operands and the top operator into
a subtree, which is pushed onto the operand stack.
- Operands: push onto the operand stack.
While prec(top-of-stack) ≥ prec(op) , reduce.
Push op onto the operator stack.
- (: Push ( onto the operator stack;
prec( ( ) < prec(any operator) .
- ): While top-of-stack ≠ (, reduce.
Then discard both parentheses.
- End: While operator stack is not empty, reduce.
Result is top of operand stack.
The = part of the ≥ test for operators implements left
associativity, the usual case. For right associativity, use >