


Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



Attribute Grammar Example This example illustrates the most common use of attribute grammars â prototyping compilers. It is adapted from B. Courcelle âAttribute grammars: theory and applicationsâ, Formalization of Programming Concepts, Lect. Notes in Comp. Sci., V.107. This example concerns itself with only a small part of a compiler, namely translating assignment statements. In particular, it focuses on the process of allocating temporary storage for the evaluation of expressions. For instance, in the expression a+bc, the result of bc must first be computed and stored in some memory location d, and then the addition a+d performed. In complicated expressions, numerous intermediate results must be generated and the locations where they are stored retained for later use as appropriate. This methodology is described here by means of an attribute grammar. Some pool of available temporary memory locations must be assumed. In order to focus on the desired issues, this is taken to be the symbolic locations L 0 , L 1 , L 2 , ⌠Courcelle expresses the code for an assignment statement in terms of âthree address instructionsâ. That is, the usual precedence is used to resolve the order of operations, and suitable temporary locations are determined, but the code is symbolically indicated to avoid computer architecture details. Also, temporary locations are reused when their prior use is completed. For example, the assignment X := 3.14 * (X+Y) will be translated into L 0 := 3.14; L 1 := X; L 2 := Y; L 1 := L 1 +L 2 ; L 0 := L 0 *L 1 ; X:= L 0. This attribute grammar uses the attribute âfreeâ to denote the first unused temporary memory location available, the attribute âresâ to denote the memory location used to hold the result of an expression, term, etc., and âcodeâ to denote the sequence of instructions for an assignment, expression, etc. The semantic rules also use the function ânextâ applied to temporary memory locations with the obvious result (e.g., next(L 0 ) = L 1 , etc.).
BNF Semantic Rules
id asn := exp trm trm *^ fct fct const
( (^) exp ) exp +^ trm trm fct id X fct id Y
f=L 0 f=L 0 f=L 0 f=L 0 f=L 0 f=L 1 f=L 1 f=L 1 f=L 1 f=L 1 f=L^2 f=L 2 r=L 0 r=L 0 r=L 0 r=L 0 r=L 1 r=L 1 r=L 1 r=L 1 r=L 1 r=L^2 r=L 2 c=[L 2 :=Y] c=[L 1 :=X] c=[L 1 :=X] c=[L 1 :=X] c=[L 2 :=Y] c=[L 1 :=X; L 2 :=Y; L 1 :=L 1 +L 2 ] c=[L 1 :=X; L 2 :=Y; L 1 :=L 1 +L 2 ] c=[L 0 :=3.14] c=[L 0 :=3.14] A partially completed attribute evaluation tree.