Professional Documents
Culture Documents
Unit 3
Unit 3
o In syntax directed translation, every non-terminal can get one or more than one
attribute or sometimes 0 attribute depending on the type of the attribute. The
value of these attributes is evaluated by the semantic rules associated with the
production rule.
o In the semantic rule, attribute is VAL and an attribute may hold anything like a
string, a number, a memory location and a complex record.
Example
S→E$ { printE.VAL }
S→E$ { printE.VAL }
Example
E -> E+T | T
T -> T*F | F
F -> id
To evaluate translation rules, we can employ one depth-first search traversal on the
parse tree. This is possible only because SDT rules don’t impose any specific order on
evaluation until children’s attributes are computed before parents for a grammar
having all synthesized attributes. Otherwise, we would have to figure out the best-
suited plan to traverse through the parse tree and evaluate all the attributes in one or
more traversals. For better understanding, we will move bottom-up in the left to right
for computing the translation rules of our example.
Example 3:
We can also evaluate the postfix expression with the help of STACK
If String ab+c*, where a=1, b=3, c=5. So, string becomes 13+5*
Then
1. push 1
2. push 3
3. add the two topmost elements, and result is 4
4. push 5
5. multiply the two topmost elements and result is 20
o In the parse tree, most of the leaf nodes are single child to their parent nodes.
o In the syntax tree, we can eliminate this extra information.
o Syntax tree is a variant of parse tree. In the syntax tree, interior nodes are
operators and leaves/leafs are operands.
o Syntax tree is usually used when represent a program in a tree structure.
Abstract syntax trees are important data structures in a compiler. It contains the least
unnecessary information.
Example: Convert the expression a := (-c * b) + (-c * d) into three address code.
Three-address code is as follows:
t1 := -c
t2 := t1*b
t3 := t1*d
t4 := t2 + t3
a := t4
t is used as registers in the target program.
3. Indirect Triples –
This representation makes use of pointer to the listing of all references to
computations which is made separately and stored. It’s similar in utility as compared
to quadruple representation but requires less space than it. Temporaries are implicit
and easier to rearrange code.
E → E1 + E2 E.place := newtemp;
E.code := E1.code || E2.code
gen(E.place := E1.place '+' E2.place)
E → E1 * E2 E.place := newtemp;
E.code := E1.code || E2.code
gen(E.place := E1.place '*' E2.place)
E → id E.place:=id.place
E.code:= null