← Back to Home

🛠️ How Compilers and Interpreters Work

From source text to running code: lexing, parsing, ASTs, bytecode and JITs, plus a working mini-compiler in about 100 lines of Python.

Every program you write is text. Something has to turn total = price * 2 + tax into instructions a CPU can execute. That something is a compiler, an interpreter, or, in most modern languages, a mix of both.

Knowing how this pipeline works pays off in practical ways. It explains why Python is slower than Go, what a JIT actually does, how linters and code formatters work, and why "compiled vs interpreted" is a blurrier line than it sounds. By the end of this article we'll have built a tiny working compiler and virtual machine in about 100 lines of Python.

The pipeline

Almost every language implementation follows the same stages:

source text
   │  1. Lexing (tokenizing)      "price * 2"  →  [NAME price] [STAR] [NUMBER 2]
   ▼
tokens
   │  2. Parsing                  tokens → abstract syntax tree (AST)
   ▼
AST
   │  3. Semantic analysis        resolve names, check types, report errors
   ▼
checked AST
   │  4. Lowering to IR           a simpler intermediate representation
   ▼
IR
   │  5. Optimization             constant folding, inlining, dead-code removal…
   ▼
optimized IR
   │  6. Code generation          machine code, or bytecode for a VM
   ▼
executable / bytecode

The difference between a "compiler" and an "interpreter" is mostly when the last stages happen and what runs the result.

1. Lexing

The lexer (or tokenizer) groups characters into tokens: identifiers, numbers, operators, keywords. It also drops whitespace and comments. This is usually done with simple pattern matching, often regular expressions.

2. Parsing and the AST

The parser checks that tokens follow the language's grammar and builds an abstract syntax tree, a tree that captures structure and precedence. Python exposes its own parser through the ast module:

import ast
print(ast.dump(ast.parse("total = price * 2 + tax"), indent=2))
Module(
  body=[
    Assign(
      targets=[
        Name(id='total', ctx=Store())],
      value=BinOp(
        left=BinOp(
          left=Name(id='price', ctx=Load()),
          op=Mult(),
          right=Constant(value=2)),
        op=Add(),
        right=Name(id='tax', ctx=Load())))],
  type_ignores=[])

Notice that price * 2 sits inside the addition. Operator precedence has been turned into tree shape. Once you have an AST, many tools become straightforward: linters (Ruff, ESLint) walk it looking for patterns, formatters (Black, Prettier) print it back out in a canonical style, and refactoring tools rewrite it.

Most production parsers are hand-written recursive descent parsers, with one function per grammar rule. GCC, Clang, Go and V8 all use hand-written parsers. CPython has used a PEG parser generated from a grammar file since Python 3.9.

3. Semantic analysis

A syntactically valid program can still be wrong: an undefined variable, a type mismatch, calling a function with the wrong arguments. Semantic analysis resolves each name to its declaration (building symbol tables and scopes) and, in statically typed languages, checks types. This is where Go tells you x declared and not used, and where TypeScript and mypy do their work.

4–5. Intermediate representation and optimization

Optimizing directly on an AST is awkward, so compilers lower it to an intermediate representation (IR) that is closer to the machine but still independent of any particular CPU. LLVM IR is the best-known example. It's shared by Clang, Rust, Swift, Zig and others, so all of them get LLVM's optimizer and code generators for free.

Typical optimizations include:

Optimization Before After
Constant folding x = 60 * 60 * 24 x = 86400
Dead-code elimination if (false) { … } removed
Inlining area(r) calling pi * r * r pi * r * r in place, no call
Loop-invariant code motion for … { y = len(a) * 2; … } y computed once before the loop
Vectorization add one int per iteration add 8 ints per SIMD instruction

6. Code generation

Finally, the compiler emits either machine code for a specific CPU (x86-64, ARM64), or bytecode: compact instructions for a virtual machine. Machine code generation involves register allocation (deciding which values live in the CPU's few registers, a graph-coloring problem) and instruction selection.

Compiled, interpreted, or both?

Approach How it runs Examples Trade-off
Ahead-of-time (AOT) compiled Source → machine code before running C, C++, Go, Rust, Swift Fast startup and execution; build step; one binary per platform
Bytecode + interpreter Source → bytecode, then a VM loop executes it CPython, Ruby (YARV), Lua Portable and simple; each operation pays VM overhead
Bytecode + JIT VM interprets first, then compiles hot code to machine code at runtime Java (HotSpot), C# (.NET), JavaScript (V8), PyPy Near-native speed for long-running code; warm-up time and memory
Tree-walking interpreter Evaluates the AST directly Early Ruby, many teaching languages, config DSLs Simplest to build; slowest

CPython compiles too. It compiles your source to bytecode (cached in __pycache__/*.pyc) and then interprets that bytecode. You can see it with dis:

import dis

def add(a, b):
    return a + b

dis.dis(add)
  3           0 RESUME                   0

  4           2 LOAD_FAST                0 (a)
              4 LOAD_FAST                1 (b)
              6 BINARY_OP                0 (+)
             10 RETURN_VALUE

(That output is from Python 3.12. Bytecode changes between versions; 3.13, for example, fuses the two loads into one LOAD_FAST_LOAD_FAST instruction.)

Each line is one trip around the VM's main loop. That's a big reason Python is slower than Go for CPU-bound code. BINARY_OP + doesn't know whether a and b are ints, floats or strings until runtime, so it checks the types, finds the right implementation, and allocates a new result object, every time. A Go compiler knows the types in advance and emits a single ADD instruction.

CPython has been closing the gap. Python 3.11 added a specializing adaptive interpreter, which rewrites hot instructions into type-specific versions such as BINARY_OP_ADD_INT once it sees which types actually occur. Python 3.13 added an experimental JIT compiler.

How a JIT gets its speed

A JIT starts by interpreting and profiling. When a function or loop gets hot, it compiles it to machine code using what it observed at runtime: "x has always been an integer here". It inserts a cheap guard to check that assumption and generates fast specialized code behind it. If the guard ever fails, it deoptimizes back to the interpreter.

That's how V8 runs JavaScript, a dynamically typed language, at speeds that would have seemed impossible in 2005. It's also why JIT benchmarks need a warm-up period before measuring.

Build one: a tiny compiler and VM

Here's the whole pipeline for arithmetic expressions with variables: a lexer, a recursive-descent parser, a constant-folding optimizer, a compiler to stack bytecode, and a virtual machine.

import re

# ---------- 1. Lexer ----------
TOKEN = re.compile(r"\s*(?:(\d+\.?\d*)|([A-Za-z_]\w*)|(.))")

def tokenize(src):
    tokens = []
    for number, name, op in TOKEN.findall(src):
        if number: tokens.append(("NUM", float(number)))
        elif name: tokens.append(("NAME", name))
        elif op.strip(): tokens.append(("OP", op))
    tokens.append(("EOF", None))
    return tokens

# ---------- 2. Parser (recursive descent) ----------
# expr   := term (('+' | '-') term)*
# term   := factor (('*' | '/') factor)*
# factor := NUM | NAME | '(' expr ')' | '-' factor
class Parser:
    def __init__(self, tokens):
        self.tokens, self.pos = tokens, 0

    def peek(self): return self.tokens[self.pos]
    def take(self):
        tok = self.tokens[self.pos]; self.pos += 1; return tok

    def expr(self):
        node = self.term()
        while self.peek() in (("OP", "+"), ("OP", "-")):
            node = ("bin", self.take()[1], node, self.term())
        return node

    def term(self):
        node = self.factor()
        while self.peek() in (("OP", "*"), ("OP", "/")):
            node = ("bin", self.take()[1], node, self.factor())
        return node

    def factor(self):
        kind, value = self.take()
        if kind == "NUM":  return ("num", value)
        if kind == "NAME": return ("var", value)
        if (kind, value) == ("OP", "-"): return ("bin", "-", ("num", 0.0), self.factor())
        if (kind, value) == ("OP", "("):
            node = self.expr()
            if self.take() != ("OP", ")"): raise SyntaxError("expected ')'")
            return node
        raise SyntaxError(f"unexpected token {value!r}")

def parse(src):
    p = Parser(tokenize(src))
    tree = p.expr()
    if p.peek()[0] != "EOF": raise SyntaxError(f"unexpected {p.peek()[1]!r}")
    return tree

# ---------- 3. Optimizer: constant folding ----------
OPS = {"+": lambda a, b: a + b, "-": lambda a, b: a - b,
       "*": lambda a, b: a * b, "/": lambda a, b: a / b}

def fold(node):
    if node[0] != "bin": return node
    _, op, left, right = node
    left, right = fold(left), fold(right)
    if left[0] == right[0] == "num":
        return ("num", OPS[op](left[1], right[1]))
    return ("bin", op, left, right)

# ---------- 4. Code generation: stack bytecode ----------
def compile_ast(node, code=None):
    code = [] if code is None else code
    if node[0] == "num": code.append(("PUSH", node[1]))
    elif node[0] == "var": code.append(("LOAD", node[1]))
    else:
        _, op, left, right = node
        compile_ast(left, code)
        compile_ast(right, code)
        code.append(("BINOP", op))
    return code

# ---------- 5. Virtual machine ----------
def run(code, env):
    stack = []
    for instr, arg in code:
        if instr == "PUSH": stack.append(arg)
        elif instr == "LOAD": stack.append(env[arg])
        else:
            b, a = stack.pop(), stack.pop()
            stack.append(OPS[arg](a, b))
    return stack.pop()

tree = parse("price * (60 * 60) + tax")
print(tree)
# ('bin', '+', ('bin', '*', ('var', 'price'), ('bin', '*', ('num', 60.0), ('num', 60.0))), ('var', 'tax'))
optimized = fold(tree)
print(optimized)
# ('bin', '+', ('bin', '*', ('var', 'price'), ('num', 3600.0)), ('var', 'tax'))
bytecode = compile_ast(optimized)
for line in bytecode: print(line)
# ('LOAD', 'price')  ('PUSH', 3600.0)  ('BINOP', '*')  ('LOAD', 'tax')  ('BINOP', '+')
print(run(bytecode, {"price": 2.0, "tax": 5.0}))   # 7205.0

Every real compiler is this pipeline with far more detail at each stage. A few things to notice:

Why this matters day to day

For a deeper dive, Crafting Interpreters by Robert Nystrom (free online) builds a complete language twice: once as a tree-walking interpreter and once as a bytecode VM.

Copied to clipboard!