150 likes | 287 Views
Chapter 5. Syntax-Directed Translation. Fig. 5.2. Syntax-directed definition of a simple desk calculator. Fig. 5.3. Annotated parse tree for 3*5+4 n. Fig. 5.4. Syntax-directed definition with inherited attribute L.in.
E N D
Fig. 5.2. Syntax-directed definition of a simple desk calculator
Fig. 5.4. Syntax-directed definition with inherited attribute L.in.
Fig. 5.5. Parse tree with inherited attribute in at each node labeled L.
Fig. 5.16. Implementation of a desk calculator with an LR parser.
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 1. the attributes of the symbols X1 ,X2 ,· · · ,Xj-1 to the left of Xj in the production and • the inherited attributes of A. Note that every S-attributes definition is L-attributed, because the restrictions (1) and (2) apply only to inherited attributes
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 inputreal 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 D T 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 )}
Fig.5.32. At each node for L, L.in = T.type. If we ignore the actions in the above translation scheme, the sequence of moves made by the parser on the input of Fig. 5.32. is as in Fig. 5.33. For clarity, we show the corresponding grammar symbol instead of a stack state and the actual identifier instead of the token id.
Fig. 5.33.Whenever a right side for L is reduced, T is just below the right side.
Example 5.18. As an instance where we cannot predict the position, consider the following translation scheme: (5.6) 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.
Fig. 5.35. Copying an attribute value through a marker M. є (a) original production (b) modified dependencies