Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Module binary and verification

The compiled module artifact — a .rutc file — is a versioned, deterministic, hash-stable serialization of a linked program. Encoder and decoder live in rut-core/src/binary.rs; this page is the layout, the verification contract, and the constant-pool rules. The loader that runs verification is Loading and the embed loop.

Program shape

Everything the VM runs is one Program:

pub struct Program {
    pub name: String,               // module / program name
    pub scope: ScopeId,             // stable module scope (0 if unset)
    pub interner: Interner,         // every IdentId in the program
    pub surface: Surface,           // exports, for using modules
    pub inst_types: Vec<InstTy>,    // the instantiation ledger
    pub inst_fns: Vec<InstFn>,      //   — link unifies rows by key
    pub types: TypeTable,           // type descriptors, dense ids
    pub ifaces: Vec<IfaceDesc>,     // interface tables
    pub iface_slots: Vec<(u32, u32)>,   // global interface-member slots
    pub vtables: Vec<Vec<Option<u32>>>, // per type: slot -> func id
    pub disposal_impls: Vec<Option<u32>>, // per type: dispose fn id
    pub consts: Vec<ConstVal>,      // the constant pool
    pub funcs: Vec<FuncCode>,       // the code ([Typed bytecode](typed-bytecode.md))
    pub exports: Vec<(IdentId, u32)>,   // host-callable names
    pub templates: Vec<TemplateRow>,    // instantiation-independent bodies
    pub template_stubs: Vec<TemplateStub>, // bound-member stubs of the window
    pub template_first_fid: u32,    // the window's first func
    pub template_end_fid: u32,      // one past its last
}

The Surface is the export record — functions, constants, types, interface declarations, inherent method surfaces, and the builtin names core publishes. It is how a using module binds a used module’s members at compile time, and it is part of the wire format too — the surface section rides after exports, and decode validates every row against the tables above it.

Wire layout

The format is little-endian, everywhere — encoded words, hash inputs, checksums. The first byte of a byte range is the least significant byte of word 0; this is a law pinned by unit tests, not an accident of the host.

offset  field
0       magic "RUTC"                      # 4 bytes
4       version: u32                      # VERSION = 22; refuses any other value
8       name: str
        name table: u32 count, then count × str
        types: u32 count, then per type { name: IdentId, kind }
        ifaces: u32 count, then per iface { name, methods[] }
        iface slots: u32 count, then (iface: u32, member: u32) pairs
        vtables: u32 entries, then per entry { ty, [(slot, func)] }  # sparse
        disposal rows: u32 entries, then (ty, func) pairs            # sparse
        consts: u32 count, then tag + payload (below)
        funcs: u32 count, then per func (below)
        exports: u32 count, then (name: IdentId, func: u32) pairs
        instantiation ledger: type rows, then fn identities   # below
        surface: namespace, funcs, consts, types + scope blocks + type
                 exports, interface decls, inherent method surfaces,
                 the native rows   # below
        templates: window first fid, window end (exclusive), then
                 u32 count, then per row (below)   # template bodies ride the binary
  • Templates (instantiation-independent bodies): after the surface, the wire carries the template window — template_first_fid and template_end_fid (every func in [first, end) is template-derived; the end is WIRE, not implicit, because a pack walk that materializes consumer-served instantiations into a decoded dep appends them AFTER the window — real ledger instantiations, not window entries), then one index row per exported generic decl: the kind tag (0 free / 1 method), the bound name(s), the #<param> placeholder rows in declaration order, the bound interface names, and the fid of the placeholder-compiled body (the body itself rides funcs). The window’s bound-member stubs ride beside the rows as (fid, param placeholder, member name) triples. Decode validates the window against the func table and every type id against the carried blocks; a consumer-spelled shape the pack-time ledger misses monomorphizes from these rows at link (see Bundles — instantiation independence).

  • Name table. Names are interner ids everywhere — type names, field names, enum members, interface/method names, function names, exports. The binary carries only the interner’s non-well-known tail; the fixed well-known prefix (self, nil, the builtin members, the primitives, …) is implied by the format. Decoding rebuilds the interner, so a decoded program is self-contained; at link, each module’s tail merges into the linked program’s table with the same rebase the type ids get.

  • Type kinds encode as a one-byte tag: nil, primitives, str, bytes, arrays, enums (member + value pairs), records (field table), interface objects, opaque, fn types, ?T, trace, Weak<T>.

  • Const tags: 0 i64, 1 f64, 2 bool, 4 str, 5 type id. Retired tags fail decode loudly rather than being reinterpreted.

  • Funcs serialize in full: name, param/ret types, is_method, capture count, the typed register table, both operand pools, the op stream, the span table, the parallel (line, col) position table, and the host-fn binding id when the function is a bodyless thunk.

  • Instantiation ledger: the owner-anchored identity of every instantiation the program compiled — type rows (owner, decl, arguments, type id) first, then fn identities (the kind, the substitution values, and the local fn id). Instantiation is owned by the declaring package, and link unifies rows sharing a key into ONE program-wide row; a consumer resolves its requests against a packaged binary’s ledger. Type exports carry their generic parameter lists beside this (see the surface below).

  • Surface: the exported surface rides after exports — the namespace head, funcs (with their async/host rows), consts, the carried type descriptors + scope blocks + type exports (generic exports carry their parameter names in order), interface declarations (SurfaceIface — every module publishes the interfaces it declares; a consumer links them into one merged table), the inherent method surfaces (the linkable-classes phase’s one row per class with methods), and the native rows with their ambient bits. There are no impl-registration rows on the wire — satisfaction is structural, so nothing registers. Names are ids into the name table above; decode rejects any id its tables cannot resolve.

  • Versioning policy: the version u32 must equal the toolchain’s exactly — there is no migration or best-effort decode. A byte that changes observable behavior bumps the version; artifacts from older compilers are refused with the standard version error.

Determinism

Same AST + same dependency versions + same compiler version ⇒ byte-identical bytes. Serialization order is fixed (mount order, manifest order, pool order), so binaries are cacheable by content hash, two builds diff to nothing, and a trace captured against one binary can be restored against a locally rebuilt one (Diagnostics, traces, and symbolication).

Strip levels

The symbolication data rides in every function: the spans table (pc → byte offset) and the parallel pos table (pc → line/col). A build that skips filling pos produces a binary whose traces still capture and render, degrading to pc-only text. Names ride the interner; dropping name strings is a publishing choice, and stripped traces restore through recompilation-by-determinism (see Diagnostics, traces, and symbolication).

Both strippable halves are format-legal encodings, not special cases: tail strings are opaque to the format (rewriting them to mangled %N names touches no id, opcode, or table), and 0/empty pos is the documented stripped encoding — a stripped binary decodes and verifies identically, no version bump required. The toolchain lane that produces and restores them — the mangle/keep-set law, the private .rutsym sidecar, and run --symbols — is Symbol stripping and .rutsym sidecars.

Type ids are program-global in a linked binary only because link already rebased them. At rest (per module, pre-link) ids are module-local; the boot table — the fixed primitive and builtin prefix — is shared by every module, and each module’s remaining types append after it. Every type id reachable from a type descriptor, interface signature, constant, function signature, or op operand is remapped at link, and type_id<T>() constants rebase with everything else.

type_id<T>() values are u32, comparable, and unique per instantiated type within a VM run: Vec<f32> ≠ Vec<f64>, [i32; 3] ≠ [i32; 4] (the constant length is part of the identity), and Point = Point across modules — identity is assigned at link (Reified types and layout).

Interface and vtable tables

  • Interfaces serialize with their member signatures; interface ids merge by name at link — an interface imported in one module and declared in another is one interface, and every capability probe and itable slot lands on the same global table.
  • Interface-member slots are a global table of (iface, member) pairs; vtables are per-type sparse maps slot → function id, merged at link. The slots a type fills are decided at its boxing sites — the boundaries where satisfaction was proved — and reach every call site from there. Nothing registers: a type that never crosses an interface-typed boundary fills nothing.

Verification (load time)

Before any code executes, the verifier re-checks every function in the binary:

checkrule
register rangeevery register operand < the function’s register-file size; NOREG legal only where an optional operand is defined
pool spansevery (off, argc) span lands inside its function’s argv / labels pool
type operandsevery type id names a row of the type table
jump targetsevery jmp/br/brtable target is in range
call aritycall argument counts match the callee’s declared signature
enum membersEnumNew member indices in range, target actually an enum
interface slotsCallI slot ids name a row of the global iface-slot table
host thunksbodyless functions are skipped (nothing to verify)

A failed verification is a load error naming the module and function — function name (#i): op @pc: message. Corrupted binaries never execute. Verification is structural: it re-establishes what the compiler enforced at emit time, so a hand-corrupted or stale artifact fails here instead of misbehaving at runtime.

The constant pool and load-time expressions

Module-level let and static initializers are folded at compile time. The surviving forms are: literals, enum members, operators over constants, record literals (immortal constant-pool cells), fixed-array literals, Vec<T>(n) / Vec::from([...]) blobs, the layout builtins, and Array<T, N>.len() with const-index bounds checks. A call to a user function in an initializer is a compile error — there is no deferred evaluation.

type_id<T>() never executes: it folds to a constant from the type table. debug position folding and trace symbolication are covered in Diagnostics, traces, and symbolication.

What is not here

A .d.rut declaration surface does not produce a binary — it has no bodies, so it compiles to a signature surface only (Host fns and declaration files). And a .rutbundle is binaries plus their container: the compiled packages ride as .rutc binaries (this format), splice-needed packages and host pkgs as source groups (Module bundles).