Syntax Tree for
Operator Precedence Parser Part 3
We want the syntax tree (a.k.a. parse tree / AST structure) for the arithmetic expression
Key parsing principles that determine the tree shape:
- keywordOperator precedence dictates that multiplication/division bind tighter than addition/subtraction, and unary minus binds tighter than those binary operators.
- keywordAssociativity only matters when chaining operators of the same precedence (e.g., ), while parentheses and unary operators remove that ambiguity.2
- keywordParentheses force a subexpression to be formed before surrounding operators are applied.
From these rules, the structure is forced as:
- the subexpression is grouped due to parentheses,
- is grouped before due to higher precedence than ,
- the unary minus applies to the entire parenthesized result: ,
- finally, multiplication combines with the negated result: .2
Footnotes
-
Parsing Expressions by Recursive Descent - Precedence/associativity rules including parentheses, unary minus, and over unary minus and . ↩ ↩2 ↩3 ↩4
-
Precedence and associativity - Explains precedence vs associativity and grouping choices like . ↩
-
Precedence - Describes how precedence shapes the parse tree; unary operators bind tightly; parentheses force grouping. ↩
Build the syntax tree from highest-precedence pieces to lowest
- 1Step 1
Create a subtree for because parentheses must form a single grouped expression before outside operators are considered.
- 2Step 2
Within , make a child subtree of the node: the subtree becomes one operand of .
- 3Step 3
Make unary '-' a node whose child is the entire subtree, i.e., structure .
- 4Step 4
Create the root '*' node with left child and right child being the unary '-' subtree.
- 5Step 5
Confirm that the tree corresponds to evaluation order: first, then , then unary negation, then multiplication.
A convenient unambiguous grammar idea is to use separate nonterminals for precedence levels and a special production for unary minus, so the parse tree enforces precedence correctly. This matches the structure we derived: unary '-' applies to a “factor/expression” and binds tighter than /.2
We can represent the final syntax tree in a compact labeled form:
- Root:
- Right child: unary '-'
- Under unary '-':
- Under : left , right
- Under : and
Footnotes
-
Context-Free Grammars (CFG) — arithmetic + unary minus example - Shows how to modify grammars to enforce operator precedence and includes unary minus as highest precedence. ↩ ↩2
-
Parsing Expressions by Recursive Descent - Precedence/associativity rules including parentheses, unary minus, and over unary minus and . ↩
Operators ordered by binding strength (as used in this expression)
Higher precedence means the operator is lower in the tree (forms its subtree earlier).
Common pitfalls when drawing the tree
Knowledge Check
In the expression , which node must be the root of the syntax tree (with the usual arithmetic precedence rules)?