How do compilers work? Lexing, parsing and code generation in plain terms
A compiler turns source code you can read into something a machine can run. It does that in a series of stages, each transforming the program into a new representation.
- Lexing (tokenizing). The raw text is split into tokens: keywords, names, numbers, operators.
x = 3 + ybecomes a short list of labeled pieces. - Parsing. Tokens are arranged into a tree that reflects the grammar of the language, usually called an abstract syntax tree (AST). This is where syntax errors are caught.
- Semantic analysis. The compiler checks meaning: are variables declared, do types match, is that function called with the right arguments?
- Intermediate representation. Many compilers translate the AST into a simpler, lower-level form that is easier to analyze.
- Optimization. Constant folding, removing dead code, inlining small functions and many other transformations happen here.
- Code generation. The optimized form becomes machine code or bytecode for a specific target.
Interpreters and just-in-time compilers reuse many of these same stages; the difference is mostly when code generation happens and whether it's saved.
Building a tiny interpreter for a calculator language is a classic project for understanding this pipeline end to end.
Have you ever written a parser or toy language? Which stage surprised you most once you understood how it worked?
Comments · 4
Building a tiny calculator parser was what finally made this click for me. Tokens first, then a tree, then evaluation. It's less magic than it sounds.
The grammar side has its own history: formal language theory from Chomsky is why we can define languages and build parsers from them mechanically.
Where does the optimiser fit in? Is it after parsing or a separate stage on the tree?
Separate stage, usually after parsing. The compiler builds a tree or intermediate form, optimises it, then generates the machine code.