How Compilers Work

The pipeline that turns source code text into something a machine can run.

What is it?

A compiler translates a program from one language (your source code) into another (machine code, bytecode, or even another high-level language). It does this in stages, each turning one representation into a slightly lower-level one:

1. Lexing splits raw text into tokens: keywords, names, numbers, operators. 2. Parsing checks the tokens follow the grammar and builds an abstract syntax tree (AST), a tree showing the program's structure. 3. Semantic analysis checks meaning: are names declared, do types match, is return inside a function? 4. The AST is lowered to an intermediate representation (IR), a simple, machine-independent form that's easy to analyze. 5. Optimization rewrites the IR to run faster or smaller without changing behaviour. 6. Code generation turns IR into machine instructions for a specific CPU, choosing registers and instruction sequences. 7. Linking combines compiled files and libraries into one executable, resolving references between them.

An interpreter runs the program directly instead of producing an executable, usually by walking the AST or executing bytecode. A JIT (just-in-time) compiler combines both: it starts interpreting, watches which code runs often, and compiles that hot code to machine code while the program runs.

Explain like I'm 10

Translating a book: first you split it into words (lexing), then work out each sentence's grammar (parsing), check it makes sense (semantic analysis), write a rough literal translation (IR), polish the wording (optimization), then typeset it for a specific printer (code generation) and bind the chapters into one volume (linking). An interpreter is a live translator reading aloud sentence by sentence; a JIT is one who starts reading aloud, then writes down translations of passages that keep coming up.

Examples

One line through the pipeline

Source:   total = price * 2 + tax;

Tokens:   IDENT(total) EQUALS IDENT(price) STAR NUMBER(2) PLUS IDENT(tax) SEMICOLON

AST:          Assign
             /      \
         total      Add
                   /    \
               Multiply  tax
               /     \
           price      2

IR (three-address code):
          t1 = price * 2
          t2 = t1 + tax
          total = t2

Optimized: t1 = price << 1      (strength reduction, valid for integers)
          total = t1 + tax

x86-64:   mov  eax, [price]
          shl  eax, 1
          add  eax, [tax]
          mov  [total], eax

A tiny tree-walking interpreter (Python)

def evaluate(node, variables):
    kind = node[0]
    if kind == "num":
        return node[1]
    if kind == "var":
        return variables[node[1]]
    left = evaluate(node[1], variables)
    right = evaluate(node[2], variables)
    if kind == "add":
        return left + right
    if kind == "mul":
        return left * right
    raise ValueError(f"unknown node {kind}")

tree = ("add", ("mul", ("var", "price"), ("num", 2)), ("var", "tax"))
print(evaluate(tree, {"price": 10, "tax": 3}))   # 23

This skips code generation entirely: it executes the AST directly. Real interpreters like CPython compile to bytecode first because a flat instruction list is faster to execute than recursively walking a tree.

How it works

Lexer. Usually a finite-state machine (often described with regular expressions). It reads characters and emits tokens with their positions, so later errors can point at the right line.

Parser. Uses a grammar to build the tree. Hand-written recursive descent parsers (one function per grammar rule) are common in production compilers (GCC, Clang, Go, V8) because they give good error messages. Generated parsers (LR, LALR via yacc/bison) are the other classic approach. Syntax errors are reported here.

Semantic analysis. Walks the AST with a symbol table that maps names to declarations in each scope, resolves which variable each name refers to, and performs type checking. Type errors and undeclared names come from here.

IR. Compilers lower the AST to an IR such as three-address code or SSA (static single assignment, where every variable is assigned exactly once). SSA makes data flow explicit, which makes many optimizations simple. LLVM IR is a widely used SSA IR shared by Clang, Rust, Swift and others.

Optimization. Typical passes: constant folding (3 * 4 → 12), dead code elimination, common subexpression elimination, inlining, loop-invariant code motion, and vectorization. Passes must preserve observable behaviour as the language spec defines it, which is why undefined behaviour in C gives the optimizer so much freedom.

Code generation. Instruction selection maps IR to CPU instructions, register allocation decides which values live in the CPU's few registers versus memory, and instruction scheduling orders them for the pipeline.

Linking. Each source file becomes an object file with unresolved symbols ("I call printf but don't define it"). The linker merges object files and libraries, resolves symbols to addresses, and writes the executable. Static linking copies library code in; dynamic linking leaves references resolved at load time.

JITs. V8 (JavaScript), HotSpot (Java) and others start by interpreting bytecode while profiling. Hot functions are compiled with optimizations based on observed types ("this argument is always an integer"). If an assumption later breaks, they deoptimize back to the interpreter.

source text
     |  lexer
     v
 tokens
     |  parser
     v
 AST  --semantic analysis (symbols, types)-->  annotated AST
     |  lowering
     v
 IR  --optimization passes-->  optimized IR
     |  code generation
     v
 object files (.o)  +  libraries
     |  linker
     v
 executable

 Interpreter: AST/bytecode --> execute directly
 JIT:         bytecode --> interpret + profile --> hot code --> machine code

Why does it exist?

CPUs only understand their own machine instructions, and writing those by hand is slow and error-prone. Compilers let people write in languages built for humans while still producing fast native code. The staged design exists because each stage is a manageable problem on its own, and a shared IR lets many source languages reuse the same optimizer and many CPU back ends.

When to use it

Knowing the pipeline pays off when you: - read compiler error messages and need to know which stage produced them, - write parsers for config formats, query languages, or DSLs, - build linters, formatters, code mods, or bundlers, which all work on ASTs (Babel, ESLint, Prettier, TypeScript), - reason about performance: inlining, why a JIT deoptimized, why undefined behaviour "changed" your program, - debug linker errors like "undefined reference" or duplicate symbols.

When not to use it

- Don't write a full compiler or parser when a data format (JSON, YAML) or an existing parser library will do. - Don't parse real languages with regular expressions; nested structure needs a real parser. - Don't hand-optimize code in ways the compiler already does (replacing * 2 with << 1); write clear code and profile.

Common mistakes

  • Thinking 'compiled vs interpreted' is a property of the language. It's a property of the implementation; Python has CPython (bytecode interpreter) and PyPy (JIT), and Java is compiled to bytecode then JIT-compiled.

  • Confusing compile errors with linker errors. 'Undefined reference to foo' means the code compiled but no object file or library provided foo.

  • Assuming the compiler executes your C code exactly as written. With optimizations on, it can reorder, remove, or merge operations, and undefined behaviour lets it assume impossible cases never happen.

  • Trying to parse nested or recursive syntax with regex instead of writing a small recursive-descent parser.

  • Believing interpreted code is always slow. A modern JIT can match or beat ahead-of-time compiled code in hot loops because it optimizes for observed runtime types.

Practice exercises

  1. Easy:

    By hand, write the tokens and draw the AST for if (count > 10) { total = total + count * 2; }.

  2. Medium:

    Write a lexer and recursive-descent parser for arithmetic expressions with +, -, *, / and parentheses that respects precedence, builds an AST, and evaluates it. Report syntax errors with the column number.

  3. Hard:

    Extend your expression language with variables and let statements, then add a constant-folding pass over the AST and a compiler that emits instructions for a small stack-based virtual machine you also write. Compare its speed to the tree-walking evaluator.

Interview questions

What are the main phases of a compiler?

Lexing (text to tokens), parsing (tokens to AST), semantic analysis (name resolution, type checking), lowering to IR, optimization, code generation (instruction selection, register allocation), and linking (combining object files and libraries into an executable).

What is the difference between a compiler and an interpreter?

A compiler translates the whole program ahead of time into another form (usually machine code) that runs later. An interpreter executes the program directly, typically from an AST or bytecode. Many systems mix both: compile to bytecode, then interpret or JIT it.

What is an AST, and why do tools use it?

An abstract syntax tree represents a program's structure with nodes for constructs (calls, assignments, operators) and without incidental syntax like parentheses and semicolons. Compilers, linters, formatters, and refactoring tools work on ASTs because structure is far easier to analyze and transform than raw text.

What is a JIT compiler, and what are its trade-offs?

It compiles code to machine code at runtime, usually only hot paths, using profiling data such as observed types. Benefits: speculative optimizations an AOT compiler can't make, and portable bytecode. Costs: warm-up time, memory for the compiler and code cache, and deoptimization when speculative assumptions fail.

What is SSA form?

Static Single Assignment: an IR where each variable is assigned exactly once, with phi functions merging values where control flow joins. It makes def-use chains explicit, which simplifies optimizations like constant propagation, dead code elimination, and register allocation.

What does a linker do?

It takes object files with unresolved symbols plus libraries, resolves each symbol to its definition, lays out code and data sections, patches addresses (relocation), and produces an executable or shared library. Dynamic linking defers some resolution to load or first-call time.

Give examples of common compiler optimizations.

Constant folding and propagation, dead code elimination, inlining, common subexpression elimination, loop-invariant code motion, loop unrolling, strength reduction, tail-call optimization, and auto-vectorization.

Why does undefined behaviour in C matter to the optimizer?

The compiler may assume undefined behaviour never happens, such as signed overflow or dereferencing null. That lets it remove checks or reorder code based on those assumptions, so a program with UB can behave very differently at -O2 than at -O0.

Where do type errors versus syntax errors come from?

Syntax errors come from the parser: the token sequence doesn't match the grammar. Type errors come from semantic analysis: the code is grammatically valid but violates typing rules, such as adding a string to a struct or calling a function with the wrong arguments.

What is bytecode, and why do runtimes like the JVM and CPython use it?

Bytecode is a compact, platform-independent instruction set for a virtual machine. It's quicker to execute than walking an AST, can be cached to skip re-parsing, ships across platforms unchanged, and gives a JIT a convenient input to profile and compile.