TExcelTAD
Home › Zig › Zig Mini Project

Zig Mini Project: A Tiny Stack VM

In this project you'll build a small stack-based virtual machine — the same idea that powers the JVM, WebAssembly and Python's bytecode interpreter, in miniature. A program is a list of instructions; the VM keeps a stack of numbers, and each instruction pushes, pops or combines values on it.

The project ties together most of the course: enums and tagged unions for instructions, structs with methods for the VM, error unions for things that can go wrong, switch for dispatch, slices, and finally an allocator and ArrayList for a tiny text assembler.

We build it in five steps. Each step is a complete program you can run and modify.

Step 1: The instruction set

An instruction is either an operation with no argument (add, mul, …) or one that carries a number (push 5, jump 3). A tagged union models that exactly:

zig · try it yourself
const std = @import("std");

const Instr = union(enum) {
    push: i64, // put a number on the stack
    add, // pop b, pop a, push a + b
    sub,
    mul,
    print, // print the top value (without popping)
    halt,
};

pub fn main() void {
    const program = [_]Instr{ .{ .push = 2 }, .{ .push = 3 }, .add, .print, .halt };
    for (program, 0..) |instr, i| {
        switch (instr) {
            .push => |n| std.debug.print("{d:>2}: push {d}\n", .{ i, n }),
            else => std.debug.print("{d:>2}: {t}\n", .{ i, instr }),
        }
    }
}
 0: push 2
 1: push 3
 2: add
 3: print
 4: halt

Printing the program like this is a disassembler — useful for debugging later.

Step 2: The stack

The VM needs a stack with a fixed capacity. Pushing onto a full stack or popping from an empty one are errors the program must report, not crashes:

zig · try it yourself
const std = @import("std");

const Stack = struct {
    data: [8]i64 = undefined,
    len: usize = 0,

    fn push(self: *Stack, value: i64) error{StackOverflow}!void {
        if (self.len == self.data.len) return error.StackOverflow;
        self.data[self.len] = value;
        self.len += 1;
    }

    fn pop(self: *Stack) error{StackUnderflow}!i64 {
        if (self.len == 0) return error.StackUnderflow;
        self.len -= 1;
        return self.data[self.len];
    }

    fn items(self: *const Stack) []const i64 {
        return self.data[0..self.len];
    }
};

pub fn main() void {
    var s = Stack{};
    s.push(10) catch unreachable;
    s.push(20) catch unreachable;
    std.debug.print("stack: {any}\n", .{s.items()});

    const top = s.pop() catch unreachable;
    std.debug.print("popped {d}, stack: {any}\n", .{ top, s.items() });

    _ = s.pop() catch unreachable;
    if (s.pop()) |v| {
        std.debug.print("unexpected {d}\n", .{v});
    } else |err| {
        std.debug.print("error: {t}\n", .{err});
    }
}
stack: { 10, 20 }
popped 20, stack: { 10 }
error: StackUnderflow

Step 3: The execution loop

Now combine them. The VM keeps a program counter (pc): the index of the next instruction. Each step fetches program[pc], advances pc, and executes the instruction with a switch. Errors from the stack propagate out of run with try:

zig · try it yourself
const std = @import("std");

const Instr = union(enum) {
    push: i64,
    add,
    sub,
    mul,
    print,
    halt,
};

const Vm = struct {
    stack: [8]i64 = undefined,
    sp: usize = 0,

    fn push(self: *Vm, v: i64) !void {
        if (self.sp == self.stack.len) return error.StackOverflow;
        self.stack[self.sp] = v;
        self.sp += 1;
    }

    fn pop(self: *Vm) !i64 {
        if (self.sp == 0) return error.StackUnderflow;
        self.sp -= 1;
        return self.stack[self.sp];
    }

    fn run(self: *Vm, program: []const Instr) !void {
        var pc: usize = 0;
        while (pc < program.len) {
            const instr = program[pc];
            pc += 1;
            switch (instr) {
                .push => |n| try self.push(n),
                .add, .sub, .mul => {
                    const b = try self.pop();
                    const a = try self.pop();
                    try self.push(switch (instr) {
                        .add => a + b,
                        .sub => a - b,
                        .mul => a * b,
                        else => unreachable,
                    });
                },
                .print => std.debug.print("{d}\n", .{self.stack[self.sp - 1]}),
                .halt => return,
            }
        }
    }
};

pub fn main() void {
    // (2 + 3) * (10 - 4)
    const program = [_]Instr{
        .{ .push = 2 },  .{ .push = 3 }, .add,
        .{ .push = 10 }, .{ .push = 4 }, .sub,
        .mul,            .print,         .halt,
    };
    var vm = Vm{};
    vm.run(&program) catch |err| std.debug.print("vm error: {t}\n", .{err});

    const broken = [_]Instr{ .{ .push = 1 }, .add };
    var vm2 = Vm{};
    vm2.run(&broken) catch |err| std.debug.print("vm error: {t}\n", .{err});
}
30
vm error: StackUnderflow

Notice the inner switch (instr) inside the arithmetic branch: grouping add, sub and mul lets them share the pop/push code. The else => unreachable documents that no other instruction can reach that point.

Step 4: Jumps and loops

A real machine needs control flow. We add dup (duplicate the top value), jump_if_pos (pop a value; if it is positive, jump to an instruction index) and jump. With these, the VM can run a countdown loop:

zig · try it yourself
const std = @import("std");

const Instr = union(enum) {
    push: i64,
    add,
    sub,
    mul,
    dup,
    print,
    jump: usize,
    jump_if_pos: usize,
    halt,
};

const Vm = struct {
    stack: [16]i64 = undefined,
    sp: usize = 0,
    steps: usize = 0,

    fn push(self: *Vm, v: i64) !void {
        if (self.sp == self.stack.len) return error.StackOverflow;
        self.stack[self.sp] = v;
        self.sp += 1;
    }

    fn pop(self: *Vm) !i64 {
        if (self.sp == 0) return error.StackUnderflow;
        self.sp -= 1;
        return self.stack[self.sp];
    }

    fn run(self: *Vm, program: []const Instr) !void {
        var pc: usize = 0;
        while (pc < program.len) {
            self.steps += 1;
            if (self.steps > 1000) return error.TooManySteps; // guard against infinite loops
            const instr = program[pc];
            pc += 1;
            switch (instr) {
                .push => |n| try self.push(n),
                .add, .sub, .mul => {
                    const b = try self.pop();
                    const a = try self.pop();
                    try self.push(switch (instr) {
                        .add => a + b,
                        .sub => a - b,
                        .mul => a * b,
                        else => unreachable,
                    });
                },
                .dup => {
                    const v = try self.pop();
                    try self.push(v);
                    try self.push(v);
                },
                .print => {
                    const v = try self.pop();
                    try self.push(v);
                    std.debug.print("{d} ", .{v});
                },
                .jump => |target| pc = target,
                .jump_if_pos => |target| {
                    if (try self.pop() > 0) pc = target;
                },
                .halt => return,
            }
        }
    }
};

pub fn main() void {
    const countdown = [_]Instr{
        .{ .push = 5 }, //         0: counter = 5
        .print, //                 1: loop: print counter
        .{ .push = 1 }, //         2
        .sub, //                   3: counter - 1
        .dup, //                   4
        .{ .jump_if_pos = 1 }, //  5: if counter > 0 goto loop
        .halt, //                  6
    };
    var vm = Vm{};
    vm.run(&countdown) catch |err| std.debug.print("vm error: {t}", .{err});
    std.debug.print("\nfinished in {d} steps\n", .{vm.steps});

    const forever = [_]Instr{.{ .jump = 0 }};
    var vm2 = Vm{};
    vm2.run(&forever) catch |err| std.debug.print("vm error: {t}\n", .{err});
}
5 4 3 2 1 
finished in 27 steps
vm error: TooManySteps

The step counter is a simple safety net: without it, a buggy program would hang the VM.

Step 5: A text assembler

Writing .{ .push = 5 } by hand is tedious. The last step parses a program from text such as push 5 / mul into instructions. The number of instructions isn't known in advance, so we collect them in an ArrayList backed by an allocator — and we report parse errors with the line number.

To make real programs possible we also add three classic stack instructions: pop (discard the top), swap (exchange the top two values) and over (copy the second value to the top). With them, computing a factorial needs only the stack:

zig · try it yourself
const std = @import("std");

const Instr = union(enum) {
    push: i64,
    pop,
    add,
    sub,
    mul,
    dup,
    swap,
    over,
    print,
    jump: usize,
    jump_if_pos: usize,
    halt,
};
const Tag = std.meta.Tag(Instr);

fn assemble(allocator: std.mem.Allocator, source: []const u8, err_line: *usize) ![]Instr {
    var list: std.ArrayList(Instr) = .empty;
    errdefer list.deinit(allocator);

    var lines = std.mem.splitScalar(u8, source, '\n');
    var line_no: usize = 0;
    while (lines.next()) |raw| {
        line_no += 1;
        err_line.* = line_no;
        // strip a comment starting with ';' and the surrounding spaces
        const code = raw[0 .. std.mem.indexOfScalar(u8, raw, ';') orelse raw.len];
        const line = std.mem.trim(u8, code, " \t");
        if (line.len == 0) continue;

        var parts = std.mem.tokenizeScalar(u8, line, ' ');
        const name = parts.next().?;
        const tag = std.meta.stringToEnum(Tag, name) orelse return error.UnknownInstruction;
        const arg = parts.next();

        const instr: Instr = switch (tag) {
            .push => .{ .push = try std.fmt.parseInt(i64, arg orelse return error.MissingArgument, 10) },
            .jump => .{ .jump = try std.fmt.parseInt(usize, arg orelse return error.MissingArgument, 10) },
            .jump_if_pos => .{ .jump_if_pos = try std.fmt.parseInt(usize, arg orelse return error.MissingArgument, 10) },
            inline else => |t| @unionInit(Instr, @tagName(t), {}),
        };
        try list.append(allocator, instr);
    }
    return list.toOwnedSlice(allocator);
}

const Vm = struct {
    stack: [16]i64 = undefined,
    sp: usize = 0,

    fn push(self: *Vm, v: i64) !void {
        if (self.sp == self.stack.len) return error.StackOverflow;
        self.stack[self.sp] = v;
        self.sp += 1;
    }

    fn pop(self: *Vm) !i64 {
        if (self.sp == 0) return error.StackUnderflow;
        self.sp -= 1;
        return self.stack[self.sp];
    }

    fn run(self: *Vm, program: []const Instr) !void {
        var pc: usize = 0;
        var steps: usize = 0;
        while (pc < program.len) : (steps += 1) {
            if (steps > 1000) return error.TooManySteps;
            const instr = program[pc];
            pc += 1;
            switch (instr) {
                .push => |n| try self.push(n),
                .pop => _ = try self.pop(),
                .add, .sub, .mul => {
                    const b = try self.pop();
                    const a = try self.pop();
                    try self.push(switch (instr) {
                        .add => a + b,
                        .sub => a - b,
                        .mul => a * b,
                        else => unreachable,
                    });
                },
                .dup, .swap, .over => {
                    const b = try self.pop();
                    const a = if (instr == .dup) b else try self.pop();
                    switch (instr) {
                        .dup => {
                            try self.push(b);
                            try self.push(b);
                        },
                        .swap => {
                            try self.push(b);
                            try self.push(a);
                        },
                        .over => {
                            try self.push(a);
                            try self.push(b);
                            try self.push(a);
                        },
                        else => unreachable,
                    }
                },
                .print => {
                    const v = try self.pop();
                    std.debug.print("{d}\n", .{v});
                    try self.push(v);
                },
                .jump => |target| pc = target,
                .jump_if_pos => |target| {
                    if (try self.pop() > 0) pc = target;
                },
                .halt => return,
            }
        }
    }
};

fn runSource(allocator: std.mem.Allocator, title: []const u8, source: []const u8) void {
    std.debug.print("== {s}\n", .{title});
    var line: usize = 0;
    const program = assemble(allocator, source, &line) catch |err| {
        std.debug.print("assembler error on line {d}: {t}\n", .{ line, err });
        return;
    };
    defer allocator.free(program);

    var vm = Vm{};
    vm.run(program) catch |err| std.debug.print("runtime error: {t}\n", .{err});
}

pub fn main() void {
    var gpa: std.heap.DebugAllocator(.{}) = .init;
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();

    runSource(allocator, "area of a 7 x 6 rectangle",
        \\push 7      ; width
        \\push 6      ; height
        \\mul
        \\print
    );

    runSource(allocator, "factorial of 5",
        \\push 1          ; 0: result         stack: r
        \\push 5          ; 1: n              stack: r n
        \\dup             ; 2: loop start     stack: r n n
        \\jump_if_pos 5   ; 3: n > 0 -> body  stack: r n
        \\jump 12         ; 4: done
        \\swap            ; 5:                stack: n r
        \\over            ; 6:                stack: n r n
        \\mul             ; 7:                stack: n r*n
        \\swap            ; 8:                stack: r*n n
        \\push 1          ; 9
        \\sub             ; 10:               stack: r*n n-1
        \\jump 2          ; 11
        \\pop             ; 12: drop n        stack: r
        \\print           ; 13
    );

    runSource(allocator, "typo",
        \\push 2
        \\mull
    );

    runSource(allocator, "missing value",
        \\push 1
        \\add
    );
}
== area of a 7 x 6 rectangle
42
== factorial of 5
120
== typo
assembler error on line 2: UnknownInstruction
== missing value
runtime error: StackUnderflow

A few details worth noticing:

  • std.meta.Tag(Instr) is the enum behind the tagged union, so stringToEnum turns "mul" into .mul. Adding a new instruction to Instr automatically makes it available in the assembler.
  • inline else => |t| @unionInit(…) generates one branch per remaining tag at compile time, creating the payload-less instructions without listing them one by one.
  • errdefer list.deinit(allocator) frees the partly built list if parsing fails; on success toOwnedSlice hands the memory to the caller, who frees it with defer allocator.free(program). The DebugAllocator would report any leak.
  • The comments in the factorial program track the stack after each instruction — the standard way to reason about stack-machine code.

Your turn

  1. Division. Add div, returning error.DivisionByZero when the divisor is 0, and use @divTrunc.
  2. Labels. Let the assembler accept loop: lines and jump loop, resolving labels to instruction indexes in a first pass with a std.StringHashMapUnmanaged(usize).
  3. Overflow. Replace a * b with @mulWithOverflow and report error.Overflow instead of panicking — then try the factorial of 25.
  4. Tracing. Add a trace: bool field to Vm that prints the program counter, instruction and stack before every step.

Each change touches only a few lines, because the compiler's exhaustive switch checks tell you exactly where a new instruction still needs handling.

Test yourself

Why is Instr a tagged union rather than an enum?

  1. Unions are faster
  2. Some instructions carry data (like the number for push) and others don't
  3. Enums cannot be switched on
  4. To save memory only

What does errdefer list.deinit(allocator) achieve in assemble?

  1. Frees the list after every call
  2. Frees the partly built list only if the function returns an error
  3. Prints the error
  4. Nothing, it is optional decoration

What protects the VM from running forever on jump 0?

  1. The DebugAllocator
  2. The step counter returning error.TooManySteps
  3. Zig's runtime
  4. Nothing