Professional Documents
Culture Documents
Lecture 2
Lecture 2
Compiler Phases
Abstract
Source Lexical Parsing
Tokens Syntax
Program Analysis
Tree
Semantic
Analysis
Attributed
Target Code Optimized AST
Code Generation Code Optimization (Intermediate
Code)
Lexical Analysis
Lexical Analysis - Analogy
● Recognize words
Space
if x == 0 then { y = 1; } else { z = 2; }
Keywords
Constants
Lexical Analysis
● Divides programs into tokens
subject object
sentence
Parsing
● Parsing program expressions with “Parse Tree” or AST
if x == 0 then { y = 1; } else { z = 2; }
x == 0 y 1 z 2
If-then-else-stmt
Semantic Analysis
Semantic Analysis - Analogy
● Understand the meaning once parsing is done
x = 1; x = 1;
{ {
x = 2; z = 2;
print x; print x;
} }
Semantic Analysis
● Understand the meaning once parsing is done
○ Stricter rules for resolving ambiguities
● Compilers perform semantic checks
○ Type checking and scope analysis to find inconsistencies
Optimization
Optimization - Analogy
● Edit sentences
○ Revise sentences to shorter sentences while keeping the meaning
○ Remove redundant sentences
y = 0; x = y + 1; print x;
print 1;
Code Generation
Code Generation - Analogy
● Generate “equivalent” sentence in another language