Compiler Important
Compiler Important
Compiler design involves multiple phases, each responsible for a specific part of translating a
high-level program (like C, Java, or Python) into machine code. Below are the main phases of a
compiler, explained with examples for better understanding.
🔸 Purpose:
Breaks the source code into tokens (keywords, identifiers, operators, etc.)
🔸 Input:
c
CopyEdit
int x = 10 + 20;
🔸 Output (Tokens):
css
CopyEdit
[int], [identifier: x], [=], [10], [+], [20], [;]
🔸 Purpose:
Checks if the token sequence follows the grammar rules (syntax) of the language
Creates a parse tree or abstract syntax tree (AST)
🔸 Example:
For: x = 10 + 20;
AST:
markdown
CopyEdit
=
/ \
x +
/ \
10 20
🔷 3. Semantic Analysis
🔸 Purpose:
🔸 Example:
c
CopyEdit
int x;
x = "Hello"; // Error: assigning string to an integer
🔸 Output:
Symbol Table
Type Error (if any)
🔸 Purpose:
🔸 Example:
For x = 10 + 20;
Intermediate Code (Three-address code):
ini
CopyEdit
t1 = 10 + 20
x = t1
🔷 5. Code Optimization
🔸 Purpose:
🔸 Example:
c
CopyEdit
x = 10 + 20; // Constant Folding
Optimized IR:
ini
CopyEdit
x = 30
🔸 Purpose:
🔸 Example:
Assembly (x86-like):
nginx
CopyEdit
MOV R1, #30
MOV x, R1
🔷 7. Code Linking and Assembly
🔸 Purpose:
Assembles machine code and links libraries or other object files to create the final
executable
📌 Summary Table:
Phase Task Example Output
int x = 10 + 20; → [int], [x],
Lexical Analysis Token generation
[=], ...
Syntax Analysis Parse Tree creation x = 10 + 20 AST
Semantic Analysis Type and scope checking Error if x = "text";
Intermediate Code
IR generation t1 = 10 + 20; x = t1
Gen
Code Optimization Improve performance x = 30
Assembly or Machine
Target Code Gen MOV R1, #30
Code
Linking & Assembly Executable file creation .exe, .out, etc.