Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 11

Compiler

Design
CSCI415: Tutorial 9
Semantic Analysis
Semantic Analysis
• int x= 3+2.5
• Will this line of code produce an error?
Semantic Analysis
• A semantic analyzer checks the source program for semantic errors and
collects the type information for the code generation.

• Semantics of a language provide meaning to its constructs, like tokens and


syntax structure. Semantics help interpret symbols, their types, and their
relations with each other.
Semantic CFG + semantic rules = Syntax

analysis Directed Definitions


Syntax directed translation
Syntax Directed Translation has augmented rules to the grammar that facilitate
semantic analysis.
SDT involves passing information bottom-up and/or top-down the parse tree in
form of attributes attached to the nodes. Syntax-directed translation rules use:
1) Lexical values of nodes
2) Constants
3) Attributes associated with the non-terminals in their definitions.
Example 1 E
E.value = 10

SDT for evaluation of expression


E T
● E-> E+T | T E.value = 6
+
T.value = 4
● T-> T*F|F
● F->num T F
T.value = 6 F.value = 4
Using SDT evaluate the expression 2*3+4
num
E-> E+T { E.value= E1.value+T.value} T * F num.value = 4
E-> T { E.value = T.value} T.value = 2 F.value = 3

T-> T*F { T.value= T1.value * F.value} F num


T-> F { T.value=F.value} F.value = 2 num.value = 3
F-> num { F.value=num.value}
num
num.value = 2
Example 2 E
Print(‘+’)

SDT for Infix to postfix expression E T


● E-> E+T | T + Print(‘*’)
● T-> T*F|F
T
● F->num T
Using SDT evaluate the expression 2+3*8
F
Print(2) T F
E-> E+T {printf(“+”);} *
Print(8)
E->T {}
T-> T*F {printf(“*”);} F num
num
Print(3) num.value = 8
T->F {} num.value = 2
F-> num{printf(num.value);} num
num.value = 3
Output: 234*+
ANTLR lab task
Intellij
Using ANTLR write grammar with syntax rules to calculate arithmetaic
expressions (+,-,*,/)

You might also like