programmingconcepts

§ 8.1 · Tools

Compilers

A program that translates code you can read into code a machine can run, one stage at a time.

A compiler translates source code into a lower-level form a machine can run, such as machine code or bytecode. It works in stages: lexing splits text into tokens, parsing builds a syntax tree, analysis checks types and names, and code generation emits instructions, usually after optimizing. Interpreters share the front stages but run the program directly.

Input
Source code
Output
Machine code or bytecode
Stages
Lex, parse, check, optimize, generate
Examples
gcc, rustc, go build, javac
Requires
RecursionStacks and queues

The pipeline

A compiler is a chain of small translations. Each stage takes one representation and produces a simpler, more precise one.

Stage Input → output For x = 1 + 2 * 3
Lexing Characters → tokens x = 1 + 2 * 3
Parsing Tokens → syntax tree =(x, +(1, *(2, 3)))
Analysis Tree → checked tree x is an integer; every name is defined.
Optimization Tree or IR → faster IR 1 + 2 * 3 folds to 7 at compile time.
Code generation IR → instructions mov eax, 7

The front end (lexing, parsing, analysis) understands the language. The back end (optimization, code generation) understands the machine. Projects like LLVM share one back end across many languages, which is how Rust, Swift and Clang all reach the same CPUs.

A tiny compiler

The code below compiles arithmetic like 2 * (3 + 4) into instructions for a tiny stack machine, then runs them. It has all three core stages:

  1. tokenize turns "12+(3)" into ["12", "+", "(", "3", ")"].
  2. compile is a recursive descent parser: one function per grammar rule. expr handles + and -, term handles *, and factor handles numbers and parentheses. Because expr calls term, multiplication binds tighter than addition.
  3. Code generation happens as it parses. After both sides of an operator are compiled, it emits the operator, giving postfix order: 1 + 2 * 3 becomes push 1, push 2, push 3, mul, add.
def tokenize(source):
    """Lexing: turn characters into tokens."""
    tokens, i = [], 0
    while i < len(source):
        ch = source[i]
        if ch.isspace():
            i += 1
        elif ch.isdigit():
            j = i
            while j < len(source) and source[j].isdigit():
                j += 1
            tokens.append(source[i:j])
            i = j
        elif ch in "+-*()":
            tokens.append(ch)
            i += 1
        else:
            raise SyntaxError(f"unexpected character {ch!r}")
    return tokens


def compile_expr(source):
    """Parsing and code generation: tokens in, stack-machine instructions out."""
    tokens, code, pos = tokenize(source), [], 0

    def peek():
        return tokens[pos] if pos < len(tokens) else None

    def take():
        nonlocal pos
        pos += 1
        return tokens[pos - 1]

    def expr():  # expr := term (("+" | "-") term)*
        term()
        while peek() in ("+", "-"):
            op = take()
            term()
            code.append("add" if op == "+" else "sub")

    def term():  # term := factor ("*" factor)*
        factor()
        while peek() == "*":
            take()
            factor()
            code.append("mul")

    def factor():  # factor := number | "(" expr ")"
        tok = take() if peek() is not None else None
        if tok == "(":
            expr()
            if peek() != ")":
                raise SyntaxError("expected )")
            take()
        elif tok is not None and tok.isdigit():
            code.append("push " + tok)
        else:
            raise SyntaxError(f"unexpected {tok!r}")

    expr()
    if peek() is not None:
        raise SyntaxError(f"unexpected {peek()!r}")
    return code


def run(code):
    """A tiny virtual machine: every instruction works on a stack."""
    stack = []
    for ins in code:
        if ins.startswith("push "):
            stack.append(int(ins[5:]))
        else:
            b, a = stack.pop(), stack.pop()
            stack.append(a + b if ins == "add" else a - b if ins == "sub" else a * b)
    return stack.pop()

run is a virtual machine. Each push puts a number on a stack; each operator pops two and pushes the result. The Java JVM, Python’s bytecode and WebAssembly are all stack machines built on the same idea.

Compilers vs interpreters

Compiler Interpreter
When it translates Before the program runs While it runs
Startup Slower build, then fast start Starts at once
Speed Usually faster Usually slower
Errors Many caught before running Found when the line runs

Most modern runtimes mix both. A just-in-time (JIT) compiler starts by interpreting, watches which code runs often, and compiles just that to machine code.

Common mistakes

  1. Thinking compiled means bug-free. A compiler checks syntax and, in typed languages, types. It can’t check that your logic is right; that’s what testing is for.
  2. Parsing with regular expressions. Regexes can’t match nested structure like parentheses. Real languages need a parser.
  3. Ignoring warnings. Compiler warnings are cheap bug reports. Most teams build with warnings treated as errors.

Check yourself

Check yourself

Which stage turns total = price 2 into the tokens total, =, price, , 2?

Check yourself

What does the stack machine in the example leave on the stack after push 4, push 3, sub?

Sources

  • Alfred Aho, Monica Lam, Ravi Sethi and Jeffrey Ullman, Compilers: Principles, Techniques, and Tools, 2nd edition (2006).
  • Robert Nystrom, Crafting Interpreters (2021), craftinginterpreters.com.
  • Chris Lattner and Vikram Adve, “LLVM: A Compilation Framework for Lifelong Program Analysis & Transformation,” CGO 2004.

Newsletter

One new concept each week, by email.

Signup opens soon.