4b, a tiny fantasy console

A 16×16 fantasy console and its toolchain, wired together from composable Zig modules in a single build.zig.

I wrote earlier about Vex, a WebAssembly fantasy console. 4b is much smaller.

It is an independent reimplementation of 4BoD (4 Bits of DOOM), a fantasy console from the 2017 FC Dev jam. The entire machine fits in a short list:

  • 256 instructions of 12 bits each — 384 bytes of program memory
  • 16 registers, four bits each, plus a four-bit accumulator
  • a 16×16, one-bit screen
  • four buttons, no sound

The toolchain has three parts: assemble with 4a, run with 4b, compile with 4c.

Important: What I want to describe here is not the machine, but how those three programs and their shared libraries are wired together in build.zig.

The pieces

Each stage of the toolchain is its own source file:

src/
  -- shared
  isa.zig          opcode table, encode/decode
  rom.zig          12-bit words -> 384-byte image
  dia.zig          diagnostics
  vm.zig           the machine

  -- 4a, the assembler
  4a.zig           CLI
  lexer.zig        tokenizer
  parser.zig       lines -> items
  symbols.zig      pass 1: labels and constants
  codegen.zig      pass 2: emit words

  -- 4c, the compiler
  4c.zig           CLI
  4c/lexer.zig     tokenizer
  4c/parser.zig    recursive descent
  4c/ast.zig       syntax tree
  4c/sema.zig      folding, register allocation
  4c/codegen.zig   word emission, flag slots
  4c/emit_asm.zig  words -> 4A text
  4c/compiler.zig  pipeline

  -- the box
  4b.c             window and input (C + raylib)
  • Assembler: lex → parse → analyze → generate → pack

  • Compiler: lex → parse → sema → codegen → pack

    The compiler can also emit its words back out as 4A assembly.

Note: Several of those files are needed by two programs at once — which runs into a Zig rule about module roots. That is where the build file gets interesting.

One file, one module, many consumers

The way around the module-root rule is to create the module object once and refer to it by name everywhere. build.zig defines a small helper that wraps a source file in a module:

fn zigModule(
    b: *std.Build,
    root_source_file: []const u8,
    target: std.Build.ResolvedTarget,
    optimize: std.builtin.OptimizeMode,
) *std.Build.Module {
    return b.createModule(.{
        .root_source_file = b.path(root_source_file),
        .target = target,
        .optimize = optimize,
    });
}

The leaves

Here is how build() creates the shared leaves:

// Shared leaf modules. The 4a/4c implementations reach these through
// named imports (not file paths) so that the same implementation file can
// serve as the root of both a CLI executable and an embeddable static
// library without any file belonging to two module graphs.
const dia_mod = zigModule(b, "src/dia.zig", target, optimize);
const isa_mod = zigModule(b, "src/isa.zig", target, optimize);
const rom_mod = zigModule(b, "src/rom.zig", target, optimize);

const shared_imports = [_]std.Build.Module.Import{
    .{ .name = "dia", .module = dia_mod },
    .{ .name = "isa", .module = isa_mod },
    .{ .name = "rom", .module = rom_mod },
};

Pipelines and consumers

The compiler needs one more import than the assembler: its tests run generated code on the VM, so the compiler’s import set adds vm. The two pipelines are modules built from those imports:

const vm_mod = zigModule(b, "src/vm.zig", target, optimize);

const com_imports = shared_imports ++ [_]std.Build.Module.Import{
    .{ .name = "vm", .module = vm_mod },
};

const asm_mod = b.createModule(.{
    .root_source_file = b.path("src/assembler.zig"),
    .target = target,
    .optimize = optimize,
    .imports = &shared_imports,
});

const com_mod = b.createModule(.{
    .root_source_file = b.path("src/4c/compiler.zig"),
    .target = target,
    .optimize = optimize,
    .imports = &com_imports,
});

From here the composition is almost mechanical. The 4a executable imports asm_mod as assembler; the 4c executable imports com_mod as compiler:

const assembler = b.addExecutable(.{
    .name = "4a",
    .root_module = b.createModule(.{
        .root_source_file = b.path("src/4a.zig"),
        .imports = &.{
            .{ .name = "assembler", .module = asm_mod },
            .{ .name = "dia", .module = dia_mod },
        },
    }),
});

const compiler = b.addExecutable(.{
    .name = "4c",
    .root_module = b.createModule(.{
        .root_source_file = b.path("src/4c.zig"),
        .imports = &.{
            .{ .name = "compiler", .module = com_mod },
            .{ .name = "dia", .module = dia_mod },
            .{ .name = "rom", .module = rom_mod },
        },
    }),
});

The box links both pipelines, plus the VM:

const vm_lib  = b.addLibrary(.{ .name = "vm",  .root_module = vm_mod });
const asm_lib = b.addLibrary(.{ .name = "asm", .root_module = asm_mod });
const com_lib = b.addLibrary(.{ .name = "compile", .root_module = com_mod });

box.root_module.linkLibrary(vm_lib);
box.root_module.linkLibrary(asm_lib);
box.root_module.linkLibrary(com_lib);

The same asm_mod object is an import in one place and a library root in another. No file is rooted twice, and no implementation is copied.

Note: The box’s root module has no Zig source file at all. It is a pure C module — src/4b.c, compiled as C23 — that links three Zig static libraries and raylib.

The whole graph looks like this:

The build module graph: shared leaf modules feed two pipelines, each both a CLI import and a static library; the three libraries link into the C box

The C boundary

The three Zig libraries talk to the box through five plain exported functions:

fourb_vm_init(VM *vm)
fourb_vm_tick(VM *vm)
fourb_vm_load_rom(VM *vm, const uint8_t *rom, size_t len)
fourb_assemble(const char *path, const char *src, size_t src_len,
               uint8_t *out, char *err, size_t err_len)
fourb_compile(const char *path, const char *src, size_t src_len,
              uint8_t *out, char *err, size_t err_len)

The three VM functions all take a pointer to the same VM struct — an extern struct of exactly 804 bytes. Its field offsets are asserted on both sides of the boundary — @offsetOf in a Zig test, _Static_assert in 4b.c:

test "vm: c abi layout matches 4b.c" {
    try std.testing.expectEqual(0,   @offsetOf(VM, "program"));
    try std.testing.expectEqual(512, @offsetOf(VM, "regs"));
    try std.testing.expectEqual(528, @offsetOf(VM, "acc"));
    try std.testing.expectEqual(529, @offsetOf(VM, "screen"));
    try std.testing.expectEqual(785, @offsetOf(VM, "flags"));
    try std.testing.expectEqual(801, @offsetOf(VM, "pc"));
    try std.testing.expectEqual(802, @offsetOf(VM, "buttons"));
    try std.testing.expectEqual(804, @sizeOf(VM));
}

Both sides assert the same offsets, so a layout change on either side breaks the build immediately rather than corrupting a running cart.

Tests and examples use the same pieces

The build graph is reused two ways: the test step runs the module objects directly, while the examples step runs the executables built from them. For tests, that means pointing addTest at the modules rather than at source files:

const suites = [_]*std.Build.Module{
    assembler.root_module, // CLI + golden/negative tests
    asm_mod,               // assembler pipeline
    rom_mod,               // bit-packing
    dia_mod,               // diagnostics
    isa_mod,               // ISA table
    compiler.root_module,  // CLI
    com_mod,               // compiler pipeline
    vm_lib.root_module,    // VM opcodes
};

for (suites) |suite| {
    const suite_tests = b.addTest(.{ .root_module = suite });
    const run_suite_tests = b.addRunArtifact(suite_tests);
    test_step.dependOn(&run_suite_tests.step);
}

Around seventy inline tests live in those eight suites: golden ROMs for the assembler, opcode semantics and C-ABI offsets for the VM, and branch-lowering tests that run generated code on the VM through that vm import.

The examples step uses the tools built from those modules. Each example is built by both toolchains, with suffixed outputs so the canonical ROMs are not clobbered:

// Cross matrix: every example also builds with the other toolchain so
// a broken fill.4c or move.4a fails the build.
for ([_][]const u8{ "move", "diag", "dpad" }) |name|
    addExampleOut(b, examples_step, assembler, name, "4a", "-4a");

for ([_][]const u8{ "halt", "line", "fill" }) |name|
    addExampleOut(b, examples_step, compiler, name, "4c", "-4c");

The compiler can emit assembly with -S, and that output is valid 4A. So the cross-build is more than a convenience: it checks the promise that a program compiled directly and a program compiled to assembly and then assembled produce the same 384 bytes.

Keeping raylib small

The box needs one external dependency: raylib, for the window. It is fetched lazily, and rather than link its static archive, addRaylib compiles just three of its C files into the box’s module — rcore.c, rshapes.c and rglfw.c — with the unused modules disabled by macros:

mod.addCMacro("SUPPORT_MODULE_RTEXTURES", "0");
mod.addCMacro("SUPPORT_MODULE_RTEXT",     "0");
mod.addCMacro("SUPPORT_MODULE_RMODELS",   "0");
mod.addCMacro("SUPPORT_MODULE_RAUDIO",    "0");

Because the dependency is lazy, the compiler and its tests still build when raylib is unavailable — b.lazyDependency(...) orelse return simply skips the box. A missing graphics library should not stop zig build test.

Running it

zig build                      # build 4a, 4b and 4c into zig-out/bin/
zig build test                 # eight test suites
zig build examples             # twelve ROMs, through both toolchains

zig build run -- examples/diag.4b
zig build run -- examples/move.4c    # the box compiles sources on startup

The box also has a headless mode, which is what CI uses as a smoke test:

zig-out/bin/4b -d 2550 examples/fill.4c
zig-out/bin/4b -p                      # list palettes

-d N ticks N instructions, then dumps the final state: pc, accumulator, all sixteen registers and flags, and the 16×16 screen — # for lit pixels, . for dark ones.

Note: The build targets Zig 0.17.1, available from ziglang.org. CI installs it with mlugg/setup-zig.

In summary

The build file mirrors the structure of the program: leaves created once, two pipelines composed from them, and each pipeline used as both a CLI import and a library root without being restated. Tests run those module objects directly; examples run the tools built from them. One graph, defined in one file.

Peter Hellberg

My name is Peter Hellberg and I’m a Systems Developer in Stockholm, Sweden.