Sub topic 18
Applications: Expression Evaluation, Postfix Output, and Syntax Trees
Assume you know context-free grammars, parse trees, and basic recursive-descent or shift-reduce parsing. This chapter shows how semantic actions attach meaning to a parse.
A parser recognizes structure. A syntax-directed translation also computes a result, emits code, or builds a tree. The grammar supplies the order of operations, while attributes or actions carry information through that structure.
Expression evaluation with attributes
Consider this grammar:
E -> E + T
E -> T
T -> T * F
T -> F
F -> ( E )
F -> digitThe grammar gives multiplication higher precedence than addition because T must be completed before an E addition is reduced.
A syntax-directed definition adds semantic rules:
E -> E1 + T { E.val = E1.val + T.val }
E -> T { E.val = T.val }
T -> T1 * F { T.val = T1.val * F.val }
T -> F { T.val = F.val }
F -> ( E ) { F.val = E.val }
F -> digit { F.val = digit.lexval }Here, val is a synthesized attribute. It moves from children to their parent. For 2 + 3 * 4, the parse first computes 3 * 4, then computes 2 + 12, producing 14.
Producing postfix notation
A translation scheme places actions directly inside production bodies. For postfix output, print an operator after translating both operands:
E -> E + T { print('+') }
E -> T
T -> T * F { print('*') }
T -> F
F -> ( E )
F -> digit { print(digit.lexval) }For 2 + 3 * 4, the output is:
2 3 4 * +Postfix notation needs no parentheses because each operator follows its operands. The parse structure determines the output order.
Building a syntax tree
A syntax tree, often called an abstract syntax tree (AST), keeps the essential structure while removing grammar-only nodes such as E, T, and parentheses.
| Input fragment | AST node |
|---|---|
| `2 + 3` | `Add(Number(2), Number(3))` |
| `3 * 4` | `Mul(Number(3), Number(4))` |
| `(2 + 3)` | `Add(Number(2), Number(3))` |
A semantic action can construct these nodes:
def add(left, right):
return ("add", left, right)
def mul(left, right):
return ("mul", left, right)
def number(value):
return ("number", value)
tree = add(number(2), mul(number(3), number(4)))
print(tree)
# ('add', ('number', 2), ('mul', ('number', 3), ('number', 4)))The same tree can support several later operations:
- Evaluate it by recursively computing child values.
- Print postfix by visiting children before the operator.
- Generate machine code by emitting instructions for each node.
- Optimize it by replacing constant subtrees with their results.
Exercise
What postfix string should the translation scheme produce for 2 * (3 + 4)?
Show answer
2 3 4 + *