Professional Documents
Culture Documents
Syntax-Directed
Translation
Production Semantic Rules
LEn print ( E.val )
E E1 + T E.val := E1.val + T.val
ET E.val := T.val
T T1 * F T.val := T1.val + F.val
TF T.val := F.val
F(E) F.val := E.val
F digit F.val := digit.lexval
2
L
n
E.val = 19
E.val = 15 T.val = 4
+
T.val = 15 F.val = 4
F.val = 3 digit.lexval = 5
digit.lexval = 3
4
D
id1
Fig. 5.5. Parse tree with inherited attribute in at each node labeled L.
5
E val
E1 + E2
val val
6
D
T in 5 L
4 6
type
in 9 L 10 , id2 2 entry
id1 1 entry
8
L-Attributed Definitions
A syntax-directed definition is L-attribute if each inherited attribute of Xj,
1≤ j≤n, on the right side of A → X1X2 · · · Xn , depends only on
9
Example 5.17. The type of an identifier can be passed by copy rules
using inherited attributes as shown in Fig. 5.32 (adapted from Fig. 5.7).
We shall first examine the moves made by a bottom-up parser on the input
real p, q, r
then we show how the value of attirbute T.type can be accessed when the
productions for L are applied. The translation scheme we wish to implement is
DT
L { L.in := T.type }
T int { T.type := integer }
T real { T.type := real }
L { L1.in := L.in }
L1 , id { addtype ( id.entry , L.in ) }
L id { addtype ( id.entry , L.in ) }
10
D
T in L
type
in
real L , r
in
L , q
DT L ;
T int val [ntop] := integer
T real val [ntop] := real
L L1 , id addtype (val [top] , val [top−3] )
L id addtype (val [top] , val [top−1] )
13
Example 5.18. As an instance where we cannot predict the position, consider th
e
following translation scheme:
Production Semantic Rules
S → aAC C.i := A.s
S → bABC C.i := A.s
(5.6)
C→c C.s := g ( C.i )
C inherits the synthesized attribute A.s by a copy rule. Note that there may or
may not be a B between A and C in the stack. When reduction by C → c is
performed, the value of C.i is either in val [top−1]or in val [top−2], but it is
not clear which case applies.
14
Production Semantic Rules
S → aAC C.i := A.s
S → bABMC M.i := A.s ; C.i := M.s
C→c C.s := g ( C.i )
M→є M.s := M.i
S S
b A B M C
b A B C s i s i
s
i
є