Skip to content

Lesson 7 of 9 · 28m

Bytecode Compilation: Lowering Trees into Instructions

Translate ASTs into linear bytecode, model a stack machine, and understand what compilation actually changes.

Interpreting an AST means rediscovering program structure at every execution step. Compilation does that structural work once. Even when the target is your own virtual machine rather than machine code, the shift is profound: trees become linear instructions and control flow becomes jumps.

A stack machine is the simplest useful target

# source: 1 + 2 * 3
CONST 1
CONST 2
CONST 3
MUL
ADD
PRINT

The VM loop manipulates an explicit operand stack:

while ip < len(bytecode):
    op, arg = bytecode[ip]
    ip += 1
    if op == "CONST":
        stack.append(arg)
    elif op == "ADD":
        right, left = stack.pop(), stack.pop()
        stack.append(left + right)

Compile expressions in evaluation order

def compile_expr(node, out):
    if isinstance(node, Number):
        out.append(("CONST", node.value))
    elif isinstance(node, Binary):
        compile_expr(node.left, out)
        compile_expr(node.right, out)
        out.append((BINOP[node.op], None))

For 1 + 2 * 3, precedence was already resolved during parsing. The compiler emits exactly the operation order encoded by the tree; source parentheses no longer matter.

Control flow becomes jumps

An if lowers to a conditional jump plus an unconditional jump over the else branch. Emit placeholder jump positions, then patch them once target offsets are known:

jump_pos = emit("JUMP_IF_FALSE", None)
compile_stmt(node.then_branch, out)
end_jump = emit("JUMP", None)
out[jump_pos] = ("JUMP_IF_FALSE", len(out))
compile_stmt(node.else_branch, out)
out[end_jump] = ("JUMP", len(out))

Field notes

  • Bytecode does not have to mean binary serialization. Tuples or dataclasses are fine until the instruction set stabilizes.
  • Use a constant pool once values repeat. Be careful: pooling 1 and 1.0 together is wrong if your language distinguishes them.
  • Keep a disassembler from day one. Nobody debugs numeric opcode arrays by staring at them.
  • Correct control flow is already a full project; peephole optimization can wait.

Was this lesson helpful?

Sign in to rate