Part III — Advanced Systems · Chapter 12 · Lesson 5 of 7 · 5 min read
Lesson 5: VM Execution, Stack Behavior, Calls, Closures, Modules, and Exceptions
Lesson level: Advanced
Purpose: Follow the virtual machine as it executes a code object: the fetch–execute loop, frames, calls and returns, captured variables, module loading, and exception unwinding.
Release note: opcode names and internal structures are illustrative models. Verify behaviour against your installed v0.63 release.
Learning objectives
By the end of this lesson, you should be able to:
- Describe the VM fetch–execute loop.
- Explain what a call frame holds and how calls push and pop frames.
- Explain how closures capture variables.
- Describe how modules are loaded once and cached.
- Trace how an exception unwinds frames to a handler.
5.1 The fetch–execute loop
The VM keeps an instruction pointer into the current code object. Each step reads the instruction at that pointer, advances the pointer, and performs the operation. Jumps simply set the pointer. The loop ends when the top-level code returns or an unhandled exception escapes.
loop:
instr = code[ip]
ip = ip + 1
check instruction budget
execute instr
goto loop
The budget check is where the instruction limits from Chapter 14 are enforced, so a runaway loop stops at a predictable point.
5.2 Call frames
| Frame field | Purpose |
|---|---|
| Code object | Which instructions are running |
| Instruction pointer | Where execution resumes |
| Locals | Parameter and local variable slots |
| Operand stack | Working values for this call |
| Handler table | Active try/catch regions |
| Link to caller | Where to return |
5.3 Calling a function
reason(12)
LOAD_NAME reason
LOAD_CONST #0 ; 12
CALL 1
CALL 1 pops one argument and the function, checks arity, creates a new frame, binds the argument to the parameter slot, and starts executing the function code. The caller's frame waits, with its own stack intact.
5.4 Returning
RETURN_VALUE pops the result, discards the callee frame, and pushes the result onto the caller's stack. Execution continues at the caller's saved instruction pointer. A function that ends without an explicit return yields null.
5.5 Recursion and the stack limit
Each call adds a frame. Deep or unbounded recursion consumes frames until the configured recursion or stack limit is reached, at which point the VM raises a limit error instead of exhausting host memory.
5.6 Closures
When an inner function refers to a variable of an enclosing function, the compiler marks that variable as captured. The VM stores it in a cell that both functions share, so the inner function sees updates even after the outer call returns.
function make_counter() {
let count = 0
return function() { count += 1; return count }
}
let next = make_counter()
print next() # 1
print next() # 2
Each call to make_counter creates a fresh cell, so separate counters do not interfere.
5.7 Modules
An import asks the VM's module loader for a module by name. On first import the loader locates the source or PEAC, validates it, runs its top-level code in a fresh module environment, and caches the result. Later imports return the cached module, so initialization runs once.
- Exports are the names the module chooses to expose (Chapter 9).
- Circular imports can observe a partially initialized module; keep initialization free of cross-module calls.
- Module loading obeys the same capability rules as other file access.
5.8 Exceptions
A try block registers a handler region in the frame. When an instruction raises an error, the VM looks for a handler covering the current instruction pointer. If none exists in this frame, it discards the frame and checks the caller, repeating until a handler is found or the stack is empty.
function parse_qty(text) {
try {
return std.convert.to_int(text)
} catch err {
return 0
} finally {
print "parsed"
}
}
5.9 Unwinding and finally
While unwinding, the VM runs every finally block it passes, in order from innermost to outermost. Operand stack contents above the handler's saved depth are discarded, so a handler always starts with a consistent stack.
5.10 Errors the VM itself raises
| Error | Raised when |
|---|---|
| Type error | An operator receives incompatible values |
| Name error | A name cannot be resolved at runtime |
| Arity error | A call passes the wrong number of arguments |
| Limit error | Instruction, time, memory, recursion, or output budget is exhausted |
| Permission error | Code requests a capability the host did not grant |
Limit and permission errors should usually not be caught by script code; the host needs to see them.
5.11 Worked trace
Trace print reason(12) where reason returns "BULK" when quantity is at least 10:
- Top frame pushes the function and 12, then calls.
- A new frame binds qty = 12.
- The comparison pushes true; the conditional jump falls through.
- "BULK" is pushed and returned.
- The callee frame is discarded; "BULK" is on the top frame's stack.
- print pops and outputs it.
5.12 Common mistakes
| Mistake | Consequence | Fix |
|---|---|---|
| Catching limit errors in scripts | Host loses the signal | Let them propagate |
| Heavy work during module initialization | Slow or circular imports | Initialize lazily in functions |
| Assuming closures copy values | Surprising shared state | Remember captured cells are shared |
| Unbounded recursion | Limit error at runtime | Use loops or bounded depth |
5.13 Guided practice
- Draw the frames during a call chain of three functions.
- Predict output for two independent counters from make_counter.
- Trace which finally blocks run when an error passes through two frames.
- Explain why a module's top-level print appears only once.
5.14 Hands-on lab
Using the VM debugger, step through an order_rules call that raises a validation error inside a nested function and is caught two frames up. Record the frames, the handler that matched, and the stack depth at each point.
Deliverable: a frame-by-frame trace and a short explanation of the unwinding path.
5.15 Review questions
- What happens on each iteration of the fetch–execute loop?
- What does a call frame contain?
- How does a closure keep access to an outer variable?
- Why does a module initialize only once?
- In what order do finally blocks run during unwinding?
5.16 Applied challenge
Design a test that proves the interpreter and VM unwind exceptions identically, including finally ordering and the value returned from a handler.
Lesson summary
- The VM runs a fetch–execute loop with a budget check on every instruction.
- Calls push frames; returns pop them and pass values back.
- Closures share captured cells; modules initialize once and are cached.
- Exceptions unwind frames to the nearest handler, running finally blocks on the way.
Transition to Lesson 6
Understanding execution is easier when you can see it. Lesson 6 covers disassembly, profiling, and comparing interpreter and VM execution.
Lesson status: Ready for review.