
The structure of a compiler refers to how a compiler is organized into different parts (phases) , where each phase performs a specific task in translating a...
The structure of a compiler refers to how a compiler is organized into different parts (phases), where each phase performs a specific task in translating a program from high-level language β machine code.
Source Program
β
Lexical Analysis
β
Syntax Analysis
β
Semantic Analysis
β
Intermediate Code Generation
β
Code Optimization
β
Code Generation
β
Target (Machine Code)
Two important components work with all phases:
Stores information about variables, functions, identifiers
Example:
Variable Name | Type | Scope
x | int | global
There are 6 main phases:
Converts source code into tokens (smallest units).
int x = 10;
π Tokens:
int | x | = | 10 | ;
π βLexical analyzer converts characters β tokensβ
Checks whether tokens follow grammar rules of the language.
Correct:
int x = 10;
Incorrect:
int = x 10;
=
/ \
x 10
π βParser checks grammar using CFG (Context-Free Grammar)β
Checks the meaning of the program.
int x;
x = "Hello"; β Error
π βEnsures program is logically correctβ
Generates machine-independent intermediate code.
x = a + b
π Intermediate Code:
t1 = a + b
x = t1
π βCreates intermediate representation (IR)β
Improves code to make it faster and efficient.
Before:
x = a + 0
After:
x = a
π βOptimization improves performance without changing outputβ
Converts intermediate code into machine code.
ADD R1, R2
MOV R1, x
π βFinal phase produces executable codeβ
int x = a + b;
| Phase | Output |
|---|---|
| Lexical | int, x, =, a, +, b |
| Syntax | Parse tree |
| Semantic | Type checked |
| Intermediate | t1 = a + b |
| Optimization | t1 = a + b |
| Code Generation | Machine instructions |
π Frequently asked:
| Phase | Input | Output | Main Function | Errors |
|---|---|---|---|---|
| Lexical Analysis | Source code | Tokens | Break code into tokens | Invalid symbols |
| Syntax Analysis | Tokens | Parse tree | Check grammar | Syntax errors |
| Semantic Analysis | Parse tree | Annotated tree | Check meaning | Type errors |
| Intermediate Code | Annotated tree | IR code | Generate intermediate form | β |
| Code Optimization | IR code | Optimized IR | Improve efficiency | β |
| Code Generation | Optimized IR | Machine code | Final output | β |
A compiler works in multiple phases, each with a specific role
Understanding each phase helps in:
Open this section to view and download past papers
Click on Show Past Papers to load available exam papers.