Syntax Directed Translation
Syntax Directed Translation
Outline
• Translation Schemes
Phases of Compiler
Semantic Analysis
• As for Lexical and Syntax analysis, also for Semantic Analysis we need
both a Representation Formalism and an Implementation Mechanism.
• Example. Let us consider the Grammar for arithmetic expressions. The Syntax
Directed Definition associates to each non terminal a synthesized attribute called
val.
E .val = 1 9 n
E .val = 1 5 + T.val = 4
T.val = 1 5 F.val = 4
F.val = 3 digit.lexval= 5
digit.lexval= 3
Inherited Attributes
• The non terminal T has a synthesized attribute, type, determined by the keyword in the
declaration.
• The production D → T L is associated with the semantic rule L .i n := T.t y pe which set
the inherited attribute L .i n .
• Note: The production L → L 1 , id distinguishes the two occurrences of L .
Inherited Attributes: An Example
• Synthesized attributes can be evaluated by a Postorder traversal.
• Inherited attributes that do not depend from right children can be
evaluated by a classical Preorder traversal.
• The annotated parse-tree for the sentence- real id1, id2, id3 is:
D
T.t y pe = r eal L .i n = r e a l
real L .i n = r e a l , id3
L .i n = r e a l , id2
id1
Inherited Attributes: An Example
• The annotated parse-tree for the input real id1, id2, id3 is:
T.t y pe = r eal L .i n = r e a l
real L .i n = r e a l , id3
L .i n = r e a l , id2
id1
• L .i n is then inherited top-down the tree by the other L -nodes.
• At each L -node the procedure addtype inserts into the symbol table the
type of the identifier.
Dependency Graphs
• The parser keeps the values of the synthesized attributes in its stack.
• Whenever a reduction A → α is made, the attribute for A is computed from the
attributes of α which appear on the stack.
State Val
… …
X X.x
Y Y.y
top Z Z.z
…. …..
Extending a Parser Stack: An Example
• Example. Consider the S-attributed definitions for the arithmetic
expressions. To evaluate attributes the parser executes the following code
P RODUCTION C ODE
L → En print(val[top − 1])
E → E1 + T val[ntop] := val[top] + val[top − 2]
E→T
T → T1 ∗ F val[ntop] := val[top] ∗ val[top − 2]
T →F
F → (E) val[ntop] := val[top − 1]
F → digit
• The variable n t op is set to the new top of the stack. After a reduction is
done top is set to ntop: When a reduction A → α is done with |α | =
r , then n t op = t op − r + 1 .
• During a shift action both the token and its value are pushed into the stack.
Extending a Parser Stack: An Example
• The following Figure shows the moves made by the parser on input
3*5+4n.
– Stack states are replaced by their corresponding grammar symbol;
– Instead of the token digit the actual value is shown.
L-Attributed Definitions