Sub topic 22
Syntax-directed translation schemes and semantic action placement
This chapter assumes you know the following:
- Context-free grammars and parse trees.
- FIRST and FOLLOW sets.
- LL(1) and LR parsing at the level of the earlier chapters.
- Synthesized and inherited attributes, and the S-attributed and L-attributed classes.
From definition to scheme
A syntax-directed definition (SDD) states what each attribute equals and leaves the evaluation order open. A syntax-directed translation (SDT) scheme fixes the order. It is a grammar whose production bodies contain semantic actions, which are code fragments in braces. An action runs at the moment the parser reaches its position in the body.
E' -> + T { print('+') } E'Here the parser matches +, parses T, runs the print, and then parses E'. Moving the action elsewhere in the body changes the output, so placement is part of the scheme's meaning.
Where actions may go
In an SDD, a rule such as A.s = B.x can be evaluated whenever its inputs are ready. In a scheme, the position of the action must guarantee that its inputs are ready. For L-attributed definitions the rules are:
| Attribute | Where its action goes |
|---|---|
| Inherited attribute of a body symbol X | Immediately before X, and after every symbol whose attributes it uses |
| Synthesized attribute of the head | At the right end of the body, after all the attributes it uses |
| Synthesized attribute of a body symbol | Computed inside that symbol's own production |
An action may use the inherited attributes of the head, and attributes of symbols to its left. It must not use any attribute of a symbol to its right, and it must not use a synthesized attribute of the symbol it precedes.
Valid: D -> T { L.in = T.type } L
Invalid: A -> { A.s = B.x } BThe second scheme reads B.x before B has been parsed. This is the most common placement mistake in GATE questions.
Postfix SDT
If every action sits at the right end of its production, the scheme is a postfix SDT. S-attributed definitions convert directly to this form.
A bottom-up parser executes each action when it reduces by that production. The parser keeps attribute values on its stack next to the grammar symbols. At a reduction by A -> X Y Z { action }, the values of X, Y and Z are the top three stack entries. The action reads them, and the result replaces them as the value of A.
For the left-recursive grammar E -> E + T { print('+') } | T, the input 2 + 3 * 4 yields 2 3 4 * +. The + is printed only after both operands have been translated, because the reduction happens after both subtrees are complete.
Actions in the middle of a body
When an action is in the middle of a body, the parser must run it before it has seen the rest. A top-down parser does this naturally, because it expands the body from left to right. A bottom-up parser does not know which production it is in until the reduction. The standard fix is a marker nonterminal, which is an empty production that carries the action.
Original: A -> X { act } Y
Rewritten: A -> X M Y
M -> ε { act }Now the action sits at the right end of M -> ε, so it is postfix. A marker can introduce LR conflicts, because the parser must decide to reduce M before it sees the following input. This is one reason inherited attributes are harder to handle bottom-up.
Translating while removing left recursion
Top-down parsers cannot use E -> E + T. Removing left recursion creates E', and the actions must move with the structure so that the output stays the same. The postfix translation of the original grammar becomes:
E -> T E'
E' -> + T { print('+') } E' | - T { print('-') } E' | ε
T -> num { print(num.val) }The action after T in E' is in the middle of a body, which is legal because it only uses the token + to its left. It prints the operator after the right operand and before the rest of the chain. This gives left-associative output, so 9-5+2 becomes 9 5 - 2 +.
The recursive descent version below implements this scheme. Each action becomes a line of code placed exactly where the action sits in the body.
def translate(tokens):
toks = list(tokens) + ["$"]
out = []
i = 0
def term(): # T -> num { print(num.val) }
nonlocal i
t = toks[i]
if not t.isdigit():
raise SyntaxError(f"unexpected token {t!r}")
out.append(t)
i += 1
def rest(): # E' -> (+|-) T { print(op) } E' | epsilon
nonlocal i
while toks[i] in ("+", "-"):
op = toks[i]
i += 1
term()
out.append(op) # the action, placed after T
term() # E -> T E'
rest()
if toks[i] != "$":
raise SyntaxError(f"unexpected token {toks[i]!r}")
return " ".join(out)
print(translate(["9", "-", "5", "+", "2"])) # 9 5 - 2 +The while loop is the tail call E' rewritten as iteration. The output order is unchanged.
Tracing a scheme
To trace a scheme, build the parse tree and insert each action as an extra child at its position in the body. Then do a depth-first, left-to-right walk. Execute each action as the walk reaches it. For a bottom-up parser, the same order results from running each action at its reduction. For postfix SDTs, both views give identical output.
Common errors
- Putting an inherited attribute's action after the symbol that needs it.
- Using a synthesized attribute of a symbol to the right of the action.
- Reading
A.sin the middle of the body when it is only available at the right end. - Converting a left-recursive scheme to an LL(1) grammar without moving the actions with their operands.
- Assuming a mid-body action works unchanged in an LR parser. It needs a marker nonterminal.
Exercise
Consider the scheme S -> a S { print("1") } | b { print("2") }. A bottom-up parser reads the input a a b. What does it print?
Show answer
The reductions happen innermost first. First S -> b prints 2. Then S -> a S prints 1 for the inner S, and again for the outer S. The output is 211.
Exercise
In the scheme D -> L { T.in = L.type } T, state whether the action placement is valid for an L-attributed definition. Give the reason.
Show answer
It is invalid. The action computes the inherited attribute T.in, so it must come before T, which it does, but it uses L.type, which is the synthesized attribute of a symbol to its left. That part is fine. The real problem arises only if L.type depends on T. If L.type does not depend on T, the scheme is valid. If L.type needs T.in, the dependency is circular and the scheme cannot be evaluated.
Exercise
Rewrite A -> X { f } Y so that f runs at the right end of a production, for use in an LR parser.
Show answer
Introduce a marker nonterminal M. Write A -> X M Y and M -> ε { f }.