Compiler Phases
Compiler Phases
Let’s explore each phase with full explanation, in the order they work, and with an easy-to-
understand example.
🔧 ✅ What it does:
🔤 Example:
Source code:
🧰 Tools used:
Lex (a tool for lexical analysis)
This is the second phase. After the lexical analyzer sends the tokens, the parser checks
whether these tokens are arranged according to the grammar rules of the programming
language.
It builds a Parse Tree or Syntax Tree, which shows the structure of the code.
🔧 ✅ What it does:
🧠 Example:
Input:
Parser ensures:
x is a variable
= is an assignment
5 + 3 is a valid expression
This is the third phase. It checks whether the code makes logical sense. Even if it is
syntactically correct, it may be semantically wrong.
It checks:
Variable declarations
Type compatibility (e.g., int + float)
Proper use of operators
🔧 ✅ What it does:
This is the fourth phase. After checking that the code is syntactically and semantically
correct, the compiler now converts it into an intermediate form that is not yet machine
code but is closer to it.
🔧 ✅ What it does:
🧠 Example:
This is the fifth phase, and its main goal is to make the code better, faster, and more
efficient, without changing what it does.
🔧 ✅ What it does:
🧠 Example:
🧱💻 6. CODE GENERATION PHASE (Final Machine
Code Phase)
🧠 📝 What is Code Generation?
This is the final phase where the compiler converts the intermediate optimized code into
actual machine code or assembly code, which the computer can directly execute.
🔧 ✅ What it does:
🧠 Example:
Intermediate:
It is a data structure used by the compiler to store all variable names, function names,
types, scopes, memory addresses, etc.
This is used by multiple phases to quickly look up info about variables and functions.
At every phase, the compiler checks for errors and tries to report them clearly so the
programmer can fix them. It also tries to recover and continue compilation.