compiler-design-module-4-syntax-directed-translation-set-1
compiler-design-module-4-syntax-directed-translation-set-1
Warning
• Syntax of statements
o stmt → id = expr ;
| if ( expr ) stmt ;
| if ( expr ) stmt else stmt ;
| while ( expr ) stmt ;
expr → expr + term | expr - term | term
term → term * factor | term / factor | factor
factor → digit | ( expr )
digit → 0 | 1 | … | 9
2.3 SYNTAX-DIRECTED TRANSLATION(SDT)
A formalism for specifying translations for programming language constructs.
( attributes of a construct: type, string, location, etc)
• Syntax directed definition(SDD) for the translation of constructs
• Syntax directed translation scheme(SDTS) for specifying translation
Postfix notation for an expression E
• If E is a variable or constant, then the postfix nation for E is E itself ( E.t≡E ).
• if E is an expression of the form E1 op E2 where op is a binary operator
o E1' is the postfix of E1,
o E2' is the postfix of E2
o then E1' E2' op is the postfix for E1 op E2
• if E is (E1), and E1' is a postfix
then E1' is the postfix for E
eg) 9-5+2⇒95-2+
9 - (5 + 2) ⇒ 9 5 2 + -
Suppose a node n in parse tree is labeled by X and X.a denotes the value
of attribute a of X at that node.
compute X's attributes X.a using the semantic rules associated with X.
Fig 2.7. Example of a depth-first traversal of a tree. Fig 2.8. An extra leaf is constructed for a semantic action.
Example 2.8.
• SDD vs. SDTS for infix to postfix translation.
2.4 PARSING
if token string x ∈ L(G), then parse tree
else error message
Top-Down parsing
1. At node n labeled with nonterminal A, select one of the productions whose left part is
A and construct children of node n with the symbols on the right side of that production.
2. Find the next node at which a sub-tree is to be constructed.
ex. G: type → simple
|↑id
|array [ simple ] of type
simple → integer
|char
|num dotdot num
Fig 2.10. Top-down parsing while scanning the input from left to right.
• G : { S->aSb | c | ab }
According to topdown parsing procedure, acb , aabb∈L(G)?
• S/acb⇒aSb/acb⇒aSb/acb⇒aaSbb/acb ⇒ X
(S→aSb) move (S→aSb) backtracking
⇒aSb/acb⇒acb/acb⇒acb/acb⇒acb/acb
(s→c) move move
so, acb∈ L(G)
Is is finished in 7 steps including one backtracking.
• S/aabb⇒aSb/aabb⇒aSb/aabb⇒aaSbb/aabb⇒aaSbb/aabb⇒aaaSbbb/aabb ⇒ X
(S→aSb) move (S→aSb) move (S→aSb) backtracking
⇒aaSbb/aabb⇒aacbb/aabb ⇒ X
(S→c) backtracking
⇒aaSbb/aabb⇒aaabbb/aabb⇒ X
(S→ab) backtracking
⇒aaSbb/aabb⇒ X
backtracking
⇒aSb/aabb⇒acb/aabb
(S→c) bactracking
⇒aSb/aabb⇒aabb/aabb⇒aabb/aabb⇒aabb/aabb⇒aaba/aabb
(S→ab) move move move
so, aabb∈L(G)
but process is too difficult. It needs 18 steps including 5 backtrackings.