v5 Modules: imports, exports, and a linker mindset

Lesson, slides, and applied problem sets.

View Slides

Lesson

v5 Modules: imports, exports, and a linker mindset

Why modules?

We now have a real language. Modules make it scalable:

  • avoid global name collisions
  • expose only what is intentional
  • make compilation and linking a real stage

Syntax overview

module math {
  export fn add(a, b) { return a + b; }
  let secret = 7;
}

module main {
  import math as m;
  let x = m.add(1, 2);
}

Rules

  • module NAME { ... } defines a compilation unit.
  • import NAME; or import NAME as alias;
  • export may only prefix fn or let/var/const.
  • Qualified access uses . (e.g. math.add).
  • main is the entry module and must appear last.
  • A module may only import modules defined earlier in the source.

Runtime model

Modules are compiled into maps of their exports. This keeps the VM simple:

  • module init code builds a map { "add": add, ... }
  • the map is stored as a global const named after the module
  • math.add compiles to math["add"]

This gives us a clear, teachable linker story without new opcodes.


Module Items