Phases of a Compiler
How source code becomes machine code, step by step.
Lexical & Syntax Analysis
Lexical Analysis breaks source code into tokens (keywords, identifiers, symbols). Syntax Analysis (parsing) checks if these tokens follow the language's grammar, building a parse tree.
Semantic Analysis & Intermediate Code
Semantic Analysis checks meaning â like type mismatches â that grammar alone can't catch. The compiler then generates an intermediate representation, a code form that's easier to optimize and translate than the original source.
Optimization & Code Generation
The Optimization phase improves the intermediate code for speed/size without changing its behavior. Finally, Code Generation converts it into the target machine code that the CPU can actually execute.
đ Real-World Use
When you get a red squiggly underline in VS Code before you even run your code, that's essentially a mini compiler (or language server) running lexical + syntax + semantic analysis in real time to catch your errors early.
đĄ Pro Tip
A common exam/interview trap: syntax errors (wrong grammar, e.g. missing semicolon) are caught during parsing, but logical/type errors (like adding a string to a number in a strict language) are caught during Semantic Analysis â know the difference.
đ§Ē Quick Self-Test
Check what you just learned â no pressure, just practice.
1. Which phase breaks source code into tokens?
2. What does Semantic Analysis check that grammar alone can't?