PeaBox Lab › PeaLang › Learn › Chapter 12 › Lesson 5

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:

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 fieldPurpose
Code objectWhich instructions are running
Instruction pointerWhere execution resumes
LocalsParameter and local variable slots
Operand stackWorking values for this call
Handler tableActive try/catch regions
Link to callerWhere 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.

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

ErrorRaised when
Type errorAn operator receives incompatible values
Name errorA name cannot be resolved at runtime
Arity errorA call passes the wrong number of arguments
Limit errorInstruction, time, memory, recursion, or output budget is exhausted
Permission errorCode 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:

5.12 Common mistakes

MistakeConsequenceFix
Catching limit errors in scriptsHost loses the signalLet them propagate
Heavy work during module initializationSlow or circular importsInitialize lazily in functions
Assuming closures copy valuesSurprising shared stateRemember captured cells are shared
Unbounded recursionLimit error at runtimeUse loops or bounded depth

5.13 Guided practice

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

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

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.

← Previous Next →