Bytecode Linker v5

medium · compilers, bytecode, linking

Bytecode Linker v5

Link multiple module bytecode blobs into a single Bytecode program.

Function signature

func Link(mods []ModuleBytecode) (Bytecode, error)

Types

  • ModuleBytecode has Name, Imports, Exports, Bytecode.
  • Bytecode has Main []Instr and Functions []Function.
  • Function has ID, Name, Params, Code []Instr.
  • Instr has Op, Int, Str.

Rules

  • Module names must be unique.
  • main must exist and be last in the slice.
  • Each import must reference an earlier module by name.
    • Unknown module: unknown module: <name>
    • Import of future module: import of future module: <name>

Linking steps

  1. Validate module order and imports.
  2. Merge function tables with ID rebasing.
  3. Patch every MAKE_CLOSURE instruction to the rebased ID.
  4. Rebase JUMP and JUMP_IF_FALSE targets in each module’s Main by the number of Main instructions already emitted. Keep function-local jump indexes unchanged.
  5. Concatenate module Main code in order.

Inputs use valid local jump targets (including the one-past-end exit) and dense local function IDs 0..len(Functions)-1; function slice order need not equal ID order. Do not mutate input artifacts. Repeated linking of the same inputs must produce equivalent output. Copy instruction slices before patching.

Notes

  • Preserve module order from the input.
  • Return the first error encountered.
  • Keep the linker readable and straightforward.

Before implementation

Use the module’s worked reconstruction and independent debugging lab to predict an intermediate artifact first. Preserve one failing counterexample while implementing the stated API. The lesson’s transfer task uses a fresh case after the guided trace.

Run tests to see results
No issues detected
    Join Discord