Module 3 - Semantic Analysis
Module 3 - Semantic Analysis
L En Print (E.val)
F.val=3 digit.lexval=
5 parse tree showing the value
digit.lexval=3 of the attributes at each node
Annotated parse tree is called Annotated parse tree
for 3*5+4n
Exercise
Draw Annotated Parse tree for following:
1. 7+3*2n
2. (3+4)*(5+6)n
Syntax directed definition to translates arithmetic expressions from infix
to prefix notation
LE Print(E.val)
Pdigit P.val=digit.lexval
Inherited attribute
• An inherited value at a node in a parse tree is computed from
the value of attributes at the parent and/or siblings of the node.
(attribute taking value from its parents itself, and its sibilings)
Production Semantic rules
D→TL L.in = T.type
T → int T.type = integer
T → real T.type = real
L → L1 , id L1.in = L.in, addtype(id.entry,L.in)
L → id addtype(id.entry,L.in)
id
id
1
DTL
L → Lid
1 , id
Evaluation order
• A topological sort of a directed acyclic graph is any ordering of
the nodes of the graph such that edges go from nodes earlier in
the ordering to later nodes.
• If is an edge from to then appears before in the ordering.
D
1 T.type=re L.in=rea 2
al l
real 3 ,
L.in=rea id 4
l 3
,
5 L.in=rea id 6
l 2
7 id
1
Construction of syntax tree
• Following functions are used to create the nodes of the syntax
tree.
1. Mknode (op,left,right): creates an operator node with label op and
two fields containing pointers to left and right.
2. Mkleaf (id, entry): creates an identifier node with label id and a
field containing entry, a pointer to the symbol table entry for the
identifier.
3. Mkleaf (num, val): creates a number node with label num and a
field containing val, the value of the number.
Construction of syntax tree for
expressions
Example: construct syntax
tree for a-4+c P5 +
P1: mkleaf(id, entry for a);
P2: mkleaf(num, 4);
P3: mknode(‘-‘,p1,p2); P3 - P4 id
Entry for a
Bottom up evaluation of S-attributed definitions
• S-attributed definition is one such class of syntax directed
definition with synthesized attributes only.
• Synthesized attributes can be evaluated using bottom up
parser only.
Synthesized attributes on the parser stack
• Consider the production AXYZ and associated semantic action
is A.a=f(X.x, Y.y, Z.z) State Value
State Value
top-2 top
top-1
top
- R
9 {Print(9 T {Print(-
)} )}
5 {Print(5 + R
T {Print(
)}
+)}
2 {Print( 𝜖
2)}
Now, Perform Depth first traversal Postfix=95-2+
Types of errors
Types of Errors
Errors