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
CompiledFnentries whose captured variables are prepended as leading hidden parameters. At closure creation (Op::MakeClosure), captured values are snapshotted intoValue::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:
- Flattens the chain of
IndexandFieldsteps from root identifier to leaf. - Evaluates the root variable once into temp local
container_slots[0]. - Walks down the chain, evaluating each index expression exact once into
index_slots[i]and saving each intermediate container incontainer_slots[i]. - Computes the new leaf value (for compound ops like
+=, reads the current leaf using the already-savedcontainer_slots[last]andindex_slots[last]). - Walks backwards from leaf to root, emitting
Op::SetIndex/Op::SetFieldand storing the updated root back into the root variable.