Compile to Bytecode v5

hard · compilers, bytecode, modules

Compile to Bytecode v5

Lower v5 modules into stack-based bytecode with module initialization and export maps.

Function signature

func CompileModules(prog *Program) []ModuleBytecode

Types

Use the provided types:

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

Module initialization

Each module compiles to init code:

ENTER_SCOPE
(import aliases)
(module statements)
PUSH_STR "exportName"
LOAD exportName
MAKE_MAP N
EXIT_SCOPE
DEFINE_CONST moduleName

Imports

For each import X as Y emit:

LOAD X
DEFINE_CONST Y

Member access

m.add compiles to:

LOAD m
PUSH_STR "add"
GET_INDEX

Notes

  • Assume the AST is already valid.
  • Preserve module order from the program.
  • Exports should list exported names in the order discovered.
  • Keep the compiler 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