Internals · 03

Bytecode VM

How ochre-vm compiles ASTs to stack-based bytecode chunks, executes call frames, implements closures, and compiles evaluate-once nested lvalues.

ochre-vm is a fast, clean stack-based bytecode virtual machine written in safe Rust. It executes the complete Ochre language — including closures, structs, enums, pattern matching, JSON, HTTP, and concurrency.

Bytecode Representation (bytecode.rs)

Each compiled function (and the top-level script) is represented as a Chunk:

  • code: Vec<Op> — flat instruction array (Const, GetLocal, SetLocal, GetGlobal, SetGlobal, Add, JumpIfFalse, MakeList, MakeMap, GetIndex, SetIndex, GetField, SetField, MakeClosure, Call, Return, Spawn, etc.).
  • spans: Vec<Span> — parallel source span table so every runtime error points to the exact offending token.
  • constants: Vec<Value> — constant pool for literals and strings.

Inspect any program's generated bytecode with ochre disasm app.och.

Call Frames & Closures (vm.rs)

  • Each active function invocation pushes a CallFrame { fn_id, ip, locals }.
  • Closures are compiled as anonymous CompiledFn entries whose captured variables are prepended as leading hidden parameters. At closure creation (Op::MakeClosure), captured values are snapshotted into Value::Closure { fn_id, captures: Arc<Vec<Value>> }.

Evaluate-Once Nested Lvalues (compiler.rs)

Because List, Map, and Struct use Copy-on-Write (Op::SetIndex / Op::SetField return the updated container on the stack), nested assignments like rows[f()][g()] += 5 cannot simply mutate a raw pointer in place.

compile_nested_assign solves this cleanly in five steps:

  1. Flattens the chain of Index and Field steps from root identifier to leaf.
  2. Evaluates the root variable once into temp local container_slots[0].
  3. Walks down the chain, evaluating each index expression exact once into index_slots[i] and saving each intermediate container in container_slots[i].
  4. Computes the new leaf value (for compound ops like +=, reads the current leaf using the already-saved container_slots[last] and index_slots[last]).
  5. Walks backwards from leaf to root, emitting Op::SetIndex / Op::SetField and storing the updated root back into the root variable.