Sub topic 17
Syntax-Directed Translation Schemes and Semantic Action Placement
Assume you know context-free grammars, parse trees, and basic parsing. This chapter uses those ideas to attach actions to grammar rules. A syntax-directed translation scheme (SDT) is a grammar whose right-hand sides contain executable semantic actions. The parser performs an action when it reaches its position in the rule.
SDDs and SDT schemes
A syntax-directed definition (SDD) attaches attributes and equations to productions. For example:
E -> E1 + T { E.val = E1.val + T.val }
E -> T { E.val = T.val }
T -> digit { T.val = digit.lexval }Here, val is a synthesized attribute. It moves information upward from children to their parent. The equations describe what the result should be, but they do not by themselves specify exactly when the computation runs.
An SDT places actions directly inside production bodies:
E -> E + T { print("+") }
T -> T * F { print("*") }
F -> digit { print(digit.lexval) }The action runs when the parser reaches it. With a bottom-up parser, actions at the right end of productions usually run when the production is reduced. This placement naturally produces postfix output.
For the input 2 + 3 * 4, the output is:
2 3 4 * +The multiplication action runs before the addition action because the grammar gives multiplication a deeper subtree.
Choosing action placement
Action placement must match the parser and the attributes used.
| Goal | Common placement | Reason |
|---|---|---|
| Compute a synthesized value | End of a production | All child values are available |
| Print a token before a later subtree | Before that subtree | The action must run first |
| Pass inherited information | Before the symbol that uses it | The value must be available during that symbol's expansion |
| Build a parent node | End of a production | Child nodes have already been built |
For example, an action that prints postfix code belongs after the operands:
E -> E + T { print("+") }Putting the action before E + T would print + before its operands, producing prefix-like output instead.
A top-down recursive-descent parser executes actions as it enters a production or reaches a statement. A bottom-up parser executes an action according to the reduction point. Therefore, translating an SDT from one parsing strategy to another may require moving or restructuring actions.
Common errors
- Printing an operator before its operands when postfix output is required.
- Using an inherited value before an earlier action has computed it.
- Assuming every parser executes actions at the same time.
- Ignoring side effects when rearranging grammar productions.
Exercise
Where should the action that prints * appear in T -> T * F when generating postfix notation, and why?
Show answer
It should appear after F, because both operands must be printed before the multiplication operator.