Sub topic 23
Applications: expression evaluation, postfix output, and syntax trees
This chapter assumes you know context-free grammars, LR and LL(1) parsing, and the difference between synthesized and inherited attributes. It applies those ideas to three standard uses of syntax-directed translation (SDT): computing a value, emitting postfix code, and building a syntax tree. Each use is a different semantic action attached to the same expression grammar.
The common setting
All three applications use the grammar of arithmetic with + and *, where * binds tighter and both operators are left associative.
E -> E + T | TT -> T * F | FF -> ( E ) | digit
This grammar is left recursive, so it suits bottom-up (LR) parsing. A top-down parser needs the left-recursion-free form from the earlier chapter. Where the grammar goes decides where the actions can go, so we treat the two cases separately.
Application 1: evaluating an expression
The grammar is S-attributed when every attribute is synthesized. Here every nonterminal has one attribute, val, computed from its children.
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 }An LR parser evaluates this on the fly. It keeps a value stack parallel to the state stack. When it reduces by T -> T1 * F, the top three value slots hold T1.val, the * token, and F.val. The parser pops them and pushes T.val. No tree is stored.
For 2 + 3 * 4, the reductions happen in this order: F -> 2, T -> F, E -> T, then F -> 3, F -> 4, T -> T * F (value 12), and finally E -> E + T (value 14). Multiplication is reduced before addition because the parser can only reduce E + T once the T on its right is complete, and T absorbs the *.
Evaluating top-down
After left-recursion removal, the value depends on something already seen to the left. That needs an inherited attribute. The grammar is then L-attributed rather than S-attributed.
E -> T { E'.inh = T.val } E' { E.val = E'.syn }
E' -> + T { E'1.inh = E'.inh + T.val } E' { E'.syn = E'1.syn }
E' -> ε { E'.syn = E'.inh }The inh value carries the running total down the tree, and the syn value carries the final answer back up. The recursive descent parser from the earlier chapter does exactly this by passing inh as a function argument and returning the result.
Application 2: postfix output
Postfix (reverse Polish) notation writes each operator after its operands, so it needs no parentheses and no precedence rules. For 2 + 3 * 4 the postfix form is 2 3 4 * +.
There are two ways to produce it. Both give the same output.
- Attribute approach. Give each nonterminal a string attribute
code, withE.code = E1.code || T.code || '+'. This is correct but copies strings. - Translation scheme approach. Put print actions in the grammar. Because each operator is printed after both operands have been recognized, the action sits at the right end of the production body.
E -> E + T { print('+') }
E -> T
T -> T * F { print('*') }
T -> F
F -> ( E )
F -> digit { print(digit.lexval) }The scheme works because the actions run in the order of a depth-first, left-to-right traversal of the parse tree. Operands are printed as the parser finishes them, and the operator follows both.
The next program does the same job as the scheme with a small hand-written parser. It rewrites the left recursion as loops, which preserves left associativity.
def to_postfix(tokens):
toks = list(tokens) + ["$"]
pos = 0
out = []
def peek():
return toks[pos]
def advance():
nonlocal pos
pos += 1
def expr():
term()
while peek() == "+":
advance()
term()
out.append("+")
def term():
factor()
while peek() == "*":
advance()
factor()
out.append("*")
def factor():
t = peek()
if t == "(":
advance()
expr()
if peek() != ")":
raise SyntaxError("expected ')'")
advance()
elif isinstance(t, int):
out.append(str(t))
advance()
else:
raise SyntaxError(f"unexpected token {t!r}")
expr()
if peek() != "$":
raise SyntaxError(f"extra input {peek()!r}")
return " ".join(out)
print(to_postfix([2, "+", 3, "*", 4]))
print(to_postfix(["(", 2, "+", 3, ")", "*", 4]))The output is 2 3 4 * + and then 2 3 + 4 *. The parentheses change the postfix output only through the order in which the parser finishes each subexpression.
Application 3: building syntax trees
A syntax tree keeps only the operators and operands. It drops the chain nonterminals such as E -> T and the parentheses. Each node is built by a function call in the action.
E -> E1 + T { E.node = mknode('+', E1.node, T.node) }
E -> T { E.node = T.node }
T -> T1 * F { T.node = mknode('*', T1.node, F.node) }
T -> F { T.node = F.node }
F -> ( E ) { F.node = E.node }
F -> digit { F.node = mkleaf(digit.lexval) }For 2 + 3 * 4 this builds + at the root, with leaf 2 as its left child and a * node as its right child. That * node has leaves 3 and 4.
Reading this tree in postorder (left subtree, right subtree, then node) gives 2 3 4 * +. The postfix output is therefore a postorder walk of the syntax tree, and the evaluation order is the same walk with values computed.
Comparing the three applications
| Application | Attribute kind | Where actions go | Result |
|---|---|---|---|
| Evaluation (bottom-up) | Synthesized only | End of each body | A number |
| Evaluation (top-down) | Inherited and synthesized | Before and after nonterminals | A number |
| Postfix output | None (side effects) | End of each body | A string of tokens |
| Syntax tree | Synthesized pointer | End of each body | A tree of nodes |
Common errors on GATE questions
- Wrong associativity after left-recursion removal. The rewritten grammar
E' -> + T E'is right recursive, but the tree must still be left associative. Passing the accumulated value through an inherited attribute restores this. For subtraction,8 - 3 - 2must give 3, not 7. - Counting print order. When actions sit at the end of bodies, tracing is a postorder walk. Write the parse tree first and then walk it.
- Mid-body actions in S-attributed schemes. An S-attributed definition has only synthesized attributes. It can always be turned into a scheme with the actions at the right ends.
- Confusing the syntax tree with the parse tree. The parse tree for
2 + 3 * 4has manyE,T, andFnodes. The syntax tree has five nodes.
Exercise
A bottom-up translation scheme has E -> E + T { print('+') }, E -> T, T -> T * F { print('*') }, T -> F, F -> ( E ), and F -> digit { print(digit.lexval) }. What does it print for the input 1 * 2 + 3 * 4?
Show answer
It prints 1 2 * 3 4 * +. The parse groups the input as (1 * 2) + (3 * 4). Each * is printed after its two operands, and the + is printed last, after both products.
Exercise
For the left-recursion-free evaluation scheme, trace E'.inh and E'.syn for the input 2 + 3 + 4.
Show answer
T.val is 2, so the first E' has inh = 2. After reading + 3, the second E' has inh = 5. After reading + 4, the third E' has inh = 9. The third E' derives ε, so its syn is 9. That value is passed back up through each E'.syn, and E.val is 9.
Exercise
Give the postfix form of (a + b) * (c + d) and say how many nodes its syntax tree has, counting leaves.
Show answer
The postfix form is a b + c d + *. The syntax tree has 7 nodes: three operator nodes (* and two +) and four leaves. Parentheses leave no nodes in the tree.