lex_bytecode/vm.rs
1//! M5: bytecode VM. Stack machine with effect dispatch through a host handler.
2
3use crate::op::*;
4use crate::program::*;
5use crate::value::{ActorCell, Value};
6use std::sync::{Arc, Mutex, OnceLock};
7use indexmap::IndexMap;
8use smol_str::SmolStr;
9use std::collections::{HashMap, VecDeque};
10
11// ── IC polymorphism instrumentation (throwaway, env-gated) ─────────
12// Enable with LEX_IC_STATS=1. With LEX_IC_STATS_OUT=<path> writes a
13// TSV to <path>.<pid> on each Vm drop; otherwise dumps to stderr.
14
15#[derive(Default)]
16struct IcStats {
17 sites: HashMap<(u32, u32), HashMap<u32, u64>>,
18}
19
20static IC_STATS: OnceLock<Mutex<IcStats>> = OnceLock::new();
21static IC_STATS_ENABLED: OnceLock<bool> = OnceLock::new();
22
23fn ic_stats_enabled() -> bool {
24 *IC_STATS_ENABLED.get_or_init(|| {
25 std::env::var("LEX_IC_STATS").map(|v| v == "1").unwrap_or(false)
26 })
27}
28
29fn record_ic_hit(fn_id: u32, site_idx: u32, shape_id: u32) {
30 let stats = IC_STATS.get_or_init(|| Mutex::new(IcStats::default()));
31 let mut s = stats.lock().unwrap();
32 *s.sites.entry((fn_id, site_idx)).or_default().entry(shape_id).or_insert(0) += 1;
33}
34
35pub fn dump_ic_stats() {
36 let Some(stats) = IC_STATS.get() else { return; };
37 let s = stats.lock().unwrap();
38 if s.sites.is_empty() { return; }
39 let mut out = String::from("fn_id\tsite_idx\tshape_id\thits\n");
40 let mut entries: Vec<_> = s.sites.iter().collect();
41 entries.sort_by_key(|((f, si), _)| (*f, *si));
42 for ((f, site), shapes) in entries {
43 let mut shape_entries: Vec<_> = shapes.iter().collect();
44 shape_entries.sort_by_key(|(sid, _)| **sid);
45 for (sid, hits) in shape_entries {
46 out.push_str(&format!("{f}\t{site}\t{sid}\t{hits}\n"));
47 }
48 }
49 match std::env::var("LEX_IC_STATS_OUT").ok() {
50 Some(path) => {
51 let pid = std::process::id();
52 let _ = std::fs::write(format!("{path}.{pid}"), out);
53 }
54 None => { eprint!("{out}"); }
55 }
56}
57
58#[derive(Debug, Clone, thiserror::Error)]
59pub enum VmError {
60 #[error("runtime panic: {0}")]
61 Panic(String),
62 #[error("type mismatch at runtime: {0}")]
63 TypeMismatch(String),
64 #[error("stack underflow")]
65 StackUnderflow,
66 #[error("unknown function: {0}")]
67 UnknownFunction(String),
68 #[error("effect handler error: {0}")]
69 Effect(String),
70 #[error("call stack overflow: recursion depth exceeded ({0})")]
71 CallStackOverflow(u32),
72 /// Refinement predicate failed at a call boundary (#209 slice 3).
73 /// Surfaced when a function declares `param :: Type{x | predicate}`,
74 /// the call-site arg couldn't be discharged statically (slice 2),
75 /// and the runtime evaluator finds the predicate is `false` for
76 /// the actual argument value. The `verdict` mirrors the shape of
77 /// `gate.verdict`-style records in `lex-trace`.
78 #[error("refinement violated: argument {param_index} of `{fn_name}` (binding `{binding}`): {reason}")]
79 RefinementFailed {
80 fn_name: String,
81 param_index: usize,
82 binding: String,
83 reason: String,
84 },
85 /// Integer division or modulo with a zero divisor (#696). Without
86 /// this guard the host `/`/`%` panics and takes the whole process
87 /// down — the crash report had a conformance harness compute a
88 /// rate over an empty set in teardown, far from any user-visible
89 /// division. Surfacing a catchable `VmError` instead keeps the
90 /// failure inside the language's error model. Float div/mod is
91 /// exempt: IEEE-754 yields inf/NaN rather than trapping.
92 #[error("integer {op} by zero")]
93 DivByZero {
94 /// `"division"` or `"modulo"` — names the offending operator.
95 op: &'static str,
96 },
97}
98
99/// Maximum simultaneous call frames. Defends against unbounded
100/// recursion in agent-emitted code: a body that calls itself
101/// without a base case would otherwise blow the host's native
102/// stack and crash the process. Real Lex code rarely exceeds
103/// ~30 frames; 1024 is generous headroom while still well under
104/// the OS stack limit at any per-frame size we use.
105pub const MAX_CALL_DEPTH: u32 = 1024;
106
107/// Per-frame stack-record budget (#464 step 2). Counts the number of
108/// `Value` slots a frame may consume from `Vm::stack_record_arena`
109/// before further `Op::AllocStackRecord` requests fall back to the
110/// heap path. 64 slots at the current `size_of::<Value>() = 64B`
111/// gives ~4 KiB per frame, matching the design-doc proposal in
112/// `docs/design/escape-analysis.md`. A handler-shaped function
113/// (one outer record of ≤8 fields, plus a handful of small inner
114/// records) fits well inside this without growing.
115pub const STACK_RECORD_BUDGET_SLOTS: u32 = 64;
116
117/// Adaptive-memoization warmup window (#229 adaptive). A pure
118/// function is given this many cache-probing calls to demonstrate a
119/// hit; if it reaches the window with zero hits, memoization is
120/// disabled for it (its calls stop hashing args). A function that
121/// genuinely benefits — e.g. naive recursive `fib`, where each call
122/// immediately reuses sub-results — accumulates hits well before the
123/// window closes and stays enabled. 64 balances "give real reuse a
124/// chance" against "don't pay the hash forever on always-miss code".
125const MEMO_WARMUP_CALLS: u32 = 64;
126
127/// Per-function adaptive-memoization state (#229 adaptive). `enabled`
128/// starts true; once a function reaches `MEMO_WARMUP_CALLS` cache
129/// probes with `hits == 0`, it flips to false and that function's
130/// calls skip the args hash entirely for the rest of the Vm's life.
131#[derive(Clone, Copy)]
132struct MemoFnState {
133 calls: u32,
134 hits: u32,
135 enabled: bool,
136}
137
138impl Default for MemoFnState {
139 fn default() -> Self {
140 MemoFnState { calls: 0, hits: 0, enabled: true }
141 }
142}
143
144/// Host-side effect dispatch. Implementors decide what `kind`/`op` mean
145/// and how arguments map to side effects.
146pub trait EffectHandler {
147 fn dispatch(&mut self, kind: &str, op: &str, args: Vec<Value>) -> Result<Value, String>;
148
149 /// Hook called by the VM at every function call so handlers can
150 /// enforce per-call budget consumption (#225). The argument is
151 /// the sum of `[budget(N)]` declared on the callee's signature;
152 /// the handler returns `Err` to refuse the call (the VM converts
153 /// to `VmError::Effect`). Default impl is a no-op so legacy
154 /// handlers and pure-only runs are unaffected.
155 fn note_call_budget(&mut self, _budget_cost: u64) -> Result<(), String> {
156 Ok(())
157 }
158
159 /// Enter a per-request allocation scope (#463 scaffolding).
160 /// Called by the runtime layer (e.g. `net.serve_fn`'s request
161 /// loop) immediately before invoking the user handler closure
162 /// for one request. Implementations push a fresh arena onto
163 /// their internal stack and return its identifier; the matching
164 /// `exit_request_scope` call drops it.
165 ///
166 /// Default impl is a no-op — handlers without arena support
167 /// return a sentinel scope id which they ignore on exit.
168 /// `DefaultHandler` in `lex-runtime` provides the real
169 /// implementation.
170 ///
171 /// Today the VM does NOT route any `Value` allocations through
172 /// the returned arena — see the scaffolding notes in
173 /// `crates/lex-runtime/src/arena.rs`. The hook exists so the
174 /// follow-on slice that adds Value-rep arena routing has a
175 /// stable trait surface to extend.
176 fn enter_request_scope(&mut self) -> u64 { 0 }
177
178 /// Exit a per-request allocation scope opened by
179 /// `enter_request_scope`. Implementations drop the arena
180 /// associated with `scope_id`. Calling exit with a scope_id
181 /// that wasn't returned by a prior enter is implementation-
182 /// defined behavior — DefaultHandler treats it as a no-op so
183 /// mismatched pairs don't panic.
184 fn exit_request_scope(&mut self, _scope_id: u64) {}
185
186 /// `list.par_map` worker-handler factory (#305 slice 2).
187 ///
188 /// Each parallel worker thread runs its own `Vm` and therefore
189 /// needs its own effect handler. The parent handler may opt in
190 /// to per-worker dispatch by returning `Some(handler)` here;
191 /// returning `None` (the default) keeps slice-1 behavior: the
192 /// worker runs `DenyAllEffects` and any effect call inside the
193 /// closure fails with `VmError::Effect`.
194 ///
195 /// The returned handler must be `Send` so the worker can take
196 /// ownership across a thread boundary. Shared state (budget
197 /// pool, chat registry, etc.) is wired up by the implementer.
198 /// Per-worker independence (MCP client cache, output sink)
199 /// is intentional — the alternative is mutex-serialization of
200 /// the whole effect dispatch, which would defeat the parallelism.
201 fn spawn_for_worker(&self) -> Option<Box<dyn EffectHandler + Send>> {
202 None
203 }
204}
205
206/// `Vm` exposes itself as a `ClosureCaller` so the parser interpreter
207/// can invoke user-supplied closures during a `parser.run` walk
208/// (#221). The Vm is reentrant for closure invocation: pushing a new
209/// frame onto an active call stack is supported, and the handler
210/// stays in place so any effects the closure body fires dispatch
211/// normally.
212impl<'a> crate::parser_runtime::ClosureCaller for Vm<'a> {
213 fn call_closure(&mut self, closure: Value, args: Vec<Value>) -> Result<Value, String> {
214 self.invoke_closure_value(closure, args)
215 .map_err(|e| format!("{e:?}"))
216 }
217}
218
219/// A handler that fails any effect call. Useful as a default for pure-only runs.
220pub struct DenyAllEffects;
221impl EffectHandler for DenyAllEffects {
222 fn dispatch(&mut self, kind: &str, op: &str, _args: Vec<Value>) -> Result<Value, String> {
223 Err(format!("effects not permitted (attempted {kind}.{op})"))
224 }
225}
226
227/// Trace receiver. Implementors record the call/effect tree and may
228/// substitute effect responses (for replay).
229pub trait Tracer {
230 fn enter_call(&mut self, node_id: &str, name: &str, args: &[Value]);
231 fn enter_effect(&mut self, node_id: &str, kind: &str, op: &str, args: &[Value]);
232 fn exit_ok(&mut self, value: &Value);
233 fn exit_err(&mut self, message: &str);
234 /// Tail-call optimization: pop the current frame's open call without
235 /// re-entering the parent (the new call takes its place).
236 fn exit_call_tail(&mut self);
237 /// During replay, return Some(v) to substitute an effect's output.
238 fn override_effect(&mut self, _node_id: &str) -> Option<Value> { None }
239}
240
241/// No-op tracer for normal execution.
242pub struct NullTracer;
243impl Tracer for NullTracer {
244 fn enter_call(&mut self, _: &str, _: &str, _: &[Value]) {}
245 fn enter_effect(&mut self, _: &str, _: &str, _: &str, _: &[Value]) {}
246 fn exit_ok(&mut self, _: &Value) {}
247 fn exit_err(&mut self, _: &str) {}
248 fn exit_call_tail(&mut self) {}
249}
250
251#[derive(Debug, Clone)]
252pub(crate) enum FrameKind {
253 /// Top-level entry frame; doesn't correspond to a Call opcode.
254 Entry,
255 /// Frame opened by Call/TailCall. The `String` is the originating
256 /// `NodeId`; useful for diagnostics even if currently unread.
257 Call(#[allow(dead_code)] String),
258}
259
260pub struct Vm<'a> {
261 program: &'a Program,
262 handler: Box<dyn EffectHandler + 'a>,
263 pub(crate) tracer: Box<dyn Tracer + 'a>,
264 /// Per-call frames. Each frame has its own locals array and pc.
265 frames: Vec<Frame>,
266 stack: Vec<Value>,
267 /// Soft cap to avoid runaway computations in tests.
268 pub step_limit: u64,
269 pub steps: u64,
270 /// Per-Vm memoization cache for pure functions (#229). Keyed by
271 /// `(fn_id, hash_call_args(args))` — a 128-bit structural digest
272 /// of the arguments (see `hash_call_args`). Effectful functions
273 /// never enter this map. The cache lives for the lifetime of one
274 /// `Vm::call` chain — calling `Vm::with_handler` again starts a
275 /// fresh cache.
276 pure_memo: std::collections::HashMap<(u32, [u8; 16]), Value>,
277 /// Diagnostic counters for `--trace` observability (#229).
278 pub pure_memo_hits: u64,
279 pub pure_memo_misses: u64,
280 /// Number of effect-free calls that skipped the cache entirely
281 /// because adaptive memoization disabled their function (#229
282 /// adaptive). Observability only.
283 pub pure_memo_skips: u64,
284 /// Adaptive-memoization state, one entry per function (indexed by
285 /// `fn_id`), parallel to `field_ics` (#229 adaptive). Memoization
286 /// only pays when a function is called repeatedly with equal args;
287 /// the unconditional `hash_call_args` on every effect-free call is
288 /// pure overhead otherwise (the `response_build` profile: 0 hits /
289 /// 3600 misses, ~12% of instructions). After a warmup window with
290 /// zero hits we stop hashing that function's calls — always safe,
291 /// since the callee is pure and recomputing yields the same value.
292 /// Sticky for the Vm's lifetime: a function that hasn't hit in
293 /// `MEMO_WARMUP_CALLS` calls won't amortize later.
294 memo_fn_state: Vec<MemoFnState>,
295 /// Monomorphic inline caches for `Op::GetField` (#462 slice 1 +
296 /// shape-keyed verification slice). Indexed by
297 /// `[fn_id as usize][site_idx as usize]` — one entry per
298 /// field-access site within each function. `site_idx` is assigned
299 /// at compile time by `FnCompiler::field_get_sites` so every emit
300 /// produces a stable identifier independent of pc. The cache
301 /// survives the planned dispatch rewrite (#461) and a future
302 /// JIT (#465).
303 ///
304 /// Slot shape: `(shape_id, offset)`. The pre-shape-keyed slice
305 /// stored only the offset and re-verified each hit by walking
306 /// `IndexMap::get_index(off)` and string-comparing the field name
307 /// against the requested `name_idx`. After this slice, hits
308 /// against compile-time records (real `shape_id`) verify with a
309 /// single `u32` compare and skip the string compare entirely —
310 /// per the #462 slice-2b measurement that observed 0% polymorphism
311 /// and 86% of hits going to records with a real shape_id.
312 ///
313 /// `NO_SHAPE_ID` records (JSON / SQL / HTTP-built — 14% of measured
314 /// hits, 100% of inbox/gateway traffic) fall through to the
315 /// pre-slice name-compare verification. Distinct dynamic shapes
316 /// both carry `NO_SHAPE_ID` and would otherwise alias on a
317 /// pure-shape-keyed IC; keeping the name compare on that path
318 /// preserves correctness without a separate cache for them.
319 ///
320 /// Outer Vec is pre-sized to `program.functions.len()`; each inner
321 /// Vec is empty until the first GetField in that function runs,
322 /// at which point we one-shot allocate it to the compiler-recorded
323 /// `field_ic_sites` size and never resize again. Lazy on the inner
324 /// side so VMs created for short-lived scripts don't eagerly
325 /// allocate IC slots for functions they never enter.
326 field_ics: Vec<Vec<Option<(u32, usize)>>>,
327 /// Stack allocator for function locals (#389 slice 3).
328 ///
329 /// Every function frame claims `locals_count` contiguous slots from
330 /// this Vec on push and releases them on pop. Because Lex uses
331 /// strictly LIFO frame semantics the most-recently-pushed frame's
332 /// slots always sit at the top of the Vec, so `truncate` is the
333 /// correct (and O(1)) release operation.
334 ///
335 /// The Vec is pre-allocated once at VM construction and then grows
336 /// only if the actual call depth × locals width exceeds the initial
337 /// capacity. After a top-level `vm.call` returns the Vec is empty
338 /// again but its capacity is retained, so the next request incurs
339 /// zero allocations for locals up to the high-water mark.
340 locals_storage: Vec<Value>,
341 /// Stack-record arena (#464 step 2). Each `Op::AllocStackRecord`
342 /// at a non-escaping site appends its `field_count` field values
343 /// here; the produced `Value::StackRecord` carries `slab_start =
344 /// arena.len() - field_count` so reads are an O(1) slab index.
345 /// On `Op::Return` the arena is truncated back to
346 /// `frame.stack_record_arena_start`, releasing every record the
347 /// frame allocated in O(1) — same lifetime story as
348 /// `locals_storage` for frame locals.
349 ///
350 /// LIFO frame discipline guarantees a frame's records always sit
351 /// at the top of the arena while the frame is live, so neither
352 /// inter-frame interleaving nor index churn can occur.
353 stack_record_arena: Vec<Value>,
354 /// Per-Vm counters for #464 acceptance measurement. Incremented
355 /// on every `Op::MakeRecord` / `Op::AllocStackRecord` dispatch.
356 /// The bench reads these to compute the stack-allocation rate
357 /// (≥ 60% of records on the stack is the acceptance bar). Cheap
358 /// in the hot path — two unconditional u64 increments per record.
359 pub stack_record_allocs: u64,
360 pub stack_record_heap_fallbacks: u64,
361 pub heap_record_allocs: u64,
362 /// Request-scoped arena slab (#463 slice 2a). Mirrors the shape of
363 /// `stack_record_arena` but lives across frames inside the
364 /// request scope opened by `EffectHandler::enter_request_scope`.
365 /// Each `Op::AllocArenaRecord` / `Op::AllocArenaTuple` appends its
366 /// field values here and pushes a handle (`Value::ArenaRecord` /
367 /// `Value::ArenaTuple`) whose `slab_start` indexes back in.
368 /// Truncated to the saved start on `exit_request_scope`, releasing
369 /// every value the scope built in O(1) — same lifetime story as
370 /// `stack_record_arena` truncating on `Op::Return`.
371 ///
372 /// Slabs nest LIFO: `arena_scope_starts` holds the
373 /// `arena_slab.len()` snapshot taken at each `enter_request_scope`,
374 /// and `exit_request_scope` truncates back to the matching entry.
375 /// An empty `arena_scope_starts` means **no active scope** — the
376 /// alloc ops fall back to their `MakeRecord` / `MakeTuple` heap
377 /// path, so the VM stays sound when arena-lowered bytecode runs in
378 /// a non-handler context.
379 arena_slab: Vec<Value>,
380 /// LIFO stack of `arena_slab.len()` snapshots, one per active
381 /// request scope. See `arena_slab`.
382 arena_scope_starts: Vec<u32>,
383 /// Counters for #463 slice-2b acceptance (will be the
384 /// arena-allocation-rate gate, paralleling the #464 stack-rate
385 /// counters above). Incremented in the op handlers; harmless in
386 /// slice 2a since codegen doesn't emit the ops yet.
387 pub arena_record_allocs: u64,
388 pub arena_record_heap_fallbacks: u64,
389 /// Optional JIT tier hook (#465 phase-1 integration). Consulted
390 /// by the `Op::Call` dispatch arm after refinements + memo. See
391 /// `crate::jit_hook` for the trait contract. `None` means
392 /// "interpreter-only" — that branch in the dispatch arm folds
393 /// to a single null-pointer check the optimizer can hoist.
394 jit_hook: Option<Box<dyn crate::jit_hook::JitHook + 'a>>,
395}
396
397struct Frame {
398 fn_id: u32,
399 pc: usize,
400 /// Start index of this frame's locals in `Vm::locals_storage` (#389
401 /// slice 3). The frame owns `locals_storage[locals_start..locals_start
402 /// + locals_len]`; `Op::Return` truncates the Vec back to
403 /// `locals_start`, releasing the slots in O(1).
404 locals_start: usize,
405 locals_len: usize,
406 /// Stack base when this frame started (for cleanup on return).
407 stack_base: usize,
408 trace_kind: FrameKind,
409 /// Pure-fn memo key (#229). `Some(key)` if the call was eligible
410 /// for memoization and missed the cache; on Op::Return the key
411 /// is used to write the return value back into the cache.
412 /// `None` means "don't memoize" — either the function isn't pure,
413 /// the call wasn't through Op::Call, or memoization is disabled.
414 memo_key: Option<(u32, [u8; 16])>,
415 /// #464 step 2: start index of this frame's records in
416 /// `Vm::stack_record_arena`. On `Op::Return`, the arena is
417 /// truncated back here. Identical lifetime discipline to
418 /// `locals_start`.
419 stack_record_arena_start: usize,
420 /// Remaining stack-record budget for this frame, in Value-slot
421 /// units (#464 step 2). Initial value: `STACK_RECORD_BUDGET_SLOTS`.
422 /// When an `Op::AllocStackRecord` would consume more slots than
423 /// remain, the VM falls back to the heap path silently (same
424 /// observable effect as `Op::MakeRecord`), so the budget never
425 /// surfaces as a user-visible error.
426 stack_record_budget_remaining: u32,
427}
428
429/// Sum of `[budget(N)]` declarations on a function's signature
430/// (#225). Used by Op::Call / Op::TailCall / Op::CallClosure to
431/// notify the EffectHandler of per-call budget cost so the handler
432/// can deduct from a shared pool and refuse calls that would
433/// exceed the policy ceiling. Negative `Int` args are ignored —
434/// the static check (`policy::check_program`) treats budgets as
435/// non-negative.
436fn call_budget_cost(f: &crate::program::Function) -> u64 {
437 let mut total: u64 = 0;
438 for e in &f.effects {
439 if e.kind == "budget" {
440 if let Some(crate::program::EffectArg::Int(n)) = &e.arg {
441 if *n >= 0 {
442 total = total.saturating_add(*n as u64);
443 }
444 }
445 }
446 }
447 total
448}
449
450/// Hash the argument list for a pure-fn memoization lookup (#229).
451///
452/// The memo cache (`pure_memo`) is keyed on this 128-bit digest with
453/// no secondary equality check, so the contract is: argument lists
454/// that are equal under `Value`'s `PartialEq` must produce the same
455/// digest, and the 128-bit width keeps the false-collision rate
456/// (which would return a wrong cached result) negligible.
457///
458/// History (#461 follow-up): this used to build a `serde_json::Value`
459/// of every arg, canonicalize it, and SHA-256 the bytes. Profiling
460/// the `response_build` workload showed that path at 27.6% of all
461/// instructions — it dominated the VM, since every effect-free call
462/// pays it whether or not the cache ever hits. The cache is per-`Vm`
463/// and ephemeral, so a cryptographic, cross-process-stable key was
464/// never needed. We now walk the `Value` tree directly into two
465/// domain-separated `SipHash` passes (deterministic fixed-key
466/// `DefaultHasher`), concatenating the two 64-bit outputs into a
467/// 128-bit key. No JSON allocation, no crypto.
468///
469/// The walk mirrors `Value::PartialEq` so the equal-args-equal-key
470/// contract holds: `Record` is hashed order-independently over its
471/// fields (matching `IndexMap`'s order-insensitive equality),
472/// `Closure` on `(body_hash, captures)` not `fn_id` (#222), and
473/// `Actor`/`Ticker` on pointer identity (matching `Arc::ptr_eq`).
474fn hash_call_args(args: &[Value]) -> [u8; 16] {
475 use std::collections::hash_map::DefaultHasher;
476 use std::hash::Hasher;
477 let mut h0 = DefaultHasher::new();
478 let mut h1 = DefaultHasher::new();
479 // Domain separator: makes the two passes diverge so the
480 // concatenated halves span the full 128-bit space rather than
481 // duplicating one 64-bit value.
482 h1.write_u8(0x9e);
483 h0.write_usize(args.len());
484 h1.write_usize(args.len());
485 for a in args {
486 hash_value_into(a, &mut h0);
487 hash_value_into(a, &mut h1);
488 }
489 let lo = h0.finish();
490 let hi = h1.finish();
491 let mut out = [0u8; 16];
492 out[..8].copy_from_slice(&lo.to_le_bytes());
493 out[8..].copy_from_slice(&hi.to_le_bytes());
494 out
495}
496
497/// Structural hash of a `Value` into `h`, consistent with
498/// `Value::PartialEq`. The leading discriminant byte keeps distinct
499/// variants from colliding (e.g. `Int(0)` vs `Bool(false)`).
500fn hash_value_into<H: std::hash::Hasher>(v: &Value, h: &mut H) {
501 use std::collections::hash_map::DefaultHasher;
502 use std::hash::Hasher as _;
503 match v {
504 Value::Int(n) => { h.write_u8(0x01); h.write_i64(*n); }
505 // Bit pattern, not value: total and deterministic. NaN==NaN
506 // by bits (a memo hit there is harmless — the callee is pure
507 // and returns the same result for bit-identical args), and
508 // +0.0/-0.0 differ (a harmless extra miss).
509 Value::Float(f) => { h.write_u8(0x02); h.write_u64(f.to_bits()); }
510 Value::Bool(b) => { h.write_u8(0x03); h.write_u8(*b as u8); }
511 Value::Str(s) => {
512 h.write_u8(0x04);
513 h.write_usize(s.len());
514 h.write(s.as_bytes());
515 }
516 Value::Bytes(b) => {
517 h.write_u8(0x05);
518 h.write_usize(b.len());
519 h.write(b);
520 }
521 Value::Unit => { h.write_u8(0x06); }
522 Value::List(items) => {
523 h.write_u8(0x07);
524 h.write_usize(items.len());
525 for it in items { hash_value_into(it, h); }
526 }
527 Value::Tuple(items) => {
528 h.write_u8(0x08);
529 h.write_usize(items.len());
530 for it in items { hash_value_into(it, h); }
531 }
532 Value::Deque(items) => {
533 h.write_u8(0x09);
534 h.write_usize(items.len());
535 for it in items { hash_value_into(it, h); }
536 }
537 // `IndexMap` equality is order-insensitive, so the hash must
538 // be too: combine per-entry sub-hashes with wrapping add (a
539 // commutative mix) rather than feeding them in iteration
540 // order.
541 Value::Record { fields, .. } => {
542 h.write_u8(0x0a);
543 let mut combined: u64 = 0;
544 for (k, val) in fields.iter() {
545 let mut e = DefaultHasher::new();
546 e.write(k.as_bytes());
547 e.write_u8(0xff);
548 hash_value_into(val, &mut e);
549 combined = combined.wrapping_add(e.finish());
550 }
551 h.write_u64(combined);
552 h.write_usize(fields.len());
553 }
554 Value::Variant { name, args } => {
555 h.write_u8(0x0b);
556 h.write_usize(name.len());
557 h.write(name.as_bytes());
558 h.write_usize(args.len());
559 for a in args { hash_value_into(a, h); }
560 }
561 // Identity is `(body_hash, captures)`, not `fn_id` (#222).
562 Value::Closure { body_hash, captures, .. } => {
563 h.write_u8(0x0c);
564 h.write(body_hash);
565 h.write_usize(captures.len());
566 for c in captures { hash_value_into(c, h); }
567 }
568 Value::F64Array { rows, cols, data } => {
569 h.write_u8(0x0d);
570 h.write_u32(*rows);
571 h.write_u32(*cols);
572 for f in data { h.write_u64(f.to_bits()); }
573 }
574 // BTreeMap / BTreeSet iterate in sorted key order — already
575 // canonical, so direct feed is order-independent.
576 Value::Map(m) => {
577 h.write_u8(0x0e);
578 h.write_usize(m.len());
579 for (k, val) in m {
580 hash_mapkey_into(k, h);
581 hash_value_into(val, h);
582 }
583 }
584 Value::Set(s) => {
585 h.write_u8(0x0f);
586 h.write_usize(s.len());
587 for k in s { hash_mapkey_into(k, h); }
588 }
589 // Pointer identity, matching `Arc::ptr_eq` in PartialEq.
590 Value::Actor(a) => {
591 h.write_u8(0x10);
592 h.write_usize(Arc::as_ptr(a) as *const () as usize);
593 }
594 Value::Ticker(t) => {
595 h.write_u8(0x11);
596 h.write_usize(Arc::as_ptr(t) as *const () as usize);
597 }
598 // Coarse summary (schema + dimensions), matching the prior
599 // `to_json` encoding which deliberately omitted the cell data
600 // (tables can be GB-scale). Equal tables share schema + dims
601 // so equal-args-equal-key holds; this is no coarser than the
602 // pre-#461-followup behavior.
603 Value::ArrowTable(t) => {
604 h.write_u8(0x12);
605 h.write_i64(t.num_rows() as i64);
606 h.write_i64(t.num_columns() as i64);
607 for f in t.schema().fields() {
608 h.write(f.name().as_bytes());
609 h.write_u8(0xfe);
610 }
611 }
612 // #464: a StackRecord crossing into the memo path means an
613 // escape the analysis was supposed to reject. Mirror the
614 // PartialEq / to_json panic rather than mint a bogus key.
615 Value::StackRecord { .. } =>
616 panic!("BUG(#464): Value::StackRecord reached memo hashing — \
617 escape analysis should have prevented escape to a call boundary"),
618 Value::StackTuple { .. } =>
619 panic!("BUG(#464): Value::StackTuple reached memo hashing — \
620 escape analysis should have prevented escape to a call boundary"),
621 // #463 slice 2a: arena handles must never reach memo hashing.
622 // The memo cache outlives every request scope, so a hashed
623 // arena handle would dangle. Slice 1's arena-eligibility
624 // analysis must exclude pure-fn allocation sites (the memo
625 // path is reached only through pure-fn calls) — any reach
626 // here is a soundness bug.
627 Value::ArenaRecord { .. } =>
628 panic!("BUG(#463): Value::ArenaRecord reached memo hashing — \
629 arena-eligibility analysis must exclude pure-fn allocation sites"),
630 Value::ArenaTuple { .. } =>
631 panic!("BUG(#463): Value::ArenaTuple reached memo hashing — \
632 arena-eligibility analysis must exclude pure-fn allocation sites"),
633 }
634}
635
636/// Hash a `MapKey` into `h` with its own discriminant so a `Str`
637/// key and an `Int` key never collide.
638fn hash_mapkey_into<H: std::hash::Hasher>(k: &crate::value::MapKey, h: &mut H) {
639 use crate::value::MapKey;
640 match k {
641 MapKey::Str(s) => { h.write_u8(0x01); h.write_usize(s.len()); h.write(s.as_bytes()); }
642 MapKey::Int(n) => { h.write_u8(0x02); h.write_i64(*n); }
643 }
644}
645
646/// Evaluate a refinement predicate at runtime against the actual
647/// argument value (#209 slice 3). Mirrors `lex_types::discharge`'s
648/// static evaluator but operates on `Value` directly.
649///
650/// Returns `Ok(true)` / `Ok(false)` for a clean boolean verdict, or
651/// `Err(reason)` if the predicate references something the runtime
652/// can't resolve (free variable beyond the binding, unsupported AST
653/// node). Callers map `Ok(false)` and `Err` to `VmError::RefinementFailed`.
654fn eval_refinement(
655 predicate: &lex_ast::CExpr,
656 binding: &str,
657 arg: &Value,
658) -> Result<bool, String> {
659 match eval_refinement_inner(predicate, binding, arg) {
660 Ok(Value::Bool(b)) => Ok(b),
661 Ok(other) => Err(format!("predicate didn't reduce to a Bool, got {other:?}")),
662 Err(e) => Err(e),
663 }
664}
665
666fn eval_refinement_inner(
667 e: &lex_ast::CExpr,
668 binding: &str,
669 arg: &Value,
670) -> Result<Value, String> {
671 use lex_ast::{CExpr, CLit};
672 match e {
673 CExpr::Literal { value } => Ok(match value {
674 CLit::Int { value } => Value::Int(*value),
675 CLit::Float { value } => Value::Float(value.parse().unwrap_or(0.0)),
676 CLit::Bool { value } => Value::Bool(*value),
677 CLit::Str { value } => Value::Str(value.as_str().into()),
678 CLit::Bytes { value } => Value::Str(value.as_str().into()), // hex; unusual in predicates
679 CLit::Unit => Value::Unit,
680 }),
681 CExpr::Var { name } if name == binding => Ok(arg.clone()),
682 CExpr::Var { name } => Err(format!(
683 "predicate references free var `{name}`; runtime check \
684 only resolves the binding (slice 4 will plumb call-site \
685 context)")),
686 CExpr::UnaryOp { op, expr } => {
687 let v = eval_refinement_inner(expr, binding, arg)?;
688 match (op.as_str(), v) {
689 ("not", Value::Bool(b)) => Ok(Value::Bool(!b)),
690 ("-", Value::Int(n)) => Ok(Value::Int(-n)),
691 ("-", Value::Float(n)) => Ok(Value::Float(-n)),
692 (o, v) => Err(format!("unsupported unary `{o}` on {v:?}")),
693 }
694 }
695 CExpr::BinOp { op, lhs, rhs } => {
696 // Short-circuit `and` / `or` for the same reasons as the
697 // static evaluator.
698 if op == "and" || op == "or" {
699 let l = eval_refinement_inner(lhs, binding, arg)?;
700 let lb = match l {
701 Value::Bool(b) => b,
702 other => return Err(format!("`{op}` on non-bool: {other:?}")),
703 };
704 if op == "and" && !lb { return Ok(Value::Bool(false)); }
705 if op == "or" && lb { return Ok(Value::Bool(true)); }
706 let r = eval_refinement_inner(rhs, binding, arg)?;
707 return match r {
708 Value::Bool(b) => Ok(Value::Bool(b)),
709 other => Err(format!("`{op}` on non-bool: {other:?}")),
710 };
711 }
712 let l = eval_refinement_inner(lhs, binding, arg)?;
713 let r = eval_refinement_inner(rhs, binding, arg)?;
714 apply_refinement_binop(op, &l, &r)
715 }
716 // Other AST forms (Call, Let, Match, FieldAccess, Lambda,
717 // Block, Constructors, Records, Tuples, Lists, Return) need
718 // a more general evaluator that can call back into the VM.
719 // Out of scope for slice 3; a future slice may unify this
720 // with the spec-checker's gate evaluator.
721 other => Err(format!("unsupported predicate node: {other:?}")),
722 }
723}
724
725fn apply_refinement_binop(op: &str, l: &Value, r: &Value) -> Result<Value, String> {
726 use Value::*;
727 match (op, l, r) {
728 ("+", Int(a), Int(b)) => Ok(Int(a + b)),
729 ("-", Int(a), Int(b)) => Ok(Int(a - b)),
730 ("*", Int(a), Int(b)) => Ok(Int(a * b)),
731 ("/", Int(a), Int(b)) if *b != 0 => Ok(Int(a / b)),
732 ("%", Int(a), Int(b)) if *b != 0 => Ok(Int(a % b)),
733 ("+", Float(a), Float(b)) => Ok(Float(a + b)),
734 ("-", Float(a), Float(b)) => Ok(Float(a - b)),
735 ("*", Float(a), Float(b)) => Ok(Float(a * b)),
736 ("/", Float(a), Float(b)) => Ok(Float(a / b)),
737
738 ("==", a, b) => Ok(Bool(a == b)),
739 ("!=", a, b) => Ok(Bool(a != b)),
740
741 ("<", Int(a), Int(b)) => Ok(Bool(a < b)),
742 ("<=", Int(a), Int(b)) => Ok(Bool(a <= b)),
743 (">", Int(a), Int(b)) => Ok(Bool(a > b)),
744 (">=", Int(a), Int(b)) => Ok(Bool(a >= b)),
745
746 ("<", Float(a), Float(b)) => Ok(Bool(a < b)),
747 ("<=", Float(a), Float(b)) => Ok(Bool(a <= b)),
748 (">", Float(a), Float(b)) => Ok(Bool(a > b)),
749 (">=", Float(a), Float(b)) => Ok(Bool(a >= b)),
750
751 (op, a, b) => Err(format!(
752 "unsupported binop `{op}` on {a:?} and {b:?}")),
753 }
754}
755
756fn const_str(constants: &[Const], idx: u32) -> String {
757 match constants.get(idx as usize) {
758 Some(Const::NodeId(s)) | Some(Const::Str(s)) => s.clone(),
759 _ => String::new(),
760 }
761}
762
763/// Read `LEX_PAR_MAX_CONCURRENCY` (default = available CPU cores,
764/// fallback 4). Capped at 64 so a malformed env var can't spawn an
765/// unreasonable number of OS threads.
766/// Order-defining comparator for `list.sort_by` keys (#338).
767/// Same-typed Int / Float / Str pairs compare via their native
768/// `Ord` / `PartialOrd`. Mixed-type or other key shapes compare
769/// as Equal; combined with `Vec::sort_by`'s stability that
770/// preserves the original element order — best-effort fallback
771/// that never panics.
772fn compare_sort_keys(a: &Value, b: &Value) -> std::cmp::Ordering {
773 use std::cmp::Ordering;
774 match (a, b) {
775 (Value::Int(x), Value::Int(y)) => x.cmp(y),
776 (Value::Float(x), Value::Float(y)) => x.partial_cmp(y).unwrap_or(Ordering::Equal),
777 (Value::Str(x), Value::Str(y)) => x.cmp(y),
778 _ => Ordering::Equal,
779 }
780}
781
782fn par_max_concurrency() -> usize {
783 let from_env = std::env::var("LEX_PAR_MAX_CONCURRENCY")
784 .ok()
785 .and_then(|s| s.parse::<usize>().ok())
786 .filter(|n| *n > 0);
787 let default = std::thread::available_parallelism()
788 .map(|n| n.get())
789 .unwrap_or(4);
790 from_env.unwrap_or(default).min(64)
791}
792
793/// `list.par_map`'s runtime: spawn OS threads (capped by
794/// `LEX_PAR_MAX_CONCURRENCY`), apply `closure` to each item, return
795/// results in input order. Each worker runs a fresh `Vm` with
796/// [`DenyAllEffects`] for #305 slice 1 — effectful closures fail
797/// with `VmError::Effect`. Slice 2 will plumb a per-thread effect
798/// handler split.
799fn par_map_run<'a>(
800 program: &'a Program,
801 closure: Value,
802 items: Vec<Value>,
803 worker_handlers: Vec<Box<dyn EffectHandler + Send>>,
804) -> Result<Vec<Value>, VmError> {
805 if items.is_empty() {
806 return Ok(Vec::new());
807 }
808 let n_workers = worker_handlers.len().min(items.len()).max(1);
809 // Carve items into `n_workers` round-robin buckets so each
810 // worker processes (indices, items) pairs and we can reassemble
811 // in input order.
812 let mut buckets: Vec<Vec<(usize, Value)>> = (0..n_workers).map(|_| Vec::new()).collect();
813 for (i, v) in items.into_iter().enumerate() {
814 buckets[i % n_workers].push((i, v));
815 }
816 let n_total: usize = buckets.iter().map(|b| b.len()).sum();
817 let results: std::sync::Mutex<Vec<Option<Result<Value, String>>>> =
818 std::sync::Mutex::new((0..n_total).map(|_| None).collect());
819
820 // Pair each bucket with its pre-built handler so workers own
821 // their handler outright — no shared mutable state across
822 // worker threads.
823 let mut worker_handlers = worker_handlers;
824 worker_handlers.truncate(n_workers);
825 type Pair = (Vec<(usize, Value)>, Box<dyn EffectHandler + Send>);
826 let pairs: Vec<Pair> = buckets.into_iter().zip(worker_handlers).collect();
827
828 std::thread::scope(|s| {
829 let mut handles = Vec::with_capacity(pairs.len());
830 for (bucket, handler) in pairs {
831 let closure = closure.clone();
832 let results = &results;
833 handles.push(s.spawn(move || {
834 // `Box<dyn EffectHandler + Send>` has implicit
835 // `+ 'static`; that coerces to `+ 'a` because
836 // `'static` outlives any `'a`. The `Send` bound is
837 // auto-erased on the unsize coercion.
838 let handler_for_vm: Box<dyn EffectHandler + 'a> = handler;
839 let mut vm = Vm::with_handler(program, handler_for_vm);
840 for (idx, item) in bucket {
841 let r = vm
842 .invoke_closure_value(closure.clone(), vec![item])
843 .map_err(|e| format!("{e:?}"));
844 results.lock().unwrap()[idx] = Some(r);
845 }
846 }));
847 }
848 for h in handles {
849 h.join().map_err(|_| ()).ok();
850 }
851 });
852
853 let mut out = Vec::with_capacity(n_total);
854 let inner = results.into_inner().unwrap();
855 for r in inner {
856 match r {
857 Some(Ok(v)) => out.push(v),
858 Some(Err(e)) => return Err(VmError::Effect(format!("par_map worker: {e}"))),
859 None => return Err(VmError::Panic("par_map worker did not produce a result".into())),
860 }
861 }
862 Ok(out)
863}
864
865impl<'a> Vm<'a> {
866 pub fn new(program: &'a Program) -> Self {
867 Self::with_handler(program, Box::new(DenyAllEffects))
868 }
869
870 pub fn with_handler(program: &'a Program, handler: Box<dyn EffectHandler + 'a>) -> Self {
871 Self {
872 program,
873 handler,
874 tracer: Box::new(NullTracer),
875 // Pre-allocate enough capacity for a typical request so the first
876 // call incurs no reallocation (#389 slice 3).
877 frames: Vec::with_capacity(32),
878 stack: Vec::with_capacity(128),
879 step_limit: 10_000_000,
880 steps: 0,
881 pure_memo: std::collections::HashMap::new(),
882 pure_memo_hits: 0,
883 pure_memo_misses: 0,
884 pure_memo_skips: 0,
885 memo_fn_state: vec![MemoFnState::default(); program.functions.len()],
886 field_ics: vec![Vec::new(); program.functions.len()],
887 // 256 slots handles ~32 frames × 8 locals; grows on demand and
888 // retains capacity across consecutive vm.call() invocations.
889 locals_storage: Vec::with_capacity(256),
890 // #464 step 2: zero capacity at construction — handlers that
891 // never AllocStackRecord (most code today, until the lowering
892 // pass kicks in) pay nothing. First allocation triggers Vec
893 // growth; capacity is retained across `vm.call` invocations.
894 stack_record_arena: Vec::new(),
895 stack_record_allocs: 0,
896 stack_record_heap_fallbacks: 0,
897 heap_record_allocs: 0,
898 // #463 slice 2a: empty until the first enter_request_scope.
899 // Programs that never enter a scope incur zero arena cost
900 // (the alloc ops, if reached, fall back to the heap path).
901 arena_slab: Vec::new(),
902 arena_scope_starts: Vec::new(),
903 arena_record_allocs: 0,
904 arena_record_heap_fallbacks: 0,
905 jit_hook: None,
906 }
907 }
908
909 pub fn set_tracer(&mut self, tracer: Box<dyn Tracer + 'a>) {
910 self.tracer = tracer;
911 }
912
913 /// Install (or replace) the JIT hook consulted by `Op::Call`'s
914 /// dispatch arm. With `None`, dispatch behaves exactly as before
915 /// — the hook check is a single null-option branch the optimizer
916 /// can hoist. See the [`crate::jit_hook`] module for the
917 /// contract callers must uphold.
918 pub fn set_jit_hook(&mut self, hook: Option<Box<dyn crate::jit_hook::JitHook + 'a>>) {
919 self.jit_hook = hook;
920 }
921
922 /// Cap the number of opcode dispatches before the VM aborts with
923 /// `step limit exceeded`. Useful as a runtime DoS guard against
924 /// untrusted code (e.g. the `agent-tool` sandbox, where an LLM
925 /// could emit `list.fold(list.range(0, 1_000_000_000), …)` to hang
926 /// the host). Default is 10_000_000.
927 pub fn set_step_limit(&mut self, limit: u64) {
928 self.step_limit = limit;
929 }
930
931 pub fn call(&mut self, name: &str, args: Vec<Value>) -> Result<Value, VmError> {
932 let fn_id = self.program.lookup(name).ok_or_else(|| VmError::Panic(format!("no function `{name}`")))?;
933 self.invoke(fn_id, args)
934 }
935
936 /// Vm-level handler for `parser.run` (#221). Routed here from
937 /// `Op::EffectCall` rather than through the `EffectHandler` so
938 /// the recursive parser interpreter has reentrant Vm access for
939 /// closure invocation. Returns the wrapped `Result[T, ParseErr]`
940 /// value the language sees.
941 fn run_parser_op(&mut self, args: Vec<Value>) -> Result<Value, String> {
942 let parser = args.first().cloned()
943 .ok_or_else(|| "parser.run: missing parser arg".to_string())?;
944 let input = match args.get(1) {
945 Some(Value::Str(s)) => s.clone(),
946 _ => return Err("parser.run: input must be Str".into()),
947 };
948 match crate::parser_runtime::run_parser(&parser, &input, 0, self) {
949 Ok((value, _pos)) => Ok(Value::Variant {
950 name: "Ok".into(),
951 args: vec![value],
952 }),
953 Err((pos, msg)) => {
954 let mut e: IndexMap<String, Value> = IndexMap::new();
955 e.insert("pos".into(), Value::Int(pos as i64));
956 e.insert("message".into(), Value::Str(msg.into()));
957 Ok(Value::Variant {
958 name: "Err".into(),
959 args: vec![Value::record_dynamic(e)],
960 })
961 }
962 }
963 }
964
965 // ---- Variant helpers used by conc.* registry ops (#444) ----
966 // Local helpers (avoid pulling in serde / public API). Lex's
967 // `Result`/`Option` are stdlib unions; their runtime shape is a
968 // `Value::Variant { name, args }` with the constructor name as
969 // declared (`Ok`/`Err`/`Some`/`None`).
970
971 /// VM-level handler for `conc.*` effect ops (#381).
972 ///
973 /// * `conc.spawn(init, handler)` — creates an `Actor` wrapping the
974 /// initial state and the handler closure. No background thread is
975 /// started; the actor runs synchronously on the calling thread
976 /// under a `Mutex` so concurrent callers serialise.
977 ///
978 /// * `conc.ask(actor, msg)` — locks the actor, calls
979 /// `handler(state, msg)` on *this* VM (reentrant), expects a
980 /// 2-tuple `(new_state, reply)`, updates the actor's state, and
981 /// returns `reply`.
982 ///
983 /// * `conc.tell(actor, msg)` — same as `ask` but discards the
984 /// reply and returns `Unit`.
985 fn run_conc_op(&mut self, op: &str, args: Vec<Value>) -> Result<Value, String> {
986 match op {
987 "spawn" => {
988 let mut it = args.into_iter();
989 let init = it.next().unwrap_or(Value::Unit);
990 let handler = it.next().unwrap_or(Value::Unit);
991 if !matches!(handler, Value::Closure { .. }) {
992 return Err(format!(
993 "conc.spawn: handler must be a Closure, got {handler:?}"));
994 }
995 Ok(Value::Actor(Arc::new(Mutex::new(ActorCell {
996 state: init,
997 handler: crate::value::ActorHandler::Lex(handler),
998 }))))
999 }
1000 "ask" | "tell" => {
1001 let mut it = args.into_iter();
1002 let actor_val = it.next().unwrap_or(Value::Unit);
1003 let msg = it.next().unwrap_or(Value::Unit);
1004 let cell = match actor_val {
1005 Value::Actor(ref arc) => Arc::clone(arc),
1006 other => return Err(format!(
1007 "conc.{op}: first arg must be an Actor, got {other:?}")),
1008 };
1009 // Lock the actor: guarantees at-most-one-concurrent message.
1010 let mut guard = cell.lock().map_err(|e| format!("conc.{op}: actor mutex poisoned: {e}"))?;
1011 let handler = guard.handler.clone();
1012 let state = guard.state.clone();
1013 match handler {
1014 crate::value::ActorHandler::Lex(closure_val) => {
1015 // Call handler(state, msg) on this VM — full effect access.
1016 let result = self.invoke_closure_value(closure_val, vec![state, msg])
1017 .map_err(|e| format!("conc.{op}: handler error: {e:?}"))?;
1018 // Expect (new_state, reply) tuple.
1019 match result {
1020 Value::Tuple(mut parts) if parts.len() == 2 => {
1021 let reply = parts.pop().unwrap();
1022 let new_state = parts.pop().unwrap();
1023 guard.state = new_state;
1024 drop(guard);
1025 if op == "ask" { Ok(reply) } else { Ok(Value::Unit) }
1026 }
1027 other => Err(format!(
1028 "conc.{op}: handler must return a 2-tuple (new_state, reply), got {other:?}")),
1029 }
1030 }
1031 crate::value::ActorHandler::Native(native) => {
1032 // Native bridge: fire-and-forget; `state` is unused
1033 // (the bridge's "state" is the external resource, e.g.
1034 // a WebSocket connection). The closure receives `msg`
1035 // directly. `ask` returns whatever the bridge produces;
1036 // `tell` discards it. State stays untouched.
1037 drop(guard);
1038 let result = (native.send)(msg)
1039 .map_err(|e| format!("conc.{op}: native handler error: {e}"))?;
1040 if op == "ask" { Ok(result) } else { Ok(Value::Unit) }
1041 }
1042 }
1043 }
1044 "register" => {
1045 // conc.register(actor, name) -> Result[Unit, ConcError]
1046 // Returns Ok(Unit) on first register, Err(AlreadyRegistered(name))
1047 // if the name is taken. v1 stores the actor opaquely —
1048 // see crate::conc_registry for the type-tag note.
1049 let mut it = args.into_iter();
1050 let actor = it.next().unwrap_or(Value::Unit);
1051 if !matches!(actor, Value::Actor(_)) {
1052 return Err(format!(
1053 "conc.register: first arg must be an Actor, got {actor:?}"));
1054 }
1055 let name = match it.next() {
1056 Some(Value::Str(s)) => s.to_string(),
1057 other => return Err(format!(
1058 "conc.register: name must be Str, got {other:?}")),
1059 };
1060 Ok(match crate::conc_registry::register(&name, actor) {
1061 Ok(()) => variant_ok(Value::Unit),
1062 Err(crate::conc_registry::RegError::AlreadyRegistered(n)) => {
1063 variant_err(variant("AlreadyRegistered", vec![Value::Str(n.into())]))
1064 }
1065 Err(crate::conc_registry::RegError::NotRegistered(_)) => {
1066 unreachable!("register cannot produce NotRegistered")
1067 }
1068 })
1069 }
1070 "lookup" => {
1071 // conc.lookup(name) -> Option[Actor[S, M]]
1072 // Returns Some(actor) if registered, None otherwise. The
1073 // [S, M] static parametrisation at the call site is not
1074 // checked at runtime in v1 — caller's responsibility to
1075 // match the registration site's type.
1076 let mut it = args.into_iter();
1077 let name = match it.next() {
1078 Some(Value::Str(s)) => s.to_string(),
1079 other => return Err(format!(
1080 "conc.lookup: name must be Str, got {other:?}")),
1081 };
1082 Ok(match crate::conc_registry::lookup(&name) {
1083 Some(actor) => variant("Some", vec![actor]),
1084 None => variant("None", vec![]),
1085 })
1086 }
1087 "unregister" => {
1088 // conc.unregister(name) -> Result[Unit, ConcError]
1089 let mut it = args.into_iter();
1090 let name = match it.next() {
1091 Some(Value::Str(s)) => s.to_string(),
1092 other => return Err(format!(
1093 "conc.unregister: name must be Str, got {other:?}")),
1094 };
1095 Ok(match crate::conc_registry::unregister(&name) {
1096 Ok(()) => variant_ok(Value::Unit),
1097 Err(crate::conc_registry::RegError::NotRegistered(n)) => {
1098 variant_err(variant("NotRegistered", vec![Value::Str(n.into())]))
1099 }
1100 Err(crate::conc_registry::RegError::AlreadyRegistered(_)) => {
1101 unreachable!("unregister cannot produce AlreadyRegistered")
1102 }
1103 })
1104 }
1105 "registered" => {
1106 // conc.registered() -> List[Str] — sorted snapshot.
1107 let names = crate::conc_registry::registered();
1108 Ok(Value::List(names.into_iter()
1109 .map(|n| Value::Str(n.into()))
1110 .collect()))
1111 }
1112 other => Err(format!("unknown conc.{other}")),
1113 }
1114 }
1115
1116 /// Invoke a `Value::Closure` by combining its captures with the
1117 /// supplied call args and dispatching to the underlying function.
1118 /// Used by the parser interpreter (#221) to call user-supplied
1119 /// `f` arguments inside `parser.map` / `parser.and_then` nodes.
1120 pub fn invoke_closure_value(
1121 &mut self,
1122 closure: Value,
1123 args: Vec<Value>,
1124 ) -> Result<Value, VmError> {
1125 let (fn_id, captures) = match closure {
1126 Value::Closure { fn_id, captures, .. } => (fn_id, captures),
1127 other => return Err(VmError::TypeMismatch(
1128 format!("invoke_closure_value: not a closure: {other:?}"))),
1129 };
1130 let mut combined = captures;
1131 combined.extend(args);
1132 self.invoke(fn_id, combined)
1133 }
1134
1135 /// Invoke a 1-arg closure without allocating a separate args
1136 /// `Vec` (#464 call-overhead). The closure's own `captures` Vec
1137 /// is reused as the combined `captures ++ [arg]` argument buffer,
1138 /// so the per-element call in `ListMap`/`ListFilter`/`SortByKey`
1139 /// allocates at most once (the `push`) instead of twice (a fresh
1140 /// `vec![arg]` plus the `extend`). Semantically identical to
1141 /// `invoke_closure_value(closure, vec![arg])`.
1142 pub fn invoke_closure_1(&mut self, closure: Value, arg: Value) -> Result<Value, VmError> {
1143 let (fn_id, mut combined) = match closure {
1144 Value::Closure { fn_id, captures, .. } => (fn_id, captures),
1145 other => return Err(VmError::TypeMismatch(
1146 format!("invoke_closure_1: not a closure: {other:?}"))),
1147 };
1148 combined.push(arg);
1149 self.invoke(fn_id, combined)
1150 }
1151
1152 /// Invoke a 2-arg closure without a separate args `Vec` — the
1153 /// `ListFold` combiner path. See `invoke_closure_1`.
1154 pub fn invoke_closure_2(&mut self, closure: Value, a: Value, b: Value) -> Result<Value, VmError> {
1155 let (fn_id, mut combined) = match closure {
1156 Value::Closure { fn_id, captures, .. } => (fn_id, captures),
1157 other => return Err(VmError::TypeMismatch(
1158 format!("invoke_closure_2: not a closure: {other:?}"))),
1159 };
1160 combined.push(a);
1161 combined.push(b);
1162 self.invoke(fn_id, combined)
1163 }
1164
1165 /// Open a request-scoped arena via the underlying
1166 /// `EffectHandler::enter_request_scope` (#463 scaffolding).
1167 /// Runtime layers — `net.serve_fn`, `net.serve_ws`,
1168 /// `net.serve_quic` — call this immediately before invoking the
1169 /// user handler closure for a single request. Pair with
1170 /// `exit_request_scope` once the response has been built and
1171 /// any lazy iterators in it have been drained (#477).
1172 ///
1173 /// Returns the scope id the runtime should pass back to
1174 /// `exit_request_scope`. The handler's default impl returns 0
1175 /// and the matching `exit` is a no-op; `DefaultHandler`'s
1176 /// implementation actually allocates an arena.
1177 pub fn enter_request_scope(&mut self) -> u64 {
1178 // #463 slice 2a: snapshot the slab high-water mark so
1179 // `exit_request_scope` can truncate back to here, releasing
1180 // every arena-allocated value the scope built in O(1).
1181 self.arena_scope_starts.push(self.arena_slab.len() as u32);
1182 self.handler.enter_request_scope()
1183 }
1184
1185 /// True iff there is at least one active request scope — i.e. an
1186 /// `enter_request_scope` not yet matched by `exit_request_scope`.
1187 /// Runtime layers use this to skip `materialize_arena_handles` on
1188 /// paths where no scope was entered (e.g. tiny-http worker
1189 /// dispatch), keeping the no-arena path zero-cost. Slice 2b-i.
1190 pub fn arena_scope_active(&self) -> bool {
1191 !self.arena_scope_starts.is_empty()
1192 }
1193
1194 /// Close the request scope opened by `enter_request_scope`.
1195 /// Drops the associated arena.
1196 pub fn exit_request_scope(&mut self, scope_id: u64) {
1197 // #463 slice 2a: truncate the slab back to the matching
1198 // `enter` snapshot, then notify the handler. Out-of-order /
1199 // unpaired exits (e.g. a stray `exit` with no prior `enter`)
1200 // are tolerated as no-ops — the handler does the same, and a
1201 // stray exit shouldn't crash a live server.
1202 if let Some(start) = self.arena_scope_starts.pop() {
1203 self.arena_slab.truncate(start as usize);
1204 }
1205 self.handler.exit_request_scope(scope_id)
1206 }
1207
1208 /// Deep-walk `value` and resolve every `Value::ArenaRecord` /
1209 /// `Value::ArenaTuple` handle into its heap-owned equivalent
1210 /// (`Value::Record` / `Value::Tuple`), reading field contents
1211 /// out of `Vm::arena_slab` along the way. Primitives, closures,
1212 /// maps/sets, and the host-managed handles (`Actor` / `Ticker` /
1213 /// `ArrowTable`) are returned unchanged.
1214 ///
1215 /// **The boundary helper** flagged in
1216 /// `docs/design/arena-plumbing.md` § "Arena handles MUST be
1217 /// readable at serialization". Callers — the response
1218 /// serialization path in `lex-runtime`, the trace recorder when
1219 /// it records a Call/EffectCall arg, anywhere a value crosses
1220 /// out of the VM into host-managed storage — call this
1221 /// **while the producing scope is still active**, before
1222 /// `exit_request_scope`. After exit the slab is truncated, so a
1223 /// handle materialized after-the-fact would read garbage (or
1224 /// panic on the bounds check).
1225 ///
1226 /// `Value::StackRecord` / `Value::StackTuple` would similarly
1227 /// need slab resolution, but the #464 escape analysis prevents
1228 /// them from reaching boundary-crossing ops in the first place
1229 /// (they're frame-local by construction). Reaching here means a
1230 /// hand-built or analysis-buggy program; we panic with the same
1231 /// loud-not-silent contract the other inspection paths use.
1232 ///
1233 /// Idempotent on already-materialized values (no arena handles
1234 /// in the tree → only the recursive walk's clones, no slab
1235 /// lookups). Cost per call is one walk + clone of the tree —
1236 /// amortized over the per-node mallocs avoided during request
1237 /// handling, the net stays strongly positive.
1238 pub fn materialize_arena_handles(&self, value: Value) -> Value {
1239 use crate::value::Value as V;
1240 match value {
1241 // Primitives + opaque handles cross unchanged. Cheap
1242 // — clones are essentially free for the Copy-ish ones
1243 // and Arc-bumps for the handle types.
1244 V::Int(_) | V::Float(_) | V::Bool(_) | V::Str(_) | V::Bytes(_)
1245 | V::Unit | V::Closure { .. } | V::F64Array { .. }
1246 | V::Map(_) | V::Set(_) | V::Actor(_) | V::Ticker(_)
1247 | V::ArrowTable(_) => value,
1248
1249 // Containers: recurse on each element. Map/Set keys are
1250 // MapKey (Str | Int), never Value, so no handles can
1251 // hide there.
1252 V::List(items) => V::List(
1253 items.into_iter().map(|v| self.materialize_arena_handles(v)).collect()),
1254 V::Tuple(items) => V::Tuple(
1255 items.into_iter().map(|v| self.materialize_arena_handles(v)).collect()),
1256 V::Deque(items) => V::Deque(
1257 items.into_iter().map(|v| self.materialize_arena_handles(v)).collect()),
1258 V::Variant { name, args } => V::Variant {
1259 name,
1260 args: args.into_iter().map(|v| self.materialize_arena_handles(v)).collect(),
1261 },
1262 V::Record { shape_id, fields } => {
1263 let mut out: IndexMap<SmolStr, Value> = IndexMap::with_capacity(fields.len());
1264 for (k, v) in fields.into_iter() {
1265 out.insert(k, self.materialize_arena_handles(v));
1266 }
1267 V::Record { shape_id, fields: Box::new(out) }
1268 }
1269
1270 // The actual resolution work — read the slab and build a
1271 // heap form. Field-name ordering for ArenaRecord matches
1272 // the shape's, same as `MakeRecord`'s IndexMap insertion
1273 // pattern; that's the contract that makes the polymorphic
1274 // GetField IC work, and we reuse it here.
1275 V::ArenaRecord { shape_id, slab_start, field_count } => {
1276 let start = slab_start as usize;
1277 let n = field_count as usize;
1278 debug_assert!(start + n <= self.arena_slab.len(),
1279 "ArenaRecord handle out of bounds — likely materialized after exit_request_scope");
1280 let shape = &self.program.record_shapes[shape_id as usize];
1281 let mut fields: IndexMap<SmolStr, Value> = IndexMap::with_capacity(n);
1282 for (i, name_const_idx) in shape.iter().take(n).enumerate() {
1283 let name: SmolStr = match &self.program.constants[*name_const_idx as usize] {
1284 Const::FieldName(s) => s.as_str().into(),
1285 _ => panic!("BUG(#463): ArenaRecord shape entry not a FieldName const"),
1286 };
1287 let v = self.materialize_arena_handles(self.arena_slab[start + i].clone());
1288 fields.insert(name, v);
1289 }
1290 V::Record { shape_id, fields: Box::new(fields) }
1291 }
1292 V::ArenaTuple { slab_start, arity } => {
1293 let start = slab_start as usize;
1294 let n = arity as usize;
1295 debug_assert!(start + n <= self.arena_slab.len(),
1296 "ArenaTuple handle out of bounds — likely materialized after exit_request_scope");
1297 let items: Vec<Value> = (0..n)
1298 .map(|i| self.materialize_arena_handles(self.arena_slab[start + i].clone()))
1299 .collect();
1300 V::Tuple(items)
1301 }
1302
1303 // #464 stack handles are frame-local; the analysis
1304 // prevents them from reaching any boundary the
1305 // materializer is called at. Reach = bug; panic loud.
1306 V::StackRecord { .. } =>
1307 panic!("BUG(#464/#463): Value::StackRecord reached materialize_arena_handles \
1308 — escape analysis should keep stack handles inside their frame"),
1309 V::StackTuple { .. } =>
1310 panic!("BUG(#464/#463): Value::StackTuple reached materialize_arena_handles \
1311 — escape analysis should keep stack handles inside their frame"),
1312 }
1313 }
1314
1315 /// Read a named field out of a record without materializing its
1316 /// parent. Works uniformly on `Value::Record` (heap) and
1317 /// `Value::ArenaRecord` (slab handle), so a runtime layer can
1318 /// consume the response record structurally — straight out of
1319 /// the arena slab — instead of paying for a tree-wide
1320 /// `materialize_arena_handles` walk just to read three top-level
1321 /// fields.
1322 ///
1323 /// Returns `None` if the value isn't a record or the field
1324 /// doesn't exist. The returned `Value` is a clone of the slot
1325 /// contents (records' field values can themselves be records,
1326 /// variants, etc.; cloning at the boundary is unavoidable
1327 /// without lifetime trickery on the public API).
1328 ///
1329 /// Performance: on the heap path it's a `IndexMap::get` + clone.
1330 /// On the arena path it's a linear walk of the shape's
1331 /// field-name vec (`field_count` long, typically ≤ 10) +
1332 /// an O(1) slab index + clone. The polymorphic-IC equivalent
1333 /// inside the VM is faster, but this API is for **host**
1334 /// consumers, not hot-loop dispatch.
1335 ///
1336 /// `Value::StackRecord` is deliberately not handled — those
1337 /// handles are frame-local by construction (#464 escape pass)
1338 /// and shouldn't reach host boundaries; reaching them here is
1339 /// a soundness bug surfaced as a panic, matching the existing
1340 /// inspection-path contract.
1341 pub fn get_record_field(&self, value: &Value, name: &str) -> Option<Value> {
1342 match value {
1343 Value::Record { fields, .. } => fields.get(name).cloned(),
1344 Value::ArenaRecord { shape_id, slab_start, field_count } => {
1345 let shape = self.program.record_shapes.get(*shape_id as usize)?;
1346 let n = (*field_count as usize).min(shape.len());
1347 for (i, &name_const_idx) in shape.iter().take(n).enumerate() {
1348 if let Const::FieldName(s) = &self.program.constants[name_const_idx as usize] {
1349 if s == name {
1350 return Some(self.arena_slab[*slab_start as usize + i].clone());
1351 }
1352 }
1353 }
1354 None
1355 }
1356 Value::StackRecord { .. } =>
1357 panic!("BUG(#464): Value::StackRecord reached Vm::get_record_field \
1358 — frame-local handles should never reach the host boundary"),
1359 _ => None,
1360 }
1361 }
1362
1363 /// Positional read out of a tuple without materializing its
1364 /// parent. Works uniformly on `Value::Tuple` and
1365 /// `Value::ArenaTuple`. See `get_record_field` for the lifetime
1366 /// rationale.
1367 pub fn get_tuple_elem(&self, value: &Value, idx: u16) -> Option<Value> {
1368 match value {
1369 Value::Tuple(items) => items.get(idx as usize).cloned(),
1370 Value::ArenaTuple { slab_start, arity } => {
1371 if idx >= *arity { return None; }
1372 Some(self.arena_slab[*slab_start as usize + idx as usize].clone())
1373 }
1374 Value::StackTuple { .. } =>
1375 panic!("BUG(#464): Value::StackTuple reached Vm::get_tuple_elem \
1376 — frame-local handles should never reach the host boundary"),
1377 _ => None,
1378 }
1379 }
1380
1381 /// Arena-aware `to_json` — produces a `serde_json::Value` from
1382 /// a `Value` whose tree may contain `ArenaRecord` / `ArenaTuple`
1383 /// handles, reading them straight out of `Vm::arena_slab`
1384 /// instead of materializing into a heap `Value::Record` mirror
1385 /// first.
1386 ///
1387 /// Equivalent output to `value.to_json()` on a fully-materialized
1388 /// tree (idempotent in that sense). Use this when serializing a
1389 /// handler return value to JSON for the response — saves the
1390 /// per-node IndexMap allocations the materialize-then-to_json
1391 /// pattern pays.
1392 pub fn value_to_json(&self, value: &Value) -> serde_json::Value {
1393 use serde_json::Value as J;
1394 match value {
1395 // Primitives + opaque host handles: delegate to the
1396 // existing `Value::to_json` — its output is identical
1397 // and it handles the host-handle types we don't model
1398 // (Actor / Ticker / ArrowTable / F64Array / Map / Set /
1399 // Closure / Bytes encoding) in one place.
1400 Value::Int(_) | Value::Float(_) | Value::Bool(_) | Value::Str(_)
1401 | Value::Bytes(_) | Value::Unit | Value::Closure { .. }
1402 | Value::F64Array { .. } | Value::Map(_) | Value::Set(_)
1403 | Value::Actor(_) | Value::Ticker(_) | Value::ArrowTable(_)
1404 => value.to_json(),
1405
1406 Value::List(items) => J::Array(items.iter().map(|v| self.value_to_json(v)).collect()),
1407 Value::Tuple(items) => J::Array(items.iter().map(|v| self.value_to_json(v)).collect()),
1408 Value::Deque(items) => J::Array(items.iter().map(|v| self.value_to_json(v)).collect()),
1409 Value::Variant { name, args } => {
1410 let mut m = serde_json::Map::new();
1411 m.insert("$variant".into(), J::String(name.clone()));
1412 m.insert("args".into(),
1413 J::Array(args.iter().map(|v| self.value_to_json(v)).collect()));
1414 J::Object(m)
1415 }
1416 Value::Record { fields, .. } => {
1417 let mut m = serde_json::Map::new();
1418 for (k, v) in fields.iter() {
1419 m.insert(k.to_string(), self.value_to_json(v));
1420 }
1421 J::Object(m)
1422 }
1423
1424 // Slab-direct: read the cells in shape order, emit a
1425 // JSON object using the shape's field names. The cost
1426 // delta vs the `Value::to_json` materialize-then-walk
1427 // path is the saved `Box<IndexMap>` allocation +
1428 // insertion + drop.
1429 Value::ArenaRecord { shape_id, slab_start, field_count } => {
1430 let shape = match self.program.record_shapes.get(*shape_id as usize) {
1431 Some(s) => s,
1432 None => return J::Null,
1433 };
1434 let n = (*field_count as usize).min(shape.len());
1435 let mut m = serde_json::Map::with_capacity(n);
1436 for (i, &name_const_idx) in shape.iter().take(n).enumerate() {
1437 let name = match &self.program.constants[name_const_idx as usize] {
1438 Const::FieldName(s) => s.to_string(),
1439 _ => continue,
1440 };
1441 let cell = &self.arena_slab[*slab_start as usize + i];
1442 m.insert(name, self.value_to_json(cell));
1443 }
1444 J::Object(m)
1445 }
1446 Value::ArenaTuple { slab_start, arity } => {
1447 let start = *slab_start as usize;
1448 let n = *arity as usize;
1449 let items: Vec<serde_json::Value> = (0..n)
1450 .map(|i| self.value_to_json(&self.arena_slab[start + i]))
1451 .collect();
1452 J::Array(items)
1453 }
1454
1455 // Stack handles must not reach the host — same defensive
1456 // panic as the other inspection paths.
1457 Value::StackRecord { .. } =>
1458 panic!("BUG(#464): Value::StackRecord reached Vm::value_to_json \
1459 — frame-local handles should never reach the host boundary"),
1460 Value::StackTuple { .. } =>
1461 panic!("BUG(#464): Value::StackTuple reached Vm::value_to_json \
1462 — frame-local handles should never reach the host boundary"),
1463 }
1464 }
1465
1466 pub fn invoke(&mut self, fn_id: u32, args: Vec<Value>) -> Result<Value, VmError> {
1467 let f = &self.program.functions[fn_id as usize];
1468 if args.len() != f.arity as usize {
1469 return Err(VmError::Panic(format!("arity mismatch calling {}", f.name)));
1470 }
1471 // Refinement runtime check at the public entry point too
1472 // (#209 slice 3). `Op::Call` checks for in-program calls;
1473 // this branch covers `vm.call("entry", ...)` from the host
1474 // and the reentrant `invoke_closure_value` path. Same
1475 // semantics, same error shape.
1476 //
1477 // Iterate `f.refinements` by reference — the loop body
1478 // only reads from `self.program` (via `r`) and from locals,
1479 // so we don't need to clone the Vec to detach it from
1480 // `&self`. The function name is cloned **lazily**, only on
1481 // the failure path: functions with no refinements (the common
1482 // case) never enter the loop, so the per-call `f.name.clone()`
1483 // was pure waste on the hot path (#464 call-overhead).
1484 for (i, refinement) in f.refinements.iter().enumerate() {
1485 if let Some(r) = refinement {
1486 let arg = args.get(i).cloned().unwrap_or(Value::Unit);
1487 match eval_refinement(&r.predicate, &r.binding, &arg) {
1488 Ok(true) => {}
1489 Ok(false) => return Err(VmError::RefinementFailed {
1490 fn_name: f.name.clone(),
1491 param_index: i,
1492 binding: r.binding.clone(),
1493 reason: format!("predicate failed for {} = {arg:?}", r.binding),
1494 }),
1495 Err(reason) => return Err(VmError::RefinementFailed {
1496 fn_name: f.name.clone(),
1497 param_index: i,
1498 binding: r.binding.clone(),
1499 reason,
1500 }),
1501 }
1502 }
1503 }
1504 // #465 JIT tier hook at the public entry — same contract as
1505 // the `Op::Call` dispatch arm. Pure-fn memo is not consulted
1506 // at this layer (memo is per-Op::Call); the hook fires
1507 // unconditionally for refinement-clean calls.
1508 if let Some(mut hook) = self.jit_hook.take() {
1509 let hook_result = hook.try_call(fn_id, &args);
1510 self.jit_hook = Some(hook);
1511 if let Some(result) = hook_result? {
1512 return Ok(result);
1513 }
1514 }
1515 let f = &self.program.functions[fn_id as usize];
1516 // Claim slots from the locals stack allocator (#389 slice 3).
1517 let locals_start = self.locals_storage.len();
1518 let locals_len = f.locals_count.max(f.arity) as usize;
1519 self.locals_storage.resize(locals_start + locals_len, Value::Unit);
1520 for (i, v) in args.into_iter().enumerate() {
1521 self.locals_storage[locals_start + i] = v;
1522 }
1523 // Record the depth before pushing — this is what `run` will
1524 // exit at, supporting reentrant invocation from inside the
1525 // VM (e.g. the parser interpreter calling closures, #221).
1526 let base_depth = self.frames.len();
1527 self.push_frame(Frame {
1528 fn_id, pc: 0, locals_start, locals_len,
1529 stack_base: self.stack.len(),
1530 trace_kind: FrameKind::Entry,
1531 memo_key: None,
1532 stack_record_arena_start: self.stack_record_arena.len(),
1533 stack_record_budget_remaining: STACK_RECORD_BUDGET_SLOTS,
1534 })?;
1535 self.run_to(base_depth)
1536 }
1537
1538 /// All call-frame pushes funnel through here so the depth
1539 /// check can't be skipped by a missing branch. Returns
1540 /// `CallStackOverflow` instead of letting recursion blow the
1541 /// host's native stack.
1542 fn push_frame(&mut self, frame: Frame) -> Result<(), VmError> {
1543 if self.frames.len() as u32 >= MAX_CALL_DEPTH {
1544 return Err(VmError::CallStackOverflow(MAX_CALL_DEPTH));
1545 }
1546 self.frames.push(frame);
1547 Ok(())
1548 }
1549
1550 /// Run until the frame stack drops to `base_depth`. Required for
1551 /// reentrant invocation: a `Vm::invoke` call from inside an
1552 /// already-running `run()` must return when *its* frame returns,
1553 /// not when the entire frame stack empties (#221).
1554 fn run_to(&mut self, base_depth: usize) -> Result<Value, VmError> {
1555 // #461 slice A: cache the executing function's code slice across
1556 // ops instead of re-deriving `program.functions[fn_id].code` on
1557 // every iteration. The program is borrowed (`&'a Program`) and is
1558 // never mutated during a run, so the slice reference is valid for
1559 // the whole run and — crucially — is independent of the `&mut self`
1560 // borrow the op handlers take: it points into the caller-owned
1561 // `Program`, not into `*self`. Re-resolve only when `fn_id`
1562 // changes, which is exactly the frame-transition set (Call /
1563 // CallClosure / TailCall / Return); recursion into the same
1564 // `fn_id` correctly keeps the cached slice. `frame_idx` / `fn_id`
1565 // stay recomputed per op (cheap field reads), so the op handlers
1566 // are untouched and their `fn_id` bindings shadow as before.
1567 let program: &'a Program = self.program;
1568 let mut code: &'a [Op] = &[];
1569 let mut code_fn_id: u32 = u32::MAX;
1570 loop {
1571 if self.steps > self.step_limit {
1572 let frame_idx = self.frames.len() - 1;
1573 let fn_id = self.frames[frame_idx].fn_id;
1574 let fn_name = &program.functions[fn_id as usize].name;
1575 return Err(VmError::Panic(format!(
1576 "step limit exceeded in `{fn_name}` ({} > {})",
1577 self.steps, self.step_limit,
1578 )));
1579 }
1580 self.steps += 1;
1581 let frame_idx = self.frames.len() - 1;
1582 let pc = self.frames[frame_idx].pc;
1583 let fn_id = self.frames[frame_idx].fn_id;
1584 if fn_id != code_fn_id {
1585 code = &program.functions[fn_id as usize].code;
1586 code_fn_id = fn_id;
1587 }
1588 // #461 slice B: the bytecode verifier (#366) proves pc stays
1589 // in bounds for every reachable op — every path through a
1590 // function ends in Return / Jump / TailCall, so execution
1591 // never falls off the end of `code`. The per-op
1592 // `pc >= code.len()` guard is therefore redundant for verified
1593 // programs; demote it to a debug-only assertion. The `code[pc]`
1594 // index below stays bounds-checked, so a malformed program in
1595 // a release build still panics (loudly, just without the
1596 // bespoke message) rather than reading out of bounds — no
1597 // `unsafe`, no UB, only the cold error-return path leaves the
1598 // hot loop.
1599 debug_assert!(
1600 pc < code.len(),
1601 "ran past end of code in `{}`",
1602 program.functions[fn_id as usize].name,
1603 );
1604 let op = code[pc];
1605 self.frames[frame_idx].pc = pc + 1;
1606
1607 match op {
1608 Op::PushConst(i) => {
1609 let c = &self.program.constants[i as usize];
1610 self.stack.push(const_to_value(c));
1611 }
1612 Op::Pop => { self.pop()?; }
1613 Op::Dup => {
1614 let v = self.peek()?.clone();
1615 self.stack.push(v);
1616 }
1617 Op::LoadLocal(i) => {
1618 let base = self.frames[frame_idx].locals_start;
1619 let v = self.locals_storage[base + i as usize].clone();
1620 self.stack.push(v);
1621 }
1622 Op::StoreLocal(i) => {
1623 let v = self.pop()?;
1624 let base = self.frames[frame_idx].locals_start;
1625 self.locals_storage[base + i as usize] = v;
1626 }
1627 Op::MakeRecord { shape_idx, field_count } => {
1628 self.heap_record_allocs += 1;
1629 let shape = &self.program.record_shapes[shape_idx as usize];
1630 let n = field_count as usize;
1631 debug_assert_eq!(shape.len(), n,
1632 "MakeRecord field_count must match record_shapes[shape_idx].len()");
1633 let mut values: Vec<Value> = (0..n).map(|_| Value::Unit).collect();
1634 for i in (0..n).rev() {
1635 values[i] = self.pop()?;
1636 }
1637 let mut rec: IndexMap<SmolStr, Value> = IndexMap::with_capacity(n);
1638 for (i, val) in values.into_iter().enumerate() {
1639 let name: SmolStr = match &self.program.constants[shape[i] as usize] {
1640 Const::FieldName(s) => s.as_str().into(),
1641 _ => return Err(VmError::TypeMismatch("expected FieldName const".into())),
1642 };
1643 rec.insert(name, val);
1644 }
1645 self.stack.push(Value::Record { shape_id: shape_idx, fields: Box::new(rec) });
1646 }
1647 Op::AllocStackRecord { shape_idx, field_count } => {
1648 // #464 step 2. Same value-stack contract as
1649 // MakeRecord (pop `field_count`, push 1), but the
1650 // fields live in the VM's stack-record arena
1651 // instead of a heap-allocated IndexMap.
1652 //
1653 // Budget check: if this frame's remaining
1654 // allocation budget can't cover `field_count`
1655 // slots, fall back to MakeRecord behavior. The
1656 // observable result is identical (a record
1657 // value) so the compiler doesn't need to know
1658 // ahead of time whether the budget will hold.
1659 let n = field_count as usize;
1660 let frame = &mut self.frames[frame_idx];
1661 if frame.stack_record_budget_remaining < field_count as u32 {
1662 self.stack_record_heap_fallbacks += 1;
1663 // Heap fallback path — exact copy of
1664 // MakeRecord's body. Compiler emitted
1665 // AllocStackRecord because escape analysis
1666 // proved the record can stay frame-local;
1667 // the budget exhaustion is a runtime cost
1668 // ceiling, not a correctness issue.
1669 let shape = &self.program.record_shapes[shape_idx as usize];
1670 debug_assert_eq!(shape.len(), n,
1671 "AllocStackRecord field_count must match record_shapes[shape_idx].len()");
1672 let mut values: Vec<Value> = (0..n).map(|_| Value::Unit).collect();
1673 for i in (0..n).rev() {
1674 values[i] = self.pop()?;
1675 }
1676 let mut rec: IndexMap<SmolStr, Value> = IndexMap::with_capacity(n);
1677 for (i, val) in values.into_iter().enumerate() {
1678 let name: SmolStr = match &self.program.constants[shape[i] as usize] {
1679 Const::FieldName(s) => s.as_str().into(),
1680 _ => return Err(VmError::TypeMismatch("expected FieldName const".into())),
1681 };
1682 rec.insert(name, val);
1683 }
1684 self.stack.push(Value::Record { shape_id: shape_idx, fields: Box::new(rec) });
1685 } else {
1686 self.stack_record_allocs += 1;
1687 // Stack path: append the popped field values
1688 // to the arena in shape order (matches the
1689 // IndexMap insertion order used by MakeRecord,
1690 // so the polymorphic GetField IC sees the same
1691 // offset for either variant).
1692 frame.stack_record_budget_remaining -= field_count as u32;
1693 let slab_start = self.stack_record_arena.len();
1694 // Reserve all slots upfront so we can write in
1695 // shape order while popping in reverse —
1696 // matches MakeRecord's idiom.
1697 self.stack_record_arena.resize(slab_start + n, Value::Unit);
1698 for i in (0..n).rev() {
1699 let v = self.pop()?;
1700 self.stack_record_arena[slab_start + i] = v;
1701 }
1702 self.stack.push(Value::StackRecord {
1703 shape_id: shape_idx,
1704 slab_start: slab_start as u32,
1705 field_count,
1706 });
1707 }
1708 }
1709 Op::AllocArenaRecord { shape_idx, field_count } => {
1710 // #463 slice 2a. Same value-stack contract as
1711 // MakeRecord, but field values land in the
1712 // request-scoped `arena_slab` instead of a
1713 // per-field heap IndexMap. Runtime fallback when
1714 // no scope is active — the op silently degrades
1715 // to the MakeRecord heap path so arena-lowered
1716 // bytecode stays sound in non-handler contexts
1717 // (REPL, tests, top-level scripts).
1718 let n = field_count as usize;
1719 if self.arena_scope_starts.is_empty() {
1720 self.arena_record_heap_fallbacks += 1;
1721 // Heap fallback path — exact copy of
1722 // MakeRecord's body. Same compile-time
1723 // contract (shape order, IndexMap insertion)
1724 // so the resulting Value::Record is
1725 // indistinguishable from a direct MakeRecord.
1726 let shape = &self.program.record_shapes[shape_idx as usize];
1727 debug_assert_eq!(shape.len(), n,
1728 "AllocArenaRecord field_count must match record_shapes[shape_idx].len()");
1729 let mut values: Vec<Value> = (0..n).map(|_| Value::Unit).collect();
1730 for i in (0..n).rev() {
1731 values[i] = self.pop()?;
1732 }
1733 let mut rec: IndexMap<SmolStr, Value> = IndexMap::with_capacity(n);
1734 for (i, val) in values.into_iter().enumerate() {
1735 let name: SmolStr = match &self.program.constants[shape[i] as usize] {
1736 Const::FieldName(s) => s.as_str().into(),
1737 _ => return Err(VmError::TypeMismatch("expected FieldName const".into())),
1738 };
1739 rec.insert(name, val);
1740 }
1741 self.stack.push(Value::Record { shape_id: shape_idx, fields: Box::new(rec) });
1742 } else {
1743 self.arena_record_allocs += 1;
1744 // Arena path: append the popped field values
1745 // to the slab in shape order (matches
1746 // MakeRecord's IndexMap insertion order, so
1747 // the polymorphic GetField IC sees the same
1748 // offset across all three variants).
1749 let slab_start = self.arena_slab.len();
1750 self.arena_slab.resize(slab_start + n, Value::Unit);
1751 for i in (0..n).rev() {
1752 let v = self.pop()?;
1753 self.arena_slab[slab_start + i] = v;
1754 }
1755 self.stack.push(Value::ArenaRecord {
1756 shape_id: shape_idx,
1757 slab_start: slab_start as u32,
1758 field_count,
1759 });
1760 }
1761 }
1762 Op::MakeTuple(n) => {
1763 let mut items: Vec<Value> = (0..n).map(|_| Value::Unit).collect();
1764 for i in (0..n as usize).rev() { items[i] = self.pop()?; }
1765 self.stack.push(Value::Tuple(items));
1766 }
1767 Op::AllocStackTuple { arity } => {
1768 // #464 tuple codegen. Same value-stack contract as
1769 // MakeTuple (pop `arity`, push 1), but the elements
1770 // live in the shared stack-record arena instead of
1771 // a heap Vec. Budget exhaustion falls back to the
1772 // MakeTuple heap path — identical observable result.
1773 let n = arity as usize;
1774 let frame = &mut self.frames[frame_idx];
1775 if frame.stack_record_budget_remaining < arity as u32 {
1776 self.stack_record_heap_fallbacks += 1;
1777 let mut items: Vec<Value> = (0..n).map(|_| Value::Unit).collect();
1778 for i in (0..n).rev() { items[i] = self.pop()?; }
1779 self.stack.push(Value::Tuple(items));
1780 } else {
1781 self.stack_record_allocs += 1;
1782 frame.stack_record_budget_remaining -= arity as u32;
1783 let slab_start = self.stack_record_arena.len();
1784 self.stack_record_arena.resize(slab_start + n, Value::Unit);
1785 for i in (0..n).rev() {
1786 let v = self.pop()?;
1787 self.stack_record_arena[slab_start + i] = v;
1788 }
1789 self.stack.push(Value::StackTuple {
1790 slab_start: slab_start as u32,
1791 arity,
1792 });
1793 }
1794 }
1795 Op::AllocArenaTuple { arity } => {
1796 // #463 slice 2a. Tuple analogue of
1797 // AllocArenaRecord: arena slab when a scope is
1798 // active, MakeTuple heap fallback otherwise.
1799 let n = arity as usize;
1800 if self.arena_scope_starts.is_empty() {
1801 self.arena_record_heap_fallbacks += 1;
1802 let mut items: Vec<Value> = (0..n).map(|_| Value::Unit).collect();
1803 for i in (0..n).rev() { items[i] = self.pop()?; }
1804 self.stack.push(Value::Tuple(items));
1805 } else {
1806 self.arena_record_allocs += 1;
1807 let slab_start = self.arena_slab.len();
1808 self.arena_slab.resize(slab_start + n, Value::Unit);
1809 for i in (0..n).rev() {
1810 let v = self.pop()?;
1811 self.arena_slab[slab_start + i] = v;
1812 }
1813 self.stack.push(Value::ArenaTuple {
1814 slab_start: slab_start as u32,
1815 arity,
1816 });
1817 }
1818 }
1819 Op::MakeList(n) => {
1820 let mut items: Vec<Value> = (0..n).map(|_| Value::Unit).collect();
1821 for i in (0..n as usize).rev() { items[i] = self.pop()?; }
1822 self.stack.push(Value::List(items.into()));
1823 }
1824 Op::MakeVariant { name_idx, arity } => {
1825 let mut args: Vec<Value> = (0..arity).map(|_| Value::Unit).collect();
1826 for i in (0..arity as usize).rev() { args[i] = self.pop()?; }
1827 let name = match &self.program.constants[name_idx as usize] {
1828 Const::VariantName(s) => s.clone(),
1829 _ => return Err(VmError::TypeMismatch("expected VariantName const".into())),
1830 };
1831 self.stack.push(Value::Variant { name, args });
1832 }
1833 Op::GetField { name_idx, site_idx } => {
1834 let v = self.pop()?;
1835 match v {
1836 Value::Record { fields: r, shape_id } => {
1837 if ic_stats_enabled() {
1838 record_ic_hit(fn_id, site_idx, shape_id);
1839 }
1840 // Inline cache keyed by (fn_id, site_idx) with
1841 // shape_id-keyed verification (#462). Slot stores
1842 // (shape_id_at_install, offset). Hit verification:
1843 // - real shape_id (!= NO_SHAPE_ID) matches: offset
1844 // is guaranteed valid (records with the same
1845 // shape_id share the same field-name ordering
1846 // from the compile-time `record_shapes` table).
1847 // One u32 compare; no string work.
1848 // - NO_SHAPE_ID matches NO_SHAPE_ID: distinct
1849 // dynamic shapes both carry this sentinel and
1850 // would otherwise alias, so we fall back to
1851 // verifying via name compare against the field
1852 // at the cached offset — the pre-slice
1853 // correctness path.
1854 // On any mismatch we walk by name and reinstall
1855 // (shape_id, offset).
1856 let fid = fn_id as usize;
1857 let sid = site_idx as usize;
1858 if self.field_ics[fid].is_empty() {
1859 let n = self.program.functions[fid].field_ic_sites as usize;
1860 self.field_ics[fid] = vec![None; n];
1861 }
1862 let cached = self.field_ics[fid][sid];
1863 let value = 'ic: {
1864 if let Some((cached_shape, off)) = cached {
1865 if cached_shape == shape_id {
1866 if shape_id != crate::value::NO_SHAPE_ID {
1867 // Real shape match: offset is sound.
1868 if let Some((_, val)) = r.get_index(off) {
1869 break 'ic val.clone();
1870 }
1871 } else if let Some((k, val)) = r.get_index(off) {
1872 // Dynamic shape: verify by name.
1873 if let Const::FieldName(s) =
1874 &self.program.constants[name_idx as usize]
1875 {
1876 if s == k { break 'ic val.clone(); }
1877 }
1878 }
1879 }
1880 }
1881 // Cache miss: resolve by name, install
1882 // (shape_id, offset).
1883 let name = match &self.program.constants[name_idx as usize] {
1884 Const::FieldName(s) => s.as_str(),
1885 _ => return Err(VmError::TypeMismatch(
1886 "expected FieldName const".into())),
1887 };
1888 let (off, _, val) = r.get_full(name)
1889 .ok_or_else(|| VmError::TypeMismatch(
1890 format!("missing field `{name}`")))?;
1891 self.field_ics[fid][sid] = Some((shape_id, off));
1892 val.clone()
1893 };
1894 self.stack.push(value);
1895 }
1896 Value::StackRecord { shape_id, slab_start, field_count } => {
1897 // #464 step 2: dispatch over a stack-allocated
1898 // record. The IC slot stored
1899 // (shape_id, offset_in_shape) is interoperable
1900 // with the heap path because MakeRecord builds
1901 // the IndexMap in shape order — offset N means
1902 // the same field in either representation. So
1903 // we share `field_ics` with the heap path; no
1904 // per-variant cache pollution.
1905 if ic_stats_enabled() {
1906 record_ic_hit(fn_id, site_idx, shape_id);
1907 }
1908 let fid = fn_id as usize;
1909 let sid = site_idx as usize;
1910 if self.field_ics[fid].is_empty() {
1911 let n = self.program.functions[fid].field_ic_sites as usize;
1912 self.field_ics[fid] = vec![None; n];
1913 }
1914 let cached = self.field_ics[fid][sid];
1915 let value = 'ic: {
1916 if let Some((cached_shape, off)) = cached {
1917 if cached_shape == shape_id && (off as u16) < field_count {
1918 // Shape-keyed verification is sound
1919 // here for the same reason as the
1920 // heap path — compile-time shape
1921 // IDs are issued by
1922 // `Program::record_shapes` and
1923 // their field order is fixed.
1924 // Stack records always carry a
1925 // compile-time shape_id (NO_SHAPE_ID
1926 // is impossible — AllocStackRecord
1927 // is only emitted at compile time
1928 // with a known shape_idx).
1929 let idx = slab_start as usize + off;
1930 break 'ic self.stack_record_arena[idx].clone();
1931 }
1932 }
1933 // Cache miss: walk the shape's field-name
1934 // vec to find the slot for `name_idx`. The
1935 // miss path is O(field_count) like the
1936 // heap path, but the hot retrieval after
1937 // install is one array index — cheaper
1938 // than IndexMap::get_index.
1939 let shape =
1940 &self.program.record_shapes[shape_id as usize];
1941 let target_name = match &self.program.constants[name_idx as usize] {
1942 Const::FieldName(s) => s.as_str(),
1943 _ => return Err(VmError::TypeMismatch(
1944 "expected FieldName const".into())),
1945 };
1946 let mut found: Option<usize> = None;
1947 for (i, fn_const_idx) in shape.iter().enumerate() {
1948 if let Const::FieldName(s) =
1949 &self.program.constants[*fn_const_idx as usize]
1950 {
1951 if s == target_name { found = Some(i); break; }
1952 }
1953 }
1954 let off = found.ok_or_else(|| VmError::TypeMismatch(
1955 format!("missing field `{target_name}` on stack record")))?;
1956 self.field_ics[fid][sid] = Some((shape_id, off));
1957 self.stack_record_arena[slab_start as usize + off].clone()
1958 };
1959 self.stack.push(value);
1960 }
1961 Value::ArenaRecord { shape_id, slab_start, field_count } => {
1962 // #463 slice 2a: dispatch over an
1963 // arena-allocated record. Identical IC
1964 // story to `StackRecord` above — the slot
1965 // stores `(shape_id, offset)` and offset
1966 // semantics match `Value::Record`'s
1967 // IndexMap insertion order, so the IC is
1968 // three-way interoperable.
1969 if ic_stats_enabled() {
1970 record_ic_hit(fn_id, site_idx, shape_id);
1971 }
1972 let fid = fn_id as usize;
1973 let sid = site_idx as usize;
1974 if self.field_ics[fid].is_empty() {
1975 let n = self.program.functions[fid].field_ic_sites as usize;
1976 self.field_ics[fid] = vec![None; n];
1977 }
1978 let cached = self.field_ics[fid][sid];
1979 let value = 'ic: {
1980 if let Some((cached_shape, off)) = cached {
1981 if cached_shape == shape_id && (off as u16) < field_count {
1982 let idx = slab_start as usize + off;
1983 break 'ic self.arena_slab[idx].clone();
1984 }
1985 }
1986 let shape =
1987 &self.program.record_shapes[shape_id as usize];
1988 let target_name = match &self.program.constants[name_idx as usize] {
1989 Const::FieldName(s) => s.as_str(),
1990 _ => return Err(VmError::TypeMismatch(
1991 "expected FieldName const".into())),
1992 };
1993 let mut found: Option<usize> = None;
1994 for (i, fn_const_idx) in shape.iter().enumerate() {
1995 if let Const::FieldName(s) =
1996 &self.program.constants[*fn_const_idx as usize]
1997 {
1998 if s == target_name { found = Some(i); break; }
1999 }
2000 }
2001 let off = found.ok_or_else(|| VmError::TypeMismatch(
2002 format!("missing field `{target_name}` on arena record")))?;
2003 self.field_ics[fid][sid] = Some((shape_id, off));
2004 self.arena_slab[slab_start as usize + off].clone()
2005 };
2006 self.stack.push(value);
2007 }
2008 other => return Err(VmError::TypeMismatch(
2009 format!("GetField on non-record: {other:?}"))),
2010 }
2011 }
2012 Op::GetElem(i) => {
2013 let v = self.pop()?;
2014 match v {
2015 Value::Tuple(items) => {
2016 let v = items.into_iter().nth(i as usize)
2017 .ok_or_else(|| VmError::TypeMismatch(format!("tuple index {i} out of range")))?;
2018 self.stack.push(v);
2019 }
2020 // #464 tuple codegen: positional read out of a
2021 // frame-local tuple. The arena slot is an O(1)
2022 // index, mirroring the heap path's nth().
2023 Value::StackTuple { slab_start, arity } => {
2024 if i >= arity {
2025 return Err(VmError::TypeMismatch(
2026 format!("tuple index {i} out of range")));
2027 }
2028 let v = self.stack_record_arena[slab_start as usize + i as usize].clone();
2029 self.stack.push(v);
2030 }
2031 // #463 slice 2a: positional read out of an
2032 // arena tuple — same O(1) index pattern as
2033 // StackTuple but through `arena_slab`.
2034 Value::ArenaTuple { slab_start, arity } => {
2035 if i >= arity {
2036 return Err(VmError::TypeMismatch(
2037 format!("tuple index {i} out of range")));
2038 }
2039 let v = self.arena_slab[slab_start as usize + i as usize].clone();
2040 self.stack.push(v);
2041 }
2042 other => return Err(VmError::TypeMismatch(format!("GetElem on non-tuple: {other:?}"))),
2043 }
2044 }
2045 Op::TestVariant(i) => {
2046 let name = match &self.program.constants[i as usize] {
2047 Const::VariantName(s) => s.clone(),
2048 _ => return Err(VmError::TypeMismatch("expected VariantName const".into())),
2049 };
2050 let v = self.pop()?;
2051 match &v {
2052 Value::Variant { name: vname, .. } => {
2053 self.stack.push(Value::Bool(vname == &name));
2054 }
2055 // For tag-only enums of primitive type (e.g. ParseError = Empty | NotNumber)
2056 // the value is currently a Variant too, since constructors emit MakeVariant.
2057 other => return Err(VmError::TypeMismatch(format!("TestVariant on non-variant: {other:?}"))),
2058 }
2059 }
2060 Op::GetVariant(_i) => {
2061 let v = self.pop()?;
2062 match v {
2063 Value::Variant { args, .. } => {
2064 self.stack.push(Value::Tuple(args));
2065 }
2066 other => return Err(VmError::TypeMismatch(format!("GetVariant on non-variant: {other:?}"))),
2067 }
2068 }
2069 Op::GetVariantArg(i) => {
2070 let v = self.pop()?;
2071 match v {
2072 Value::Variant { mut args, .. } => {
2073 if (i as usize) >= args.len() {
2074 return Err(VmError::TypeMismatch("variant arg index oob".into()));
2075 }
2076 self.stack.push(args.swap_remove(i as usize));
2077 }
2078 other => return Err(VmError::TypeMismatch(format!("GetVariantArg on non-variant: {other:?}"))),
2079 }
2080 }
2081 Op::GetListLen => {
2082 let v = self.pop()?;
2083 match v {
2084 Value::List(items) => self.stack.push(Value::Int(items.len() as i64)),
2085 other => return Err(VmError::TypeMismatch(format!("GetListLen on non-list: {other:?}"))),
2086 }
2087 }
2088 Op::GetListElem(i) => {
2089 let v = self.pop()?;
2090 match v {
2091 Value::List(items) => {
2092 let v = items.into_iter().nth(i as usize)
2093 .ok_or_else(|| VmError::TypeMismatch("list index oob".into()))?;
2094 self.stack.push(v);
2095 }
2096 other => return Err(VmError::TypeMismatch(format!("GetListElem on non-list: {other:?}"))),
2097 }
2098 }
2099 Op::GetListElemDyn => {
2100 // Stack: [list, idx]
2101 let idx = match self.pop()? {
2102 Value::Int(n) => n as usize,
2103 other => return Err(VmError::TypeMismatch(format!("GetListElemDyn idx: {other:?}"))),
2104 };
2105 let v = self.pop()?;
2106 match v {
2107 Value::List(items) => {
2108 let v = items.into_iter().nth(idx)
2109 .ok_or_else(|| VmError::TypeMismatch("list index oob".into()))?;
2110 self.stack.push(v);
2111 }
2112 other => return Err(VmError::TypeMismatch(format!("GetListElemDyn on non-list: {other:?}"))),
2113 }
2114 }
2115 Op::ListAppend => {
2116 let value = self.pop()?;
2117 let list = self.pop()?;
2118 match list {
2119 Value::List(mut items) => {
2120 items.push_back(value);
2121 self.stack.push(Value::List(items));
2122 }
2123 other => return Err(VmError::TypeMismatch(format!("ListAppend on non-list: {other:?}"))),
2124 }
2125 }
2126 Op::Jump(off) => {
2127 let new_pc = (self.frames[frame_idx].pc as i32 + off) as usize;
2128 self.frames[frame_idx].pc = new_pc;
2129 }
2130 Op::JumpIf(off) => {
2131 let v = self.pop()?;
2132 if v.as_bool() {
2133 let new_pc = (self.frames[frame_idx].pc as i32 + off) as usize;
2134 self.frames[frame_idx].pc = new_pc;
2135 }
2136 }
2137 Op::JumpIfNot(off) => {
2138 let v = self.pop()?;
2139 if !v.as_bool() {
2140 let new_pc = (self.frames[frame_idx].pc as i32 + off) as usize;
2141 self.frames[frame_idx].pc = new_pc;
2142 }
2143 }
2144 Op::MakeClosure { fn_id, capture_count } => {
2145 let n = capture_count as usize;
2146 let mut captures: Vec<Value> = (0..n).map(|_| Value::Unit).collect();
2147 for i in (0..n).rev() { captures[i] = self.pop()?; }
2148 // Look up the canonical body hash so the resulting
2149 // `Value::Closure` carries it for equality (#222).
2150 let body_hash = self.program.functions[fn_id as usize].body_hash;
2151 self.stack.push(Value::Closure { fn_id, body_hash, captures });
2152 }
2153 Op::CallClosure { arity, node_id_idx } => {
2154 let arity = arity as usize;
2155 // Args sit on the value stack at [args_base..]; the
2156 // closure sits just below them at args_base - 1. Take
2157 // the closure out (leaving a Unit placeholder), then
2158 // write its captures and pop the args directly into
2159 // the callee's locals — no per-call args Vec and no
2160 // `captures.extend(args)` realloc (#464). The combined
2161 // [captures, args] view the tracer wants is exactly
2162 // the contiguous locals slice we just filled.
2163 let args_base = self.stack.len() - arity;
2164 let closure = std::mem::replace(&mut self.stack[args_base - 1], Value::Unit);
2165 let (fn_id, captures) = match closure {
2166 Value::Closure { fn_id, captures, .. } => (fn_id, captures),
2167 other => return Err(VmError::TypeMismatch(format!("CallClosure on non-closure: {other:?}"))),
2168 };
2169 let fid = fn_id as usize;
2170 let node_id = const_str(&self.program.constants, node_id_idx);
2171 let budget_cost = call_budget_cost(&self.program.functions[fid]);
2172 if budget_cost > 0 {
2173 self.handler.note_call_budget(budget_cost)
2174 .map_err(VmError::Effect)?;
2175 }
2176 let cap_n = captures.len();
2177 let locals_start = self.locals_storage.len();
2178 let locals_len = self.program.functions[fid].locals_count
2179 .max(self.program.functions[fid].arity) as usize;
2180 self.locals_storage.resize(locals_start + locals_len, Value::Unit);
2181 for (i, v) in captures.into_iter().enumerate() {
2182 self.locals_storage[locals_start + i] = v;
2183 }
2184 // Move the args off the value stack into the locals
2185 // following the captures (popping leaves the args off
2186 // the stack; the closure's Unit placeholder is then
2187 // the top, so truncate it away).
2188 for i in (0..arity).rev() {
2189 self.locals_storage[locals_start + cap_n + i] = self.pop()?;
2190 }
2191 self.stack.truncate(args_base - 1);
2192 self.tracer.enter_call(&node_id, &self.program.functions[fid].name, &self.locals_storage[locals_start..locals_start + cap_n + arity]);
2193 self.push_frame(Frame {
2194 fn_id, pc: 0, locals_start, locals_len,
2195 stack_base: self.stack.len(),
2196 trace_kind: FrameKind::Call(node_id),
2197 // Op::CallClosure intentionally doesn't memoize
2198 // for v1 (#229) — closures over captures need a
2199 // hashing strategy that includes the captures.
2200 // Direct Op::Call is the v1 surface.
2201 memo_key: None,
2202 stack_record_arena_start: self.stack_record_arena.len(),
2203 stack_record_budget_remaining: STACK_RECORD_BUDGET_SLOTS,
2204 })?;
2205 }
2206 Op::SortByKey { node_id_idx: _ } => {
2207 // #338: pop (xs, f). For each x in xs, invoke
2208 // f(x) to derive a sortable key. Stable-sort the
2209 // (key, value) pairs by key. Return the values
2210 // in sorted order. Keys must be Int / Float /
2211 // Str; mixed-type pairs and other types compare
2212 // as equal (preserving original order — stable
2213 // sort).
2214 let f = self.pop()?;
2215 let xs = self.pop()?;
2216 let items = match xs {
2217 Value::List(v) => v,
2218 other => return Err(VmError::TypeMismatch(
2219 format!("SortByKey requires a List, got: {other:?}"))),
2220 };
2221 if !matches!(f, Value::Closure { .. }) {
2222 return Err(VmError::TypeMismatch(
2223 format!("SortByKey requires a closure, got: {f:?}")));
2224 }
2225 let mut keyed: Vec<(Value, Value)> = Vec::with_capacity(items.len());
2226 for item in items {
2227 let key = self.invoke_closure_1(f.clone(), item.clone())?;
2228 keyed.push((key, item));
2229 }
2230 keyed.sort_by(|(ka, _), (kb, _)| compare_sort_keys(ka, kb));
2231 let sorted: VecDeque<Value> = keyed.into_iter().map(|(_, v)| v).collect();
2232 self.stack.push(Value::List(sorted));
2233 }
2234 Op::ParallelMap { node_id_idx: _ } => {
2235 // #305 slice 1: pop (xs, f) and apply f to each
2236 // element across OS threads.
2237 //
2238 // #305 slice 2: each worker now asks the parent
2239 // handler for a thread-safe per-worker handler via
2240 // `EffectHandler::spawn_for_worker`. Handlers that
2241 // opt in (e.g. `DefaultHandler`) yield a fresh
2242 // instance sharing the budget pool; handlers that
2243 // don't fall back to the slice-1 behavior of
2244 // `DenyAllEffects` in the worker.
2245 let f = self.pop()?;
2246 let xs = self.pop()?;
2247 let items = match xs {
2248 Value::List(v) => v,
2249 other => return Err(VmError::TypeMismatch(
2250 format!("ParallelMap requires a List, got: {other:?}"))),
2251 };
2252 if !matches!(f, Value::Closure { .. }) {
2253 return Err(VmError::TypeMismatch(
2254 format!("ParallelMap requires a closure, got: {f:?}")));
2255 }
2256 // Pre-build one handler per worker on the main
2257 // thread so the worker just owns its handler with
2258 // no shared borrowing. The actual worker count is
2259 // capped by `LEX_PAR_MAX_CONCURRENCY` (resolved
2260 // inside par_map_run); cap ≤ items.len() so we
2261 // never over-allocate handlers.
2262 let n_workers = par_max_concurrency().max(1).min(items.len().max(1));
2263 let mut worker_handlers: Vec<Box<dyn EffectHandler + Send>> =
2264 Vec::with_capacity(n_workers);
2265 for _ in 0..n_workers {
2266 worker_handlers.push(
2267 self.handler
2268 .spawn_for_worker()
2269 .unwrap_or_else(|| Box::new(DenyAllEffects)),
2270 );
2271 }
2272 let results = par_map_run(self.program, f, items.into_iter().collect(), worker_handlers)?;
2273 self.stack.push(Value::List(results.into()));
2274 }
2275 Op::ListMap { node_id_idx: _ } => {
2276 // #464: native map. Owns `xs` (no per-iteration
2277 // clone of the input or accumulator that the old
2278 // inlined `LoadLocal`-based loop incurred) and
2279 // builds the output with one pre-sized allocation.
2280 let f = self.pop()?;
2281 let xs = self.pop()?;
2282 let items = match xs {
2283 Value::List(v) => v,
2284 other => return Err(VmError::TypeMismatch(
2285 format!("ListMap requires a List, got: {other:?}"))),
2286 };
2287 if !matches!(f, Value::Closure { .. }) {
2288 return Err(VmError::TypeMismatch(
2289 format!("ListMap requires a closure, got: {f:?}")));
2290 }
2291 let mut out: VecDeque<Value> = VecDeque::with_capacity(items.len());
2292 for item in items {
2293 out.push_back(self.invoke_closure_1(f.clone(), item)?);
2294 }
2295 self.stack.push(Value::List(out));
2296 }
2297 Op::ListFilter { node_id_idx: _ } => {
2298 // #464: native filter. Pred is applied to a clone
2299 // of each element; the original element is kept on
2300 // a true result.
2301 let f = self.pop()?;
2302 let xs = self.pop()?;
2303 let items = match xs {
2304 Value::List(v) => v,
2305 other => return Err(VmError::TypeMismatch(
2306 format!("ListFilter requires a List, got: {other:?}"))),
2307 };
2308 if !matches!(f, Value::Closure { .. }) {
2309 return Err(VmError::TypeMismatch(
2310 format!("ListFilter requires a closure, got: {f:?}")));
2311 }
2312 let mut out: VecDeque<Value> = VecDeque::new();
2313 for item in items {
2314 let keep = self.invoke_closure_1(f.clone(), item.clone())?;
2315 if keep.as_bool() {
2316 out.push_back(item);
2317 }
2318 }
2319 self.stack.push(Value::List(out));
2320 }
2321 Op::ListFold { node_id_idx: _ } => {
2322 // #464: native left-fold. `acc` is threaded by
2323 // value; each element is moved into the combiner.
2324 let f = self.pop()?;
2325 let init = self.pop()?;
2326 let xs = self.pop()?;
2327 let items = match xs {
2328 Value::List(v) => v,
2329 other => return Err(VmError::TypeMismatch(
2330 format!("ListFold requires a List, got: {other:?}"))),
2331 };
2332 if !matches!(f, Value::Closure { .. }) {
2333 return Err(VmError::TypeMismatch(
2334 format!("ListFold requires a closure, got: {f:?}")));
2335 }
2336 let mut acc = init;
2337 for item in items {
2338 acc = self.invoke_closure_2(f.clone(), acc, item)?;
2339 }
2340 self.stack.push(acc);
2341 }
2342 Op::Call { fn_id, arity, node_id_idx } => {
2343 let arity = arity as usize;
2344 let fid = fn_id as usize;
2345 // Args sit on the value stack at [args_base..]. We
2346 // read them in place for the refinement / memo /
2347 // trace checks and only move them into the locals
2348 // slot-allocator at the very end — avoiding a
2349 // per-call args Vec (#464 call-overhead). The stack
2350 // naturally holds the args until consumed, so the
2351 // only early-exit cleanup is truncating them off on
2352 // a memo hit; a refinement error aborts the VM.
2353 let args_base = self.stack.len() - arity;
2354 let node_id = const_str(&self.program.constants, node_id_idx);
2355 let budget_cost = call_budget_cost(&self.program.functions[fid]);
2356 if budget_cost > 0 {
2357 self.handler.note_call_budget(budget_cost)
2358 .map_err(VmError::Effect)?;
2359 }
2360 // Refinement runtime check (#209 slice 3). Each
2361 // param's `Option<Refinement>` is evaluated against
2362 // the actual arg before the frame is pushed. The
2363 // tracer sees the call enter; failure surfaces as
2364 // `VmError::RefinementFailed` *before* the body
2365 // starts, which means an erroring trace shows the
2366 // call as enter+exit_err with the verdict reason
2367 // (same shape as `gate.verdict`).
2368 //
2369 // Iterate by reference — the loop body reads only
2370 // through `r` (borrowed from `self.program`) and the
2371 // arg slots on the stack; we don't mutate `self`, so
2372 // the borrows are disjoint.
2373 let refinements = &self.program.functions[fid].refinements;
2374 for (i, refinement) in refinements.iter().enumerate() {
2375 if let Some(r) = refinement {
2376 let arg = self.stack[args_base + i].clone();
2377 match eval_refinement(&r.predicate, &r.binding, &arg) {
2378 Ok(true) => { /* satisfied, continue */ }
2379 Ok(false) => {
2380 return Err(VmError::RefinementFailed {
2381 fn_name: self.program.functions[fid].name.clone(),
2382 param_index: i,
2383 binding: r.binding.clone(),
2384 reason: format!(
2385 "predicate failed for {} = {arg:?}",
2386 r.binding),
2387 });
2388 }
2389 Err(reason) => {
2390 return Err(VmError::RefinementFailed {
2391 fn_name: self.program.functions[fid].name.clone(),
2392 param_index: i,
2393 binding: r.binding.clone(),
2394 reason,
2395 });
2396 }
2397 }
2398 }
2399 }
2400 // Pure-fn memoization (#229): if the callee declares
2401 // no effects, hash the args and consult the cache.
2402 // On hit, push the cached value, emit synthetic
2403 // enter+exit trace events (so the trace still shows
2404 // the call), and skip the frame push entirely.
2405 //
2406 // Adaptive gate (#229 adaptive): only hash if this
2407 // function still has memoization enabled. A pure
2408 // function whose args never repeat pays the hash for
2409 // nothing; after a warmup window with zero hits we
2410 // disable it and its calls take the plain path below.
2411 let memo_key: Option<(u32, [u8; 16])> =
2412 if self.program.functions[fid].effects.is_empty()
2413 && self.memo_fn_state[fid].enabled
2414 // #621: skip memo if any arg contains a request-scoped
2415 // arena handle. The memo cache outlives the request arena,
2416 // so hashing such a handle would dangle.
2417 && !self.stack[args_base..].iter().any(|v| v.contains_arena_record())
2418 {
2419 Some((fn_id, hash_call_args(&self.stack[args_base..])))
2420 } else {
2421 if self.program.functions[fid].effects.is_empty() {
2422 self.pure_memo_skips += 1;
2423 }
2424 None
2425 };
2426 if let Some(key) = memo_key {
2427 self.memo_fn_state[fid].calls += 1;
2428 if let Some(cached) = self.pure_memo.get(&key).cloned() {
2429 self.memo_fn_state[fid].hits += 1;
2430 self.pure_memo_hits += 1;
2431 self.tracer.enter_call(&node_id, &self.program.functions[fid].name, &self.stack[args_base..]);
2432 self.tracer.exit_ok(&cached);
2433 self.stack.truncate(args_base);
2434 self.stack.push(cached);
2435 continue;
2436 }
2437 self.pure_memo_misses += 1;
2438 // Disable on a cold function: warmup elapsed with
2439 // no hit. Always safe — the callee is pure, so the
2440 // plain path recomputes the identical result.
2441 let st = &mut self.memo_fn_state[fid];
2442 if st.calls >= MEMO_WARMUP_CALLS && st.hits == 0 {
2443 st.enabled = false;
2444 }
2445 }
2446 // #465 JIT tier hook. Consulted after refinements +
2447 // memo. The hook contract (see `crate::jit_hook`)
2448 // requires the dispatcher to emit the synthetic
2449 // tracer events itself — we do that on hit, then
2450 // truncate the args off the stack and push the
2451 // result, mirroring the memo-hit path above.
2452 //
2453 // Take/restore around the call so the hook can
2454 // borrow `&self.stack` for its args slice while
2455 // we hold `&mut hook`. Cheaper than cloning the
2456 // args; the take/put is two pointer writes.
2457 if let Some(mut hook) = self.jit_hook.take() {
2458 let hook_result = hook.try_call(fn_id, &self.stack[args_base..]);
2459 self.jit_hook = Some(hook);
2460 match hook_result? {
2461 Some(result) => {
2462 self.tracer.enter_call(&node_id, &self.program.functions[fid].name, &self.stack[args_base..]);
2463 self.tracer.exit_ok(&result);
2464 // Memoize the result if memo is enabled
2465 // for this fn — same semantics as a
2466 // regular call's Return path.
2467 if let Some(key) = memo_key {
2468 self.pure_memo.insert(key, result.clone());
2469 }
2470 self.stack.truncate(args_base);
2471 self.stack.push(result);
2472 continue;
2473 }
2474 None => { /* hook declined; fall through */ }
2475 }
2476 }
2477 self.tracer.enter_call(&node_id, &self.program.functions[fid].name, &self.stack[args_base..]);
2478 let locals_len = self.program.functions[fid].locals_count
2479 .max(self.program.functions[fid].arity) as usize;
2480 let locals_start = self.locals_storage.len();
2481 self.locals_storage.resize(locals_start + locals_len, Value::Unit);
2482 // Move the args off the stack into the callee's
2483 // locals (popping leaves the stack at `args_base`).
2484 for i in (0..arity).rev() {
2485 self.locals_storage[locals_start + i] = self.pop()?;
2486 }
2487 self.push_frame(Frame {
2488 fn_id, pc: 0, locals_start, locals_len,
2489 stack_base: self.stack.len(),
2490 trace_kind: FrameKind::Call(node_id),
2491 memo_key,
2492 stack_record_arena_start: self.stack_record_arena.len(),
2493 stack_record_budget_remaining: STACK_RECORD_BUDGET_SLOTS,
2494 })?;
2495 }
2496 Op::TailCall { fn_id, arity, node_id_idx } => {
2497 let arity = arity as usize;
2498 let fid = fn_id as usize;
2499 // Args sit on the value stack at [args_base..]. Read
2500 // them in place for the refinement / trace checks and
2501 // move them into the reused frame's locals at the end
2502 // — no per-call args Vec (#464). Tail calls have no
2503 // memoization, so the consumers are refinement, trace,
2504 // then the locals move. The args live on `self.stack`
2505 // while locals live on `self.locals_storage`, so the
2506 // `truncate(old_locals_start)` below (which releases
2507 // the *old* frame's locals) doesn't touch them.
2508 let args_base = self.stack.len() - arity;
2509 let node_id = const_str(&self.program.constants, node_id_idx);
2510 let budget_cost = call_budget_cost(&self.program.functions[fid]);
2511 if budget_cost > 0 {
2512 self.handler.note_call_budget(budget_cost)
2513 .map_err(VmError::Effect)?;
2514 }
2515 // Refinement runtime check on tail calls too
2516 // (#209 slice 3). Same shape as Op::Call.
2517 let refinements = &self.program.functions[fid].refinements;
2518 for (i, refinement) in refinements.iter().enumerate() {
2519 if let Some(r) = refinement {
2520 let arg = self.stack[args_base + i].clone();
2521 match eval_refinement(&r.predicate, &r.binding, &arg) {
2522 Ok(true) => {}
2523 Ok(false) => return Err(VmError::RefinementFailed {
2524 fn_name: self.program.functions[fid].name.clone(),
2525 param_index: i,
2526 binding: r.binding.clone(),
2527 reason: format!(
2528 "predicate failed for {} = {arg:?}",
2529 r.binding),
2530 }),
2531 Err(reason) => return Err(VmError::RefinementFailed {
2532 fn_name: self.program.functions[fid].name.clone(),
2533 param_index: i,
2534 binding: r.binding.clone(),
2535 reason,
2536 }),
2537 }
2538 }
2539 }
2540 // #465 JIT tier hook for tail calls. A tail-called
2541 // function's result IS the current frame's result,
2542 // so on a hook hit we collapse the current frame:
2543 // truncate state back to the frame's entry, emit
2544 // the synthetic enter+exit_ok trace events that a
2545 // normal tail-into-return would have produced, then
2546 // bubble the result up the same way Op::Return
2547 // does.
2548 if let Some(mut hook) = self.jit_hook.take() {
2549 let hook_result = hook.try_call(fn_id, &self.stack[args_base..]);
2550 self.jit_hook = Some(hook);
2551 if let Some(result) = hook_result? {
2552 self.tracer.exit_call_tail();
2553 self.tracer.enter_call(&node_id, &self.program.functions[fid].name, &self.stack[args_base..]);
2554 self.tracer.exit_ok(&result);
2555 let frame = self.frames.pop().unwrap();
2556 self.stack.truncate(frame.stack_base);
2557 self.locals_storage.truncate(frame.locals_start);
2558 self.stack_record_arena.truncate(frame.stack_record_arena_start);
2559 // Tail calls don't carry a memo_key (the
2560 // existing arm doesn't memoize them), so
2561 // skip the memo store the Return path does.
2562 if self.frames.len() <= base_depth {
2563 return Ok(result);
2564 }
2565 self.stack.push(result);
2566 continue;
2567 }
2568 }
2569 // A tail call closes the current call's trace frame and
2570 // opens a new one in its place — preserves the caller's
2571 // tree depth in the trace.
2572 self.tracer.exit_call_tail();
2573 self.tracer.enter_call(&node_id, &self.program.functions[fid].name, &self.stack[args_base..]);
2574 // Reuse the current frame's locals_start position:
2575 // truncate to release old locals then extend for the
2576 // new function (#389 slice 3, same as Op::Return but
2577 // without popping the frame).
2578 let old_locals_start = self.frames.last().unwrap().locals_start;
2579 self.locals_storage.truncate(old_locals_start);
2580 let new_locals_len = self.program.functions[fid].locals_count
2581 .max(self.program.functions[fid].arity) as usize;
2582 self.locals_storage.resize(old_locals_start + new_locals_len, Value::Unit);
2583 // Move the args off the value stack into the callee's
2584 // locals (popping leaves the stack at `args_base`).
2585 for i in (0..arity).rev() {
2586 self.locals_storage[old_locals_start + i] = self.pop()?;
2587 }
2588 // #464 step 2: a tail-called function gets a fresh
2589 // stack-record arena view. Release any records the
2590 // pre-tail-call code allocated (they can't be live
2591 // — the args have already been popped off the
2592 // value stack) and refill the budget for the
2593 // callee.
2594 let arena_start = self.frames.last().unwrap().stack_record_arena_start;
2595 self.stack_record_arena.truncate(arena_start);
2596 let frame = self.frames.last_mut().unwrap();
2597 frame.fn_id = fn_id;
2598 frame.pc = 0;
2599 frame.locals_len = new_locals_len;
2600 frame.trace_kind = FrameKind::Call(node_id);
2601 frame.stack_record_budget_remaining = STACK_RECORD_BUDGET_SLOTS;
2602 }
2603 Op::EffectCall { kind_idx, op_idx, arity, node_id_idx } => {
2604 let mut args: Vec<Value> = (0..arity).map(|_| Value::Unit).collect();
2605 for i in (0..arity as usize).rev() { args[i] = self.pop()?; }
2606 let kind = match &self.program.constants[kind_idx as usize] {
2607 Const::Str(s) => s.clone(),
2608 _ => return Err(VmError::TypeMismatch("expected Str const for effect kind".into())),
2609 };
2610 let op_name = match &self.program.constants[op_idx as usize] {
2611 Const::Str(s) => s.clone(),
2612 _ => return Err(VmError::TypeMismatch("expected Str const for effect op".into())),
2613 };
2614 let node_id = const_str(&self.program.constants, node_id_idx);
2615 self.tracer.enter_effect(&node_id, &kind, &op_name, &args);
2616 let result = match self.tracer.override_effect(&node_id) {
2617 Some(v) => Ok(v),
2618 // VM-level intercept for `parser.run` (#221).
2619 // Routed inline rather than through the handler
2620 // because the parser interpreter needs reentrant
2621 // VM access to invoke `Value::Closure` values
2622 // from `Map` / `AndThen` nodes.
2623 None if (kind.as_str(), op_name.as_str()) == ("parser", "run")
2624 => self.run_parser_op(args),
2625 // VM-level intercept for `conc.*` (#381). The actor
2626 // handler closure must run on the calling VM so it can
2627 // dispatch arbitrary effects through the same handler
2628 // chain (e.g. sql queries inside an actor).
2629 None if kind.as_str() == "conc"
2630 => self.run_conc_op(op_name.as_str(), args),
2631 None => self.handler.dispatch(&kind, &op_name, args),
2632 };
2633 match result {
2634 Ok(v) => {
2635 self.tracer.exit_ok(&v);
2636 self.stack.push(v);
2637 }
2638 Err(e) => {
2639 self.tracer.exit_err(&e);
2640 return Err(VmError::Effect(e));
2641 }
2642 }
2643 }
2644 Op::Return => {
2645 let v = self.pop()?;
2646 let frame = self.frames.pop().unwrap();
2647 // Trim any extra stuff that the function pushed but didn't pop.
2648 self.stack.truncate(frame.stack_base);
2649 // Release this frame's locals back to the arena (#389 slice 3).
2650 // LIFO frame ordering guarantees this frame's slots are at the top.
2651 self.locals_storage.truncate(frame.locals_start);
2652 // #464 step 2: release this frame's stack-record
2653 // slab. LIFO frame discipline guarantees its
2654 // records sit at the top of the arena. The
2655 // returned value `v` is escape-proven not to be
2656 // one of them — the compiler only emits
2657 // AllocStackRecord at sites that don't reach
2658 // `Return`.
2659 self.stack_record_arena.truncate(frame.stack_record_arena_start);
2660 if matches!(frame.trace_kind, FrameKind::Call(_)) {
2661 self.tracer.exit_ok(&v);
2662 }
2663 // Pure-fn memoization (#229): if this frame was a
2664 // memoizable call that missed the cache, write the
2665 // computed return value back so the next call with
2666 // the same args returns it without re-executing.
2667 if let Some(key) = frame.memo_key {
2668 self.pure_memo.insert(key, v.clone());
2669 }
2670 // Exit when we've returned past the depth this
2671 // `run_to` was entered at — supports reentrancy
2672 // (a nested `invoke` returns into its caller, not
2673 // out of the outermost VM run, #221).
2674 if self.frames.len() <= base_depth {
2675 return Ok(v);
2676 }
2677 self.stack.push(v);
2678 }
2679 Op::Panic(i) => {
2680 let msg = match &self.program.constants[i as usize] {
2681 Const::Str(s) => s.clone(),
2682 _ => "panic".into(),
2683 };
2684 return Err(VmError::Panic(msg));
2685 }
2686 // Arithmetic
2687 Op::IntAdd => self.bin_int(|a, b| Value::Int(a + b))?,
2688 Op::IntSub => self.bin_int(|a, b| Value::Int(a - b))?,
2689 Op::IntMul => self.bin_int(|a, b| Value::Int(a * b))?,
2690 Op::IntDiv => self.bin_int_divmod(false)?,
2691 Op::IntMod => self.bin_int_divmod(true)?,
2692 Op::IntNeg => {
2693 let a = self.pop()?.as_int();
2694 self.stack.push(Value::Int(-a));
2695 }
2696 Op::IntEq => self.bin_int(|a, b| Value::Bool(a == b))?,
2697 Op::IntLt => self.bin_int(|a, b| Value::Bool(a < b))?,
2698 Op::IntLe => self.bin_int(|a, b| Value::Bool(a <= b))?,
2699 Op::FloatAdd => self.bin_float(|a, b| Value::Float(a + b))?,
2700 Op::FloatSub => self.bin_float(|a, b| Value::Float(a - b))?,
2701 Op::FloatMul => self.bin_float(|a, b| Value::Float(a * b))?,
2702 Op::FloatDiv => self.bin_float(|a, b| Value::Float(a / b))?,
2703 Op::FloatNeg => {
2704 let a = self.pop()?.as_float();
2705 self.stack.push(Value::Float(-a));
2706 }
2707 Op::FloatEq => self.bin_float(|a, b| Value::Bool(a == b))?,
2708 Op::FloatLt => self.bin_float(|a, b| Value::Bool(a < b))?,
2709 Op::FloatLe => self.bin_float(|a, b| Value::Bool(a <= b))?,
2710 Op::NumAdd => {
2711 // #308: `+` is overloaded — Str+Str concatenates,
2712 // numerics add. Other arithmetic ops (-, *, /, %)
2713 // still reject Str at the type-checker layer.
2714 let b = self.pop()?;
2715 let a = self.pop()?;
2716 match (a, b) {
2717 (Value::Int(x), Value::Int(y)) => self.stack.push(Value::Int(x + y)),
2718 (Value::Float(x), Value::Float(y)) => self.stack.push(Value::Float(x + y)),
2719 (Value::Str(x), Value::Str(y)) => {
2720 // SmolStr is immutable; concatenate via a temporary String.
2721 let mut s = String::with_capacity(x.len() + y.len());
2722 s.push_str(&x);
2723 s.push_str(&y);
2724 self.stack.push(Value::Str(s.into()));
2725 }
2726 (a, b) => return Err(VmError::TypeMismatch(format!("Num op: {a:?} {b:?}"))),
2727 }
2728 }
2729 Op::NumSub => self.bin_num(|a, b| Value::Int(a - b), |a, b| Value::Float(a - b))?,
2730 Op::NumMul => self.bin_num(|a, b| Value::Int(a * b), |a, b| Value::Float(a * b))?,
2731 Op::NumDiv => self.num_divmod(false)?,
2732 Op::NumMod => self.num_divmod(true)?,
2733 Op::NumNeg => {
2734 let v = self.pop()?;
2735 match v {
2736 Value::Int(n) => self.stack.push(Value::Int(-n)),
2737 Value::Float(f) => self.stack.push(Value::Float(-f)),
2738 other => return Err(VmError::TypeMismatch(format!("NumNeg on {other:?}"))),
2739 }
2740 }
2741 Op::NumEq => self.bin_eq()?,
2742 Op::NumLt => self.bin_ord(|a, b| Value::Bool(a < b), |a, b| Value::Bool(a < b), |a, b| Value::Bool(a < b))?,
2743 Op::NumLe => self.bin_ord(|a, b| Value::Bool(a <= b), |a, b| Value::Bool(a <= b), |a, b| Value::Bool(a <= b))?,
2744 Op::BoolAnd => {
2745 let b = self.pop()?.as_bool();
2746 let a = self.pop()?.as_bool();
2747 self.stack.push(Value::Bool(a && b));
2748 }
2749 Op::BoolOr => {
2750 let b = self.pop()?.as_bool();
2751 let a = self.pop()?.as_bool();
2752 self.stack.push(Value::Bool(a || b));
2753 }
2754 Op::BoolNot => {
2755 let a = self.pop()?.as_bool();
2756 self.stack.push(Value::Bool(!a));
2757 }
2758 Op::StrConcat => {
2759 let b = self.pop()?;
2760 let a = self.pop()?;
2761 let s = format!("{}{}", a.as_str(), b.as_str());
2762 self.stack.push(Value::Str(s.into()));
2763 }
2764 Op::StrLen => {
2765 let v = self.pop()?;
2766 self.stack.push(Value::Int(v.as_str().len() as i64));
2767 }
2768 Op::StrEq => {
2769 let b = self.pop()?;
2770 let a = self.pop()?;
2771 self.stack.push(Value::Bool(a.as_str() == b.as_str()));
2772 }
2773 Op::BytesLen => {
2774 let v = self.pop()?;
2775 match v {
2776 Value::Bytes(b) => self.stack.push(Value::Int(b.len() as i64)),
2777 other => return Err(VmError::TypeMismatch(format!("BytesLen on {other:?}"))),
2778 }
2779 }
2780 Op::BytesEq => {
2781 let b = self.pop()?;
2782 let a = self.pop()?;
2783 let eq = match (a, b) {
2784 (Value::Bytes(x), Value::Bytes(y)) => x == y,
2785 _ => return Err(VmError::TypeMismatch("BytesEq operands".into())),
2786 };
2787 self.stack.push(Value::Bool(eq));
2788 }
2789
2790 // Superinstructions (#461).
2791 Op::LoadLocalAddIntConst { local_idx, imm_const_idx } => {
2792 let base = self.frames[frame_idx].locals_start;
2793 let a = self.locals_storage[base + local_idx as usize].as_int();
2794 let b = match &self.program.constants[imm_const_idx as usize] {
2795 Const::Int(n) => *n,
2796 c => return Err(VmError::TypeMismatch(
2797 format!("LoadLocalAddIntConst expected Int const, got {c:?}"))),
2798 };
2799 self.stack.push(Value::Int(a + b));
2800 // Override the default `pc + 1`: skip past the
2801 // two inert primitive ops (the original
2802 // PushConst + IntAdd) that the peephole pass
2803 // left in place for body-hash stability.
2804 self.frames[frame_idx].pc = pc + 3;
2805 }
2806 Op::LoadLocalAddLocal { lhs_idx, rhs_idx } => {
2807 let base = self.frames[frame_idx].locals_start;
2808 let a = self.locals_storage[base + lhs_idx as usize].as_int();
2809 let b = self.locals_storage[base + rhs_idx as usize].as_int();
2810 self.stack.push(Value::Int(a + b));
2811 // Override the default `pc + 1`: skip past the
2812 // two inert primitive ops (the original
2813 // LoadLocal(rhs_idx) + IntAdd) that the peephole
2814 // pass left in place for body-hash stability.
2815 self.frames[frame_idx].pc = pc + 3;
2816 }
2817 Op::LoadLocalSubLocal { lhs_idx, rhs_idx } => {
2818 let base = self.frames[frame_idx].locals_start;
2819 let a = self.locals_storage[base + lhs_idx as usize].as_int();
2820 let b = self.locals_storage[base + rhs_idx as usize].as_int();
2821 self.stack.push(Value::Int(a - b));
2822 self.frames[frame_idx].pc = pc + 3;
2823 }
2824 Op::LoadLocalMulLocal { lhs_idx, rhs_idx } => {
2825 let base = self.frames[frame_idx].locals_start;
2826 let a = self.locals_storage[base + lhs_idx as usize].as_int();
2827 let b = self.locals_storage[base + rhs_idx as usize].as_int();
2828 self.stack.push(Value::Int(a * b));
2829 self.frames[frame_idx].pc = pc + 3;
2830 }
2831 Op::LoadLocalGetField { local_idx, name_idx, site_idx } => {
2832 // #461 slice 9: fused `LoadLocal + GetField`. Reads
2833 // the field directly out of the local record by
2834 // reference and pushes it, advancing pc by 2 (one
2835 // tombstone — the original GetField). Avoids the
2836 // unfused pair's whole-record clone onto the value
2837 // stack: the dominant heap-record churn on the
2838 // `response_build` profile (`r.total` field reads).
2839 let base = self.frames[frame_idx].locals_start;
2840 let v = self.read_local_record_field(
2841 base, local_idx, fn_id, name_idx, site_idx, "LoadLocalGetField")?;
2842 self.stack.push(v);
2843 self.frames[frame_idx].pc = pc + 2;
2844 }
2845 Op::LoadLocalGetFieldAdd { local_idx, name_idx, site_idx } => {
2846 // #461 slice 7: fused `LoadLocal + GetField + IntAdd`.
2847 // Pop the prior stack top (the accumulator), read the
2848 // field by reference (shared IC via
2849 // `read_local_record_field`), push the sum, advance
2850 // pc by 3 (skip the GetField and IntAdd tombstones).
2851 let acc = self.pop()?.as_int();
2852 let base = self.frames[frame_idx].locals_start;
2853 let b = self.read_local_record_field(
2854 base, local_idx, fn_id, name_idx, site_idx, "LoadLocalGetFieldAdd")?.as_int();
2855 self.stack.push(Value::Int(acc + b));
2856 self.frames[frame_idx].pc = pc + 3;
2857 }
2858 Op::LoadLocalGetFieldSub { local_idx, name_idx, site_idx } => {
2859 // #461 slice 8: `LoadLocal + GetField + IntSub`. The
2860 // `acc - r.field` idiom. IntSub computes
2861 // deeper-minus-top; the field was on top in the
2862 // unfused form, so the result is `acc - field`.
2863 let acc = self.pop()?.as_int();
2864 let base = self.frames[frame_idx].locals_start;
2865 let b = self.read_local_record_field(
2866 base, local_idx, fn_id, name_idx, site_idx, "LoadLocalGetFieldSub")?.as_int();
2867 self.stack.push(Value::Int(acc - b));
2868 self.frames[frame_idx].pc = pc + 3;
2869 }
2870 Op::LoadLocalGetFieldMul { local_idx, name_idx, site_idx } => {
2871 // #461 slice 8: `LoadLocal + GetField + IntMul`. The
2872 // `acc * r.field` idiom (mul is commutative, so
2873 // operand order doesn't matter).
2874 let acc = self.pop()?.as_int();
2875 let base = self.frames[frame_idx].locals_start;
2876 let b = self.read_local_record_field(
2877 base, local_idx, fn_id, name_idx, site_idx, "LoadLocalGetFieldMul")?.as_int();
2878 self.stack.push(Value::Int(acc * b));
2879 self.frames[frame_idx].pc = pc + 3;
2880 }
2881 Op::LoadLocalEqIntConstJumpIfNot { local_idx, imm_const_idx, jump_offset } => {
2882 // First jump-aware fusion (#461 slice 5). The
2883 // JumpIfNot's offset is relative to its own
2884 // pc + 1 = (pc + 3) + 1 = pc + 4, so the branch
2885 // target is `pc + 4 + jump_offset`. Fall-through
2886 // (equal → JumpIfNot doesn't jump) is `pc + 4`
2887 // (skip past the 3 tombstones — PushConst +
2888 // IntEq + JumpIfNot).
2889 let base = self.frames[frame_idx].locals_start;
2890 let a = self.locals_storage[base + local_idx as usize].as_int();
2891 let b = match &self.program.constants[imm_const_idx as usize] {
2892 Const::Int(n) => *n,
2893 _ => return Err(VmError::TypeMismatch(
2894 "LoadLocalEqIntConstJumpIfNot expects Const::Int".into())),
2895 };
2896 let next_pc = if a == b {
2897 pc + 4
2898 } else {
2899 ((pc as i32 + 4) + jump_offset) as usize
2900 };
2901 self.frames[frame_idx].pc = next_pc;
2902 }
2903 Op::LoadLocalStoreEqIntConstJumpIfNot { src, dst, imm_const_idx, jump_offset } => {
2904 // Slice 6: absorbs LoadLocal + StoreLocal + slice-5 op.
2905 // 6-slot window total (this op + 5 tombstones); fall-
2906 // through is `pc + 6`, branch target is `pc + 6 +
2907 // jump_offset` (the original JumpIfNot was at slot
2908 // pc+5, with offset relative to its own pc+1 = pc+6).
2909 let base = self.frames[frame_idx].locals_start;
2910 let a = self.locals_storage[base + src as usize].as_int();
2911 // Mirror the original `StoreLocal(dst)` — later
2912 // arm tests in the same `match` expect to find
2913 // the scrutinee at `locals[dst]`.
2914 self.locals_storage[base + dst as usize] = Value::Int(a);
2915 let b = match &self.program.constants[imm_const_idx as usize] {
2916 Const::Int(n) => *n,
2917 _ => return Err(VmError::TypeMismatch(
2918 "LoadLocalStoreEqIntConstJumpIfNot expects Const::Int".into())),
2919 };
2920 let next_pc = if a == b {
2921 pc + 6
2922 } else {
2923 ((pc as i32 + 6) + jump_offset) as usize
2924 };
2925 self.frames[frame_idx].pc = next_pc;
2926 }
2927 Op::LoadLocalAddIntConstStoreLocal { src, imm_const_idx, dest } => {
2928 let base = self.frames[frame_idx].locals_start;
2929 let a = self.locals_storage[base + src as usize].as_int();
2930 let b = match &self.program.constants[imm_const_idx as usize] {
2931 Const::Int(n) => *n,
2932 c => return Err(VmError::TypeMismatch(
2933 format!("LoadLocalAddIntConstStoreLocal expected Int const, got {c:?}"))),
2934 };
2935 self.locals_storage[base + dest as usize] = Value::Int(a + b);
2936 // Skip past the 3 inert primitive ops we
2937 // absorbed (original PushConst + IntAdd +
2938 // StoreLocal).
2939 self.frames[frame_idx].pc = pc + 4;
2940 }
2941 }
2942 }
2943 }
2944
2945 fn pop(&mut self) -> Result<Value, VmError> {
2946 self.stack.pop().ok_or(VmError::StackUnderflow)
2947 }
2948 fn peek(&self) -> Result<&Value, VmError> {
2949 self.stack.last().ok_or(VmError::StackUnderflow)
2950 }
2951
2952 /// IC-cached field read of `locals[local_idx]`, shared by the
2953 /// field-read fusions: slice 9's `LoadLocalGetField` and slice
2954 /// 7/8's `LoadLocalGetField{Add,Sub,Mul}`. Uses the same
2955 /// `(fn_id, site_idx)` inline-cache slot as the unfused
2956 /// `Op::GetField`, so the paths stay cache-consistent.
2957 /// `op_name` only appears in the non-record error message.
2958 ///
2959 /// Reads the record **by reference** and clones out only the
2960 /// selected field — it does *not* clone the whole record. The
2961 /// unfused `[LoadLocal, GetField]` pair clones the entire record
2962 /// (`Box<IndexMap>` for a heap record) onto the value stack just
2963 /// to read one field and drop the rest; on the `response_build`
2964 /// profile that whole-record clone+drop of the returned `Response`
2965 /// dominated the malloc traffic. Borrowing in place removes it.
2966 ///
2967 /// Borrow discipline: the inline-cache slot can't be written while
2968 /// the record (a borrow of `self.locals_storage`) is live, so the
2969 /// match yields `(value, install)` and the `field_ics` write
2970 /// happens after the borrow ends.
2971 ///
2972 /// `#[inline(always)]`: hot dispatch path, called from four tight
2973 /// `run_to` arms; leaving it out-of-line showed up as a standalone
2974 /// call frame on the profile.
2975 #[inline(always)]
2976 fn read_local_record_field(
2977 &mut self,
2978 base: usize,
2979 local_idx: u16,
2980 fn_id: u32,
2981 name_idx: u32,
2982 site_idx: u32,
2983 op_name: &str,
2984 ) -> Result<Value, VmError> {
2985 let fid = fn_id as usize;
2986 let sid = site_idx as usize;
2987 if self.field_ics[fid].is_empty() {
2988 let n = self.program.functions[fid].field_ic_sites as usize;
2989 self.field_ics[fid] = vec![None; n];
2990 }
2991 let cached = self.field_ics[fid][sid];
2992 let li = base + local_idx as usize;
2993
2994 let (value, install): (Value, Option<(u32, usize)>) =
2995 match &self.locals_storage[li] {
2996 Value::Record { fields: r, shape_id } => {
2997 let shape_id = *shape_id;
2998 if ic_stats_enabled() {
2999 record_ic_hit(fn_id, site_idx, shape_id);
3000 }
3001 let hit = if let Some((cached_shape, off)) = cached {
3002 if cached_shape == shape_id {
3003 if shape_id != crate::value::NO_SHAPE_ID {
3004 r.get_index(off).map(|(_, val)| val.clone())
3005 } else if let Some((k, val)) = r.get_index(off) {
3006 match &self.program.constants[name_idx as usize] {
3007 Const::FieldName(s) if s == k => Some(val.clone()),
3008 _ => None,
3009 }
3010 } else { None }
3011 } else { None }
3012 } else { None };
3013 match hit {
3014 Some(v) => (v, None),
3015 None => {
3016 let name = match &self.program.constants[name_idx as usize] {
3017 Const::FieldName(s) => s.as_str(),
3018 _ => return Err(VmError::TypeMismatch(
3019 "expected FieldName const".into())),
3020 };
3021 let (off, _, val) = r.get_full(name)
3022 .ok_or_else(|| VmError::TypeMismatch(
3023 format!("missing field `{name}`")))?;
3024 (val.clone(), Some((shape_id, off)))
3025 }
3026 }
3027 }
3028 &Value::StackRecord { shape_id, slab_start, field_count } => {
3029 if ic_stats_enabled() {
3030 record_ic_hit(fn_id, site_idx, shape_id);
3031 }
3032 if let Some((cached_shape, off)) = cached {
3033 if cached_shape == shape_id && (off as u16) < field_count {
3034 let idx = slab_start as usize + off;
3035 (self.stack_record_arena[idx].clone(), None)
3036 } else {
3037 let off = self.resolve_stack_field(shape_id, name_idx)?;
3038 (self.stack_record_arena[slab_start as usize + off].clone(),
3039 Some((shape_id, off)))
3040 }
3041 } else {
3042 let off = self.resolve_stack_field(shape_id, name_idx)?;
3043 (self.stack_record_arena[slab_start as usize + off].clone(),
3044 Some((shape_id, off)))
3045 }
3046 }
3047 // #463 slice 2a: superinstruction read out of an
3048 // arena-allocated record held in a local. Same shape
3049 // resolution as the stack-record arm (records share
3050 // the same `record_shapes` table regardless of
3051 // allocation site); only the slab indexed differs.
3052 &Value::ArenaRecord { shape_id, slab_start, field_count } => {
3053 if ic_stats_enabled() {
3054 record_ic_hit(fn_id, site_idx, shape_id);
3055 }
3056 if let Some((cached_shape, off)) = cached {
3057 if cached_shape == shape_id && (off as u16) < field_count {
3058 let idx = slab_start as usize + off;
3059 (self.arena_slab[idx].clone(), None)
3060 } else {
3061 let off = self.resolve_stack_field(shape_id, name_idx)?;
3062 (self.arena_slab[slab_start as usize + off].clone(),
3063 Some((shape_id, off)))
3064 }
3065 } else {
3066 let off = self.resolve_stack_field(shape_id, name_idx)?;
3067 (self.arena_slab[slab_start as usize + off].clone(),
3068 Some((shape_id, off)))
3069 }
3070 }
3071 other => return Err(VmError::TypeMismatch(
3072 format!("{op_name} on non-record: {other:?}"))),
3073 };
3074 if let Some(entry) = install {
3075 self.field_ics[fid][sid] = Some(entry);
3076 }
3077 Ok(value)
3078 }
3079
3080 /// Resolve a field offset within a stack-record shape by name
3081 /// (the slow path when the inline cache misses). Factored out so
3082 /// `read_local_record_field` doesn't hold the `locals_storage`
3083 /// borrow across the `record_shapes` / `constants` walk.
3084 #[inline]
3085 fn resolve_stack_field(&self, shape_id: u32, name_idx: u32) -> Result<usize, VmError> {
3086 let shape = &self.program.record_shapes[shape_id as usize];
3087 let target_name = match &self.program.constants[name_idx as usize] {
3088 Const::FieldName(s) => s.as_str(),
3089 _ => return Err(VmError::TypeMismatch("expected FieldName const".into())),
3090 };
3091 for (i, fn_const_idx) in shape.iter().enumerate() {
3092 if let Const::FieldName(s) = &self.program.constants[*fn_const_idx as usize] {
3093 if s == target_name { return Ok(i); }
3094 }
3095 }
3096 Err(VmError::TypeMismatch(
3097 format!("missing field `{target_name}` on stack record")))
3098 }
3099
3100 fn bin_int(&mut self, f: impl Fn(i64, i64) -> Value) -> Result<(), VmError> {
3101 let b = self.pop()?.as_int();
3102 let a = self.pop()?.as_int();
3103 self.stack.push(f(a, b));
3104 Ok(())
3105 }
3106 /// Guarded integer `/` (`is_mod == false`) or `%` (`is_mod == true`)
3107 /// for `Op::IntDiv` / `Op::IntMod` (#696). A zero divisor raises
3108 /// `VmError::DivByZero` instead of panicking the host. `wrapping_*`
3109 /// also tames the only other panicking input, `i64::MIN / -1` (and
3110 /// `i64::MIN % -1`), whose true result overflows `i64`: division
3111 /// wraps to `i64::MIN`, modulo to `0`.
3112 fn bin_int_divmod(&mut self, is_mod: bool) -> Result<(), VmError> {
3113 let b = self.pop()?.as_int();
3114 let a = self.pop()?.as_int();
3115 if b == 0 {
3116 return Err(VmError::DivByZero { op: if is_mod { "modulo" } else { "division" } });
3117 }
3118 let v = if is_mod { a.wrapping_rem(b) } else { a.wrapping_div(b) };
3119 self.stack.push(Value::Int(v));
3120 Ok(())
3121 }
3122 /// Guarded `/` / `%` for the overloaded `Op::NumDiv` / `Op::NumMod`,
3123 /// which accept either both-`Int` or both-`Float` operands (#696).
3124 /// Integers route through the same zero/overflow guards as
3125 /// `bin_int_divmod`; floats keep IEEE-754 semantics (inf/NaN, no
3126 /// trap). Mirrors the type checker, which only admits these two
3127 /// operand shapes for `%` (int) and `/` (int or float).
3128 fn num_divmod(&mut self, is_mod: bool) -> Result<(), VmError> {
3129 let b = self.pop()?;
3130 let a = self.pop()?;
3131 match (a, b) {
3132 (Value::Int(x), Value::Int(y)) => {
3133 if y == 0 {
3134 return Err(VmError::DivByZero { op: if is_mod { "modulo" } else { "division" } });
3135 }
3136 let v = if is_mod { x.wrapping_rem(y) } else { x.wrapping_div(y) };
3137 self.stack.push(Value::Int(v));
3138 Ok(())
3139 }
3140 (Value::Float(x), Value::Float(y)) => {
3141 self.stack.push(Value::Float(if is_mod { x % y } else { x / y }));
3142 Ok(())
3143 }
3144 (a, b) => Err(VmError::TypeMismatch(format!("Num op: {a:?} {b:?}"))),
3145 }
3146 }
3147 fn bin_float(&mut self, f: impl Fn(f64, f64) -> Value) -> Result<(), VmError> {
3148 let b = self.pop()?.as_float();
3149 let a = self.pop()?.as_float();
3150 self.stack.push(f(a, b));
3151 Ok(())
3152 }
3153 fn bin_num(
3154 &mut self,
3155 i: impl Fn(i64, i64) -> Value,
3156 f: impl Fn(f64, f64) -> Value,
3157 ) -> Result<(), VmError> {
3158 let b = self.pop()?;
3159 let a = self.pop()?;
3160 match (a, b) {
3161 (Value::Int(x), Value::Int(y)) => { self.stack.push(i(x, y)); Ok(()) }
3162 (Value::Float(x), Value::Float(y)) => { self.stack.push(f(x, y)); Ok(()) }
3163 (a, b) => Err(VmError::TypeMismatch(format!("Num op: {a:?} {b:?}"))),
3164 }
3165 }
3166
3167 /// Like `bin_num` but also handles `Str` operands via lexicographic order.
3168 /// Used by `NumLt` / `NumLe` because the type checker admits `Str < Str`
3169 /// and `>` / `>=` compile as swap+NumLt / swap+NumLe (#332).
3170 fn bin_ord(
3171 &mut self,
3172 i: impl Fn(i64, i64) -> Value,
3173 f: impl Fn(f64, f64) -> Value,
3174 s: impl Fn(&str, &str) -> Value,
3175 ) -> Result<(), VmError> {
3176 let b = self.pop()?;
3177 let a = self.pop()?;
3178 match (a, b) {
3179 (Value::Int(x), Value::Int(y)) => { self.stack.push(i(x, y)); Ok(()) }
3180 (Value::Float(x), Value::Float(y)) => { self.stack.push(f(x, y)); Ok(()) }
3181 (Value::Str(x), Value::Str(y)) => { self.stack.push(s(&x, &y)); Ok(()) }
3182 (a, b) => Err(VmError::TypeMismatch(format!("Num op: {a:?} {b:?}"))),
3183 }
3184 }
3185 fn bin_eq(&mut self) -> Result<(), VmError> {
3186 let b = self.pop()?;
3187 let a = self.pop()?;
3188 self.stack.push(Value::Bool(a == b));
3189 Ok(())
3190 }
3191}
3192
3193impl Drop for Vm<'_> {
3194 fn drop(&mut self) {
3195 if ic_stats_enabled() {
3196 dump_ic_stats();
3197 }
3198 }
3199}
3200
3201/// Construct a `Value::Variant` with the given name and args.
3202/// Used by `conc.*` registry ops to return `Result`/`Option`/`ConcError`
3203/// values without hand-writing the struct literal at every site.
3204fn variant(name: &str, args: Vec<Value>) -> Value {
3205 Value::Variant { name: name.to_string(), args }
3206}
3207fn variant_ok(payload: Value) -> Value { variant("Ok", vec![payload]) }
3208fn variant_err(payload: Value) -> Value { variant("Err", vec![payload]) }
3209
3210fn const_to_value(c: &Const) -> Value {
3211 match c {
3212 Const::Int(n) => Value::Int(*n),
3213 Const::Float(f) => Value::Float(*f),
3214 Const::Bool(b) => Value::Bool(*b),
3215 Const::Str(s) => Value::Str(s.as_str().into()),
3216 Const::Bytes(b) => Value::Bytes(b.clone()),
3217 Const::Unit => Value::Unit,
3218 Const::FieldName(s) | Const::VariantName(s) | Const::NodeId(s) => Value::Str(s.as_str().into()),
3219 }
3220}
3221
3222#[cfg(test)]
3223mod memo_hash_tests {
3224 //! #461 follow-up: invariants for the structural memo-key hash
3225 //! that replaced the SHA-256-over-canonical-JSON path. The memo
3226 //! cache keys on this digest with no equality fallback, so the
3227 //! load-bearing property is "equal-under-PartialEq args produce
3228 //! an equal key" — plus enough discrimination that distinct args
3229 //! don't collide in practice.
3230 use super::*;
3231 use indexmap::IndexMap;
3232
3233 fn rec(pairs: &[(&str, Value)]) -> Value {
3234 let mut m: IndexMap<SmolStr, Value> = IndexMap::new();
3235 for (k, v) in pairs { m.insert((*k).into(), v.clone()); }
3236 Value::Record { shape_id: crate::value::NO_SHAPE_ID, fields: Box::new(m) }
3237 }
3238
3239 #[test]
3240 fn identical_args_hash_equal() {
3241 let a = vec![Value::Int(7), Value::Str("hi".into())];
3242 let b = vec![Value::Int(7), Value::Str("hi".into())];
3243 assert_eq!(hash_call_args(&a), hash_call_args(&b));
3244 }
3245
3246 #[test]
3247 fn distinct_scalars_differ() {
3248 assert_ne!(hash_call_args(&[Value::Int(7)]), hash_call_args(&[Value::Int(8)]));
3249 assert_ne!(hash_call_args(&[Value::Int(0)]), hash_call_args(&[Value::Bool(false)]));
3250 assert_ne!(hash_call_args(&[Value::Int(0)]), hash_call_args(&[Value::Unit]));
3251 assert_ne!(hash_call_args(&[Value::Bool(true)]), hash_call_args(&[Value::Bool(false)]));
3252 }
3253
3254 #[test]
3255 fn arity_is_part_of_the_key() {
3256 assert_ne!(
3257 hash_call_args(&[Value::Int(1), Value::Int(2)]),
3258 hash_call_args(&[Value::Int(1)]),
3259 );
3260 // A 2-arg call vs a single Tuple arg of the same elements
3261 // must not collide.
3262 assert_ne!(
3263 hash_call_args(&[Value::Int(1), Value::Int(2)]),
3264 hash_call_args(&[Value::Tuple(vec![Value::Int(1), Value::Int(2)])]),
3265 );
3266 }
3267
3268 #[test]
3269 fn record_hash_is_field_order_independent() {
3270 // IndexMap equality ignores insertion order, so the key must
3271 // too — otherwise equal records would miss the cache.
3272 let r1 = rec(&[("a", Value::Int(1)), ("b", Value::Int(2))]);
3273 let r2 = rec(&[("b", Value::Int(2)), ("a", Value::Int(1))]);
3274 assert_eq!(r1, r2, "precondition: records compare equal");
3275 assert_eq!(hash_call_args(&[r1]), hash_call_args(&[r2]));
3276 }
3277
3278 #[test]
3279 fn record_distinguishes_values_and_keys() {
3280 let base = rec(&[("a", Value::Int(1)), ("b", Value::Int(2))]);
3281 let diff_val = rec(&[("a", Value::Int(1)), ("b", Value::Int(3))]);
3282 let diff_key = rec(&[("a", Value::Int(1)), ("c", Value::Int(2))]);
3283 assert_ne!(hash_call_args(std::slice::from_ref(&base)), hash_call_args(&[diff_val]));
3284 assert_ne!(hash_call_args(&[base]), hash_call_args(&[diff_key]));
3285 }
3286
3287 #[test]
3288 fn shape_id_does_not_affect_record_key() {
3289 // PartialEq ignores shape_id; the key must too.
3290 let mut m: IndexMap<SmolStr, Value> = IndexMap::new();
3291 m.insert("a".into(), Value::Int(1));
3292 let r_no_shape = Value::Record { shape_id: crate::value::NO_SHAPE_ID, fields: Box::new(m.clone()) };
3293 let r_shaped = Value::Record { shape_id: 3, fields: Box::new(m) };
3294 assert_eq!(r_no_shape, r_shaped);
3295 assert_eq!(hash_call_args(&[r_no_shape]), hash_call_args(&[r_shaped]));
3296 }
3297
3298 #[test]
3299 fn variant_name_and_args_matter() {
3300 let some1 = Value::Variant { name: "Some".into(), args: vec![Value::Int(1)] };
3301 let some1b = Value::Variant { name: "Some".into(), args: vec![Value::Int(1)] };
3302 let some2 = Value::Variant { name: "Some".into(), args: vec![Value::Int(2)] };
3303 let none = Value::Variant { name: "None".into(), args: vec![] };
3304 assert_eq!(hash_call_args(std::slice::from_ref(&some1)), hash_call_args(&[some1b]));
3305 assert_ne!(hash_call_args(std::slice::from_ref(&some1)), hash_call_args(&[some2]));
3306 assert_ne!(hash_call_args(&[some1]), hash_call_args(&[none]));
3307 }
3308
3309 #[test]
3310 fn float_bit_pattern_keys() {
3311 assert_eq!(hash_call_args(&[Value::Float(1.5)]), hash_call_args(&[Value::Float(1.5)]));
3312 assert_ne!(hash_call_args(&[Value::Float(1.5)]), hash_call_args(&[Value::Float(2.5)]));
3313 // Same NaN bit pattern → same key (harmless: pure callee is
3314 // deterministic on bit-identical args).
3315 let nan = f64::NAN;
3316 assert_eq!(hash_call_args(&[Value::Float(nan)]), hash_call_args(&[Value::Float(nan)]));
3317 }
3318}