logicaffeine_compile/vm/machine.rs
1//! The bytecode dispatch loop.
2//!
3//! Registers live in one contiguous `Vec<Value>`; `base` is the current frame's
4//! offset into it, so every register access is `registers[base + r]`. Calls use
5//! register windowing — the callee's frame starts at the caller's `args_start`,
6//! so arguments are passed with zero copying.
7
8use super::instruction::{BoundaryType, CompiledProgram, Constant, FuncIdx, ObsSiteKind, Op, Reg};
9use super::value::Value;
10use super::MAX_REGISTER_FILE;
11use logicaffeine_runtime::{ChanId, RtPayload, SelectArm, TaskId};
12
13/// Callee analysis for list-param call admission — may a region call this function while passing a
14/// pinned list argument? Returns `(list_params_stable, returns_list_param)`,
15/// both SOUND under-approximations:
16/// - `list_params_stable`: no operation which can reallocate receives a list
17/// parameter or one of its aliases. Allocating and pushing an unrelated
18/// local list is harmless, as are scalar-only helper calls.
19/// - `returns_list_param`: every `Return` traces — through `Move`s, to a
20/// fixpoint — to a list PARAMETER slot, and all list params share one element
21/// kind (the returned list kind is then unambiguous from the signature). A
22/// purely scalar return makes this `false` and rides `ret` instead.
23fn analyze_list_call_safety(
24 body: &[Op],
25 param_count: u16,
26 param_kinds: &[Option<super::native_tier::ParamKind>],
27 register_count: usize,
28) -> (bool, bool) {
29 use super::native_tier::ParamKind;
30 let n = register_count.max(param_count as usize);
31 // Slots that (transitively via Move) hold a list-parameter handle.
32 let mut is_param_list = vec![false; n];
33 for i in 0..param_count as usize {
34 if matches!(param_kinds.get(i), Some(Some(ParamKind::List(_)))) {
35 is_param_list[i] = true;
36 }
37 }
38 loop {
39 let mut changed = false;
40 for op in body {
41 match *op {
42 Op::Move { dst, src } => {
43 let (d, s) = (dst as usize, src as usize);
44 if d < n && s < n && is_param_list[s] && !is_param_list[d] {
45 is_param_list[d] = true;
46 changed = true;
47 }
48 }
49 Op::RevSwap { a, b } => {
50 let (a, b) = (a as usize, b as usize);
51 if a < n && b < n && (is_param_list[a] || is_param_list[b]) {
52 if !is_param_list[a] || !is_param_list[b] {
53 changed = true;
54 }
55 is_param_list[a] = true;
56 is_param_list[b] = true;
57 }
58 }
59 _ => {}
60 }
61 }
62 if !changed {
63 break;
64 }
65 }
66 let list_params_stable = !body.iter().any(|op| match *op {
67 Op::ListPush { list, .. } => is_param_list.get(list as usize).copied().unwrap_or(true),
68 Op::Call {
69 args_start,
70 arg_count,
71 ..
72 } => (args_start..args_start.saturating_add(arg_count))
73 .any(|r| is_param_list.get(r as usize).copied().unwrap_or(true)),
74 _ => false,
75 });
76 // All list params must share a single element kind so the return's list kind
77 // is unambiguous from the signature alone.
78 let mut elem: Option<super::native_tier::PinElem> = None;
79 let mut uniform = true;
80 for pk in param_kinds {
81 if let Some(ParamKind::List(e)) = pk {
82 if elem.is_some() && elem != Some(*e) {
83 uniform = false;
84 }
85 elem = Some(*e);
86 }
87 }
88 let returns: Vec<u16> = body
89 .iter()
90 .filter_map(|op| {
91 if let Op::Return { src } = *op {
92 Some(src)
93 } else {
94 None
95 }
96 })
97 .collect();
98 let returns_list_param = uniform
99 && !returns.is_empty()
100 && returns
101 .iter()
102 .all(|&s| (s as usize) < n && is_param_list[s as usize]);
103 (list_params_stable, returns_list_param)
104}
105
106/// The list element representation a native caller may receive by Vec handle.
107/// Keep this in lock-step with the function tier's `ListByHandle` lanes.
108fn native_list_return(return_type: Option<&BoundaryType>) -> Option<super::native_tier::PinElem> {
109 use super::native_tier::PinElem;
110 match return_type {
111 Some(BoundaryType::Seq(elem)) => match elem.as_ref() {
112 BoundaryType::Int => Some(PinElem::Int),
113 BoundaryType::Word32 => Some(PinElem::Word32),
114 _ => None,
115 },
116 _ => None,
117 }
118}
119
120/// Whether `LOGOS_JIT_CANARY=1` armed the region-frame sentinel guard
121/// (read once; the per-region path stays branch-cheap). Off by default and
122/// in release, so normal runs pay nothing — it is a diagnostic for native
123/// out-of-bounds writes.
124fn jit_canary_enabled() -> bool {
125 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
126 *ON.get_or_init(|| std::env::var("LOGOS_JIT_CANARY").is_ok_and(|v| v == "1"))
127}
128
129/// How a native region run left the loop.
130enum RegionExit {
131 /// Fell out the loop's exit edge — resume at this pc.
132 At(usize),
133 /// Install the native callee frames after restoring the caller's region.
134 Call {
135 call_pc: usize,
136 resume_pc: usize,
137 frames: Vec<super::native_tier::NativeFrame>,
138 list_args: Vec<Value>,
139 },
140 /// Hit an in-region `Return` — perform the function return with this value.
141 Return(Value),
142}
143
144/// What the native boundary decided for one call.
145enum NativeDisposition {
146 /// Completed natively; here is the re-boxed result.
147 Done(Value),
148 /// Run this call on bytecode (not compiled / guard mismatch / replay
149 /// deopt).
150 Interpret,
151 /// Precise deopt: push these frames and resume at `resume_pc`.
152 Materialize {
153 resume_pc: usize,
154 frames: Vec<super::native_tier::NativeFrame>,
155 list_args: Vec<Value>,
156 },
157}
158
159#[derive(Clone, Copy)]
160struct CallFrame {
161 return_pc: usize,
162 return_reg: Reg,
163 caller_base: usize,
164 restore_len: usize,
165 /// Iterator-stack depth at call entry; a Return unwinds any iterators the
166 /// callee left open (e.g. `Return` inside a `Repeat`).
167 iter_depth: usize,
168 /// The function whose body this frame runs — selects the per-frame
169 /// named-register map for loop regions tiering up inside it.
170 func: u16,
171 /// Absolute register index of this call's argument window (`callee_base`) and
172 /// how many arguments it holds. On return these slots are nulled: as the
173 /// callee's parameters they persist below `restore_len`, and a collection
174 /// argument would otherwise leave a live `Rc` clone in the caller's frame,
175 /// inflating `strong_count` and forcing needless copy-on-write later. Zero
176 /// `arg_count` (native/scheduler frames) clears nothing.
177 arg_lo: usize,
178 arg_count: u16,
179}
180
181/// Which registers of one code region's frame are LIVE entering each op of the region — read on
182/// some path before they are next written. A register not live at a pc holds nothing the frame
183/// will read again, so a collection it still references is a copy nobody can observe.
184///
185/// Built from the one register-operand enumeration ([`super::instruction::visit_regs`], through
186/// `op_def_uses`) and the ops' own control successors, both over-approximating what an op reads:
187/// liveness can only come out too large, never too small, so "dead" is always true.
188struct FrameLiveness {
189 /// The region `[start, end)` of `program.code` this covers.
190 start: usize,
191 end: usize,
192 /// `u64` words per pc; bit `r` of a pc's words is register `r`.
193 words: usize,
194 live_in: Vec<u64>,
195}
196
197impl FrameLiveness {
198 fn of(program: &CompiledProgram, start: usize, end: usize, regs: usize) -> FrameLiveness {
199 let words = regs.div_ceil(64).max(1);
200 let n = end - start;
201 let mut defs = vec![0u64; n * words];
202 let mut uses = vec![0u64; n * words];
203 let mut succ: Vec<Vec<usize>> = Vec::with_capacity(n);
204 // A successor outside the region is a pc this frame cannot see into: everything is live there.
205 let mut exits = vec![false; n];
206 let set = |bits: &mut [u64], i: usize, r: Reg| {
207 if (r as usize) < regs {
208 bits[i * words + r as usize / 64] |= 1u64 << (r % 64);
209 }
210 };
211 for i in 0..n {
212 let op = &program.code[start + i];
213 let (d, u) = super::instruction::op_def_uses(op, &program.functions);
214 for r in d {
215 set(&mut defs, i, r);
216 }
217 for r in u {
218 set(&mut uses, i, r);
219 }
220 let mut inside = Vec::new();
221 for t in super::instruction::op_successors(op, start + i, end) {
222 if (start..end).contains(&t) {
223 inside.push(t - start);
224 } else {
225 exits[i] = true;
226 }
227 }
228 succ.push(inside);
229 }
230 let mut live_in = vec![0u64; n * words];
231 let mut out = vec![0u64; words];
232 let mut changed = true;
233 while changed {
234 changed = false;
235 for i in (0..n).rev() {
236 out.iter_mut()
237 .for_each(|w| *w = if exits[i] { u64::MAX } else { 0 });
238 for &t in &succ[i] {
239 for w in 0..words {
240 out[w] |= live_in[t * words + w];
241 }
242 }
243 for w in 0..words {
244 let v = uses[i * words + w] | (out[w] & !defs[i * words + w]);
245 if v != live_in[i * words + w] {
246 live_in[i * words + w] = v;
247 changed = true;
248 }
249 }
250 }
251 }
252 FrameLiveness {
253 start,
254 end,
255 words,
256 live_in,
257 }
258 }
259
260 /// Whether register `r` may still be read entering `pc`. A pc outside the region answers
261 /// `true`: nothing is known about it.
262 fn is_live(&self, pc: usize, r: Reg) -> bool {
263 if !(self.start..self.end).contains(&pc) || r as usize >= self.words * 64 {
264 return true;
265 }
266 let i = pc - self.start;
267 self.live_in[i * self.words + r as usize / 64] & (1u64 << (r % 64)) != 0
268 }
269}
270
271/// The allocation a List, Map or Set value lives in — the identity copy-on-write asks about.
272fn collection_ptr(v: &Value) -> Option<usize> {
273 use crate::interpreter::RuntimeValue;
274 use std::rc::Rc;
275 match v.as_runtime_ref()? {
276 RuntimeValue::List(rc) => Some(Rc::as_ptr(rc) as *const u8 as usize),
277 RuntimeValue::Map(rc) => Some(Rc::as_ptr(rc) as *const u8 as usize),
278 RuntimeValue::Set(rc) => Some(Rc::as_ptr(rc) as *const u8 as usize),
279 _ => None,
280 }
281}
282
283/// How many holders a List, Map or Set value's allocation has (its `Rc` strong count); 1 otherwise.
284fn holder_count(v: &Value) -> usize {
285 use crate::interpreter::RuntimeValue;
286 use std::rc::Rc;
287 match v.as_runtime_ref() {
288 Some(RuntimeValue::List(rc)) => Rc::strong_count(rc),
289 Some(RuntimeValue::Map(rc)) => Rc::strong_count(rc),
290 Some(RuntimeValue::Set(rc)) => Rc::strong_count(rc),
291 _ => 1,
292 }
293}
294
295/// [`collection_ptr`] of a List, Map or Set that has more than one holder.
296fn shared_collection(v: &Value) -> Option<usize> {
297 use crate::interpreter::RuntimeValue;
298 use std::rc::Rc;
299 let shared = match v.as_runtime_ref()? {
300 RuntimeValue::List(rc) => Rc::strong_count(rc) > 1,
301 RuntimeValue::Map(rc) => Rc::strong_count(rc) > 1,
302 RuntimeValue::Set(rc) => Rc::strong_count(rc) > 1,
303 _ => false,
304 };
305 if shared {
306 collection_ptr(v)
307 } else {
308 None
309 }
310}
311
312/// The outcome of one `run_until_block` slice (T11). A non-concurrent program
313/// always returns `Done` on the first slice, so `run()` behaves exactly as the
314/// old single-shot loop. A concurrent task returns `Blocked` at each scheduler
315/// op; the driver reads [`Vm::take_pending`] and re-enters after the block clears.
316pub(crate) enum VmStep {
317 /// The (sub)program ran to completion (`Halt` or code exhausted) with the
318 /// given result payload (the main/return value, `Nothing` if none).
319 Done(crate::interpreter::RuntimeValue),
320 /// Suspended at a concurrency op; [`Vm::take_pending`] carries the request.
321 Blocked,
322 /// Suspended by the debug stepper after exhausting its per-call op budget
323 /// (`STEPPED = true` only). Resumable on the next [`Vm::run_steps`]. The
324 /// production path (`run_until_block`, `STEPPED = false`) never yields this.
325 Paused,
326}
327
328/// A read-only view of the paused VM for the Studio debug drawer: the program
329/// counter, the live call frames (Main first, current last) with their register
330/// values, the named globals, and the output so far. Values are rendered with the
331/// same `to_display_string` the `Show` op uses.
332pub(crate) struct DebugView {
333 pub pc: usize,
334 pub frames: Vec<DebugFrameView>,
335 pub globals: Vec<(String, String)>,
336 pub output: Vec<String>,
337}
338
339/// One call frame's registers in a [`DebugView`]. `func` is `None` for Main; `base`
340/// is the frame's start offset in the linear register file (its stack address).
341pub(crate) struct DebugFrameView {
342 pub func: Option<u16>,
343 pub base: usize,
344 /// `(index, type-name, display-value)` per register, e.g. `(1, "Int", "6")`.
345 pub registers: Vec<(u16, String, String)>,
346}
347
348/// One heap-allocated object (list / map / set / tuple / text / struct) reachable
349/// from the current frame or the globals — the heap-viewer's unit. `id` is the live
350/// allocation address (so two roots sharing one object share an `id` → aliasing), and
351/// `rc` is its reference count.
352pub(crate) struct HeapObjView {
353 pub id: usize,
354 pub kind: String,
355 pub summary: String,
356 /// The underlying storage layout (e.g. `packed Vec<i64>`, `columnar`) — teaches
357 /// how the data is actually laid out in memory.
358 pub storage: String,
359 pub rc: usize,
360 pub referenced_by: Vec<String>,
361}
362
363/// The heap identity of a value — its allocation address, kind, and storage-layout label.
364/// `None` for inline scalars (Int/Float/Bool/Char/…), which live in the register slot
365/// itself and are not heap objects.
366fn heap_identity(val: &Value) -> Option<(usize, String, String)> {
367 object_identity(val.as_runtime_ref()?)
368}
369
370fn object_identity(rv: &crate::interpreter::RuntimeValue) -> Option<(usize, String, String)> {
371 use crate::interpreter::RuntimeValue as RV;
372 use std::rc::Rc;
373 let s = |x: &str| x.to_string();
374 match rv {
375 RV::List(rc) => Some((
376 Rc::as_ptr(rc) as usize,
377 s("list"),
378 rc.borrow().storage_label().to_string(),
379 )),
380 RV::Map(rc) => Some((Rc::as_ptr(rc) as usize, s("map"), s("hash map"))),
381 RV::Set(rc) => Some((Rc::as_ptr(rc) as usize, s("set"), s("vec set"))),
382 RV::Tuple(rc) => Some((Rc::as_ptr(rc) as usize, s("tuple"), s("fixed tuple"))),
383 RV::Text(rc) => Some((Rc::as_ptr(rc) as usize, s("text"), s("Rc<String>"))),
384 RV::Struct(b) => Some((&**b as *const _ as usize, s("struct"), s("field map"))),
385 RV::Inductive(b) => Some((&**b as *const _ as usize, s("enum"), s("tagged variant"))),
386 _ => None,
387 }
388}
389
390/// How many handles the running program holds on each heap allocation, keyed by the
391/// allocation's address: one per root that holds it, plus one per slot of any container
392/// the roots reach. A container is entered once however many handles reach it, so its
393/// contents count once. This is the program's own reference count — `Rc::strong_count`
394/// would also count every copy held outside the roots, such as the debugger's history.
395pub(crate) fn count_handles<'a>(
396 roots: impl IntoIterator<Item = &'a crate::interpreter::RuntimeValue>,
397) -> std::collections::HashMap<usize, usize> {
398 use crate::interpreter::RuntimeValue as RV;
399 use std::collections::{HashMap, HashSet};
400
401 fn visit(v: &RV, counts: &mut HashMap<usize, usize>, entered: &mut HashSet<usize>) {
402 let Some((id, _, _)) = object_identity(v) else {
403 return;
404 };
405 *counts.entry(id).or_insert(0) += 1;
406 if !entered.insert(id) {
407 return;
408 }
409 match v {
410 RV::List(l) => {
411 for item in l.borrow().to_values() {
412 visit(&item, counts, entered);
413 }
414 }
415 RV::Set(items) => {
416 for item in items.borrow().iter() {
417 visit(item, counts, entered);
418 }
419 }
420 RV::Map(m) => {
421 for (k, item) in m.borrow().iter() {
422 visit(k, counts, entered);
423 visit(item, counts, entered);
424 }
425 }
426 RV::Tuple(items) => {
427 for item in items.iter() {
428 visit(item, counts, entered);
429 }
430 }
431 RV::Struct(s) => {
432 for item in s.fields.values() {
433 visit(item, counts, entered);
434 }
435 }
436 RV::Inductive(ind) => {
437 for item in ind.args.iter() {
438 visit(item, counts, entered);
439 }
440 }
441 _ => {}
442 }
443 }
444
445 let mut counts = HashMap::new();
446 let mut entered = HashSet::new();
447 for root in roots {
448 visit(root, &mut counts, &mut entered);
449 }
450 counts
451}
452
453/// The resumable execution state of a single-task program — enough to pause it and
454/// resume in a freshly-built `tier: None` VM. The debugger owns the
455/// [`CompiledProgram`] and rebuilds the VM each step (it cannot hold a borrowing
456/// `Vm<'p>` across steps), threading this snapshot through. Concurrency request
457/// state is intentionally omitted (the debugger is single-task, bytecode-tier).
458#[derive(Clone)]
459pub(crate) struct DebugVmState {
460 registers: Vec<Value>,
461 base: usize,
462 globals: Vec<Option<Value>>,
463 lines: Vec<String>,
464 iter_stack: Vec<(Vec<Value>, usize)>,
465 sched_active: bool,
466 sched_pc: usize,
467 sched_call_stack: Vec<CallFrame>,
468}
469
470impl DebugVmState {
471 /// The pc the program is stopped at (the op about to execute).
472 pub(crate) fn pc(&self) -> usize {
473 self.sched_pc
474 }
475 /// Call-stack depth (0 = in Main), for step-over / step-out.
476 pub(crate) fn call_depth(&self) -> usize {
477 self.sched_call_stack.len()
478 }
479 /// What the program has printed up to this state.
480 pub(crate) fn lines(&self) -> &[String] {
481 &self.lines
482 }
483}
484
485/// A concurrency request a suspended [`Vm`] hands to the scheduler driver — the
486/// VM analog of the tree-walker's `BlockingRequest`. A spawned child travels as a
487/// fully-built `Vm` (sharing the parent's `&'p program`), which the driver wraps
488/// in its own task.
489pub(crate) enum VmBlock {
490 /// Create a channel (`None` = the scheduler's default capacity); resume with its id.
491 NewChan(Option<usize>),
492 /// Send a value into a channel (blocks if full).
493 Send(ChanId, RtPayload),
494 /// Receive from a channel (blocks if empty); resume with the value.
495 Recv(ChanId),
496 /// Non-blocking send; resume with `Bool(success)`.
497 TrySend(ChanId, RtPayload),
498 /// Non-blocking receive; resume with the value or `Nothing`.
499 TryRecv(ChanId),
500 /// Close a channel.
501 Close(ChanId),
502 /// Spawn a child *by descriptor* — function index + materialised args — so the
503 /// driver builds the child `Vm` (the cooperative driver inline, a work-stealing
504 /// worker locally over its own program). `want_handle` distinguishes a launch
505 /// that binds a task handle. Resume with the child's `TaskId`.
506 SpawnDesc {
507 func: FuncIdx,
508 args: Vec<RtPayload>,
509 want_handle: bool,
510 },
511 /// Await a task's completion; resume with its result payload.
512 Await(TaskId),
513 /// Abort a task.
514 Abort(TaskId),
515 /// Block on the first ready select arm; resume with the winning arm index.
516 Select(Vec<SelectArm>),
517 /// Sleep for some logical ticks.
518 Sleep(u64),
519 /// Dial the relay (async); resume when connected. Carries the URL value.
520 NetConnect(RtPayload),
521 /// Subscribe our inbox (async); resume when subscribed. Carries the topic value.
522 NetListen(RtPayload),
523 /// Encode + publish to a peer; resume immediately. Carries `(peer, message)`.
524 NetSend(RtPayload, RtPayload),
525 /// Batch-stream a list to a peer; resume immediately. Carries `(peer, list)`.
526 NetStream(RtPayload, RtPayload),
527 /// Await a message (or batch stream, if the flag) from a peer (blocks); resume with the value.
528 /// Carries `(peer, stream_flag)`.
529 NetAwait(RtPayload, bool),
530 /// Resolve an address value into a PeerAgent handle (its canonical topic); resume with the peer.
531 /// Carries the address value.
532 NetMakePeer(RtPayload),
533 /// CRDT sync point: publish the current counter, merge what has arrived, resume with the merged
534 /// value. Carries `(topic, current)`.
535 NetSync(RtPayload, RtPayload),
536 /// A tcp.lg native (the `TcpOp` code + materialised operands); resume with the
537 /// LOGOS `Result` value from the shared `TcpRegistry::exec_values`.
538 Tcp(u8, Vec<RtPayload>),
539 /// Serve HTTP: the bound `port` and the handler `FuncIdx`. The async io
540 /// driver owns the concurrent accept loop and re-enters the handler as a
541 /// fresh child `Vm` per connection. The loop never returns, so this block
542 /// never resumes.
543 Serve(u16, FuncIdx),
544}
545
546pub struct Vm<'p> {
547 program: &'p CompiledProgram,
548 /// The constant pool MATERIALISED into runtime values once at construction.
549 /// A `LoadConst` then clones the pre-built `Value` — for a heap `Text` that
550 /// is an `Rc` refcount bump, not a fresh `String`+`Rc` allocation, so a
551 /// 1-char literal reloaded every iteration of a hot loop (string_search's
552 /// `ch`) costs no heap traffic. The pool keeps a live reference, so a
553 /// freshly-loaded literal is never the sole owner and the in-place
554 /// `add_assign` append correctly declines to mutate it.
555 const_pool: Vec<Value>,
556 registers: Vec<Value>,
557 base: usize,
558 /// One element per `Show` (a shown value may itself contain newlines —
559 /// it is still ONE output line, like the tree-walker's emit callback).
560 lines: Vec<String>,
561 /// Copies and elements copied when a record field must become privately owned.
562 record_field_copy_work: (usize, usize),
563 /// Live `Repeat` snapshots: (elements, next index). Stack-disciplined —
564 /// `IterPrepare` pushes, `IterPop` pops, nesting nests.
565 iter_stack: Vec<(Vec<Value>, usize)>,
566 /// Promoted globals (None = not yet defined; reading one is the
567 /// "Undefined variable" error).
568 globals: Vec<Option<Value>>,
569 /// Policy registry + interner for `Check` statements (absent ⇒ the
570 /// tree-walker's "Security Check requires policies" error).
571 policy_ctx: Option<(
572 &'p crate::analysis::PolicyRegistry,
573 &'p crate::intern::Interner,
574 )>,
575 /// The pluggable native tier (None = pure bytecode, e.g. WASM).
576 tier: Option<&'p dyn super::native_tier::NativeTier>,
577 /// FuncIdx of crypto.lg's `pbkdf2Sha256`, when present — the interpreted VM
578 /// substitutes the byte-identical native reference (`crypto_accel`) for its
579 /// pure Hi() loop (4096 iterations ≈ 16k SHA-256 compressions is far too slow
580 /// to run as bytecode for a live SCRAM handshake). Set by `with_policy_ctx`,
581 /// which carries the interner. Mirrors the tree-walker's `pbkdf2_accel`.
582 accel_pbkdf2: Option<FuncIdx>,
583 /// Per-function call counts (profiling toward the tier threshold).
584 hot: Vec<u32>,
585 /// Per-function native state.
586 native: Vec<super::native_tier::NativeSlot>,
587 /// Back-edge counts for MAIN loops (keyed by loop-head pc). FxHash: this
588 /// is probed once per back-edge crossing of every Main loop that has not
589 /// (or cannot) tier up — a per-iteration cost on the bytecode path.
590 region_hot: rustc_hash::FxHashMap<usize, u32>,
591 /// Compiled Main-loop regions (keyed by loop-head pc; same probe rate).
592 regions: rustc_hash::FxHashMap<usize, super::native_tier::RegionSlot>,
593 /// Per-region (loop-head pc) collection registers this region mutates IN
594 /// PLACE. Under value semantics these are copy-on-write'd at region ENTRY
595 /// (`ensure_reg_owned`) so the native code's in-place writes cannot alias a
596 /// shared allocation — the perf-preserving follow-up to the correctness-first
597 /// decline. Only populated when the region is provably alias-free (a mutated
598 /// collection never escapes it), so entry-COW alone isolates it soundly.
599 region_cow_regs: rustc_hash::FxHashMap<usize, Vec<u16>>,
600 /// Per-pc dead-region bitset: once a loop head is known `Failed`
601 /// (un-tierable, or demoted after repeated guard misses) its entry here is
602 /// set, so the back-edge hook short-circuits with a single `Vec<bool>`
603 /// index instead of re-hashing `regions` on every iteration. Loops that
604 /// never tier (effectful bodies, `Text` ops, list-param fns) are the common
605 /// case and pay only this O(1) check after the first failure. Indexed by
606 /// loop-head pc; sized to the code length.
607 region_blacklist: Vec<bool>,
608 /// Program arguments for the `args()` system native — full argv, index 0 is
609 /// the program name (mirrors the compiled binary's `env::args()`). Empty
610 /// when none were supplied.
611 program_args: Vec<String>,
612 /// Per-program native-tier context: the EXODIA 4.7 entry table plus the
613 /// shared deopt-status and live-depth cells every chain patches.
614 native_ctx: super::native_tier::NativeCtx,
615 /// The off-thread native compiler (HOTSWAP §6), present only when the VM was
616 /// given the process-installed `&'static` tier via [`Vm::with_bg_native_tier`].
617 /// `None` ⇒ compile synchronously on this thread (the retained fallback, and the
618 /// only path for a borrowed `&'p` tier). Native-only: needs `std::thread`+forge.
619 #[cfg(not(target_arch = "wasm32"))]
620 bg: Option<super::bg_compile::BgCompiler>,
621 /// Axis-1 warm-bytecode side-table (HOTSWAP §7 / P11): re-optimized function
622 /// bodies appended here, in the same pc space *after* `program.code`. A `Call`
623 /// to a function with a `warm_entry` jumps into this buffer instead of the
624 /// baseline `entry_pc`. Pure bytecode — no forge, no `rustc` — so it is the
625 /// browser's hot-swap tier. Empty until a body is installed, and every read
626 /// path is gated on `pc >= program.code.len()`, so the baseline run loop is
627 /// byte-for-byte unchanged when nothing is warm.
628 warm_code: Vec<Op>,
629 /// Per-function warm entry (indexed by function index): the absolute pc of the
630 /// body in the unified `program.code ++ warm_code` space, and its register
631 /// window. `None` ⇒ the function runs its baseline body.
632 warm_entry: Vec<Option<WarmEntry>>,
633
634 /// Resumable-execution state for the scheduler driver (T11). When a task
635 /// suspends at a concurrency op, `run_until_block` saves its `pc` + call stack
636 /// here and restores them on the next slice. A non-concurrent run never sets
637 /// `sched_active`, so it starts fresh at pc 0 — byte-for-byte the old loop.
638 sched_active: bool,
639 sched_pc: usize,
640 sched_call_stack: Vec<CallFrame>,
641 /// Ops run by every [`Vm::run_steps`] slice so far: a fueled run's driver reads the difference across a
642 /// slice to charge the fuel what the slice spent, whether it paused, blocked, failed or finished.
643 stepped: u64,
644 /// The concurrency request produced by the last `Blocked` slice (taken by the
645 /// driver). `None` between slices and for a non-concurrent run.
646 pending: Option<VmBlock>,
647 /// The register the next resume value is delivered into (`None` for a block
648 /// that yields nothing, e.g. `Send`/`Close`).
649 resume_slot: Option<Reg>,
650 /// Whether the value resuming into [`Self::resume_slot`] must be wrapped as an `Option`.
651 ///
652 /// A `Try to receive` answers "a value, or nothing", which IS an Option — but the SCHEDULER
653 /// hands back the bare payload (or `Nothing`), and the same generic resume path serves the
654 /// blocking `Recv`/`Await` where the value is NOT optional. So the wrap cannot live in the
655 /// driver; the VM records here which kind of block reserved the slot.
656 resume_wraps_option: bool,
657 /// Accumulated `Select` arms awaiting a `SelectWait`: each runtime arm plus
658 /// the register a winning recv arm binds its value into. Persists across the
659 /// block so `deliver_select` can route the received value to the right arm.
660 select_pending: Vec<(SelectArm, Option<Reg>)>,
661 /// The first failure a page entry the program took itself ([`BuiltinId::DomDispatchEntry`])
662 /// contained and no failure handler absorbed, with the failure site in force when it trapped:
663 /// the program's own failure once nothing is left to run ([`Vm::run_until_block`]).
664 ///
665 /// [`BuiltinId::DomDispatchEntry`]: crate::semantics::builtins::BuiltinId::DomDispatchEntry
666 unhandled: Option<(String, Option<u32>)>,
667 /// The failure site of the run's end, when a contained failure ended it: what
668 /// [`Vm::failing_site`] answers then, the site the failure trapped at.
669 ended_at_site: Option<Option<u32>>,
670 /// Reverse-execution history tape (Bennett/Landauer garbage), `Some` ONLY during a
671 /// [`Vm::run_recording`] pass. The production `run` path never sets or reads it, and every
672 /// recording block lives behind the `const RECORDING` monomorph, so the 2.5×-C hot loop is
673 /// byte-for-byte unchanged (`RECORDING = false` dead-strips it, exactly like `STEPPED`).
674 journal: Option<super::journal::HistoryTape>,
675 /// The pebbling plan (per-pc journal decisions) for the active recording mode — `Some` only
676 /// during a recording pass. Consulted by `record_op` (skip an elided scratch write) and by the
677 /// reverse executor (skip restoring it), so an elided entry is neither pushed nor popped.
678 journal_plan: Option<Vec<super::pebble::JournalDecision>>,
679 /// The reversibility mode the active recording was set up for. `Adiabatic` restores elided scratch
680 /// to its known default on reverse (full fidelity at the Landauer floor); the others do not.
681 reverse_mode: super::reverse::ReverseMode,
682 /// (`Adiabatic`, Piece 2) Reverse-live scratch RECOMPUTED on reverse instead of journaled, keyed
683 /// by `(frame, register)` (register numbers are frame-relative) → its pure defining op, re-run with
684 /// `self.base` set to the frame just before a reverse step reads it.
685 recompute: std::collections::HashMap<(Option<usize>, Reg), Op>,
686 /// (Corner 2) The number of recompute-op re-executions performed during a reverse pass — the
687 /// load-bearing instrument for the pebble time/space schedule. `0` outside `Adiabatic`. A
688 /// budget-0 (recompute-everything) reverse of a chain read `K` times costs `≈ chain·K`;
689 /// checkpointing bounded intermediates drops it toward the Bennett `O(T^{1+ε})` point.
690 recompute_ops: usize,
691 /// (Corner 2) The pebble CHECKPOINT budget for `Adiabatic`: the max number of recomputable chain
692 /// nodes kept ON the tape (journaled once, `landauer = 0` since they are recomputable) so downstream
693 /// recomputes stop at the nearest checkpoint instead of re-walking to the chain root. `0` = the
694 /// recompute-everything corner (`O(1)` tape, chain·reads time); higher = the space-for-time trade.
695 pebble_budget: usize,
696 /// WS6 (Phase 13): the browser WASM-JIT tier. Consulted from `Op::Call` only under the
697 /// `wasm-jit` feature; entirely absent from the default build (and behind the native x86
698 /// forge tier on native, so it is the JIT tier specifically where forge cannot run —
699 /// wasm32).
700 #[cfg(feature = "wasm-jit")]
701 wasm_tier: super::wasm_jit::WasmTier,
702 /// How the code stream partitions into Main and each function ([`super::reach::code_layout`]),
703 /// resolved the first time a copy-on-write needs a frame's region; `Some(None)` when the layout
704 /// does not resolve, and no dead register is ever released.
705 code_layout: Option<Option<super::reach::CodeLayout>>,
706 /// Each region's [`FrameLiveness`], keyed by its first pc, built the first time a
707 /// copy-on-write inside that region finds its collection shared.
708 liveness: rustc_hash::FxHashMap<usize, std::rc::Rc<FrameLiveness>>,
709 /// The run real numbers the program defines by a function read their functions in, opened the
710 /// first time the program defines one ([`Vm::open_defined_run`]).
711 defined_run: Option<crate::semantics::defined::RunScope<'static>>,
712}
713
714/// A warm function body's location in the unified pc space (`program.code` then
715/// `warm_code`) plus the register window it executes in.
716#[derive(Clone, Copy, Debug)]
717struct WarmEntry {
718 entry_pc: usize,
719 register_count: usize,
720}
721
722impl<'p> Vm<'p> {
723 pub fn new(program: &'p CompiledProgram) -> Self {
724 Vm {
725 program,
726 const_pool: program.constants.iter().map(const_to_value).collect(),
727 registers: vec![Value::nothing(); program.register_count],
728 base: 0,
729 lines: Vec::new(),
730 record_field_copy_work: (0, 0),
731 iter_stack: Vec::new(),
732 globals: vec![None; program.globals.len()],
733 policy_ctx: None,
734 tier: None,
735 accel_pbkdf2: None,
736 hot: vec![0; program.functions.len()],
737 native: (0..program.functions.len())
738 .map(|_| super::native_tier::NativeSlot::Untried)
739 .collect(),
740 region_hot: rustc_hash::FxHashMap::default(),
741 regions: rustc_hash::FxHashMap::default(),
742 region_cow_regs: rustc_hash::FxHashMap::default(),
743 region_blacklist: vec![false; program.code.len()],
744 program_args: crate::semantics::argv_with_program_name(Vec::new()),
745 native_ctx: super::native_tier::NativeCtx {
746 table: std::sync::Arc::new(super::native_tier::FnTable::new(
747 program.functions.len(),
748 )),
749 status: std::sync::Arc::new(std::sync::atomic::AtomicI64::new(0)),
750 depth: std::sync::Arc::new(std::sync::atomic::AtomicI64::new(0)),
751 },
752 #[cfg(not(target_arch = "wasm32"))]
753 bg: None,
754 warm_code: Vec::new(),
755 warm_entry: vec![None; program.functions.len()],
756 sched_active: false,
757 sched_pc: 0,
758 sched_call_stack: Vec::new(),
759 stepped: 0,
760 pending: None,
761 resume_slot: None,
762 resume_wraps_option: false,
763 select_pending: Vec::new(),
764 unhandled: None,
765 ended_at_site: None,
766 journal: None,
767 journal_plan: None,
768 reverse_mode: super::reverse::ReverseMode::Observable,
769 recompute: std::collections::HashMap::new(),
770 recompute_ops: 0,
771 pebble_budget: 0,
772 #[cfg(feature = "wasm-jit")]
773 wasm_tier: super::wasm_jit::WasmTier::new(50),
774 code_layout: None,
775 liveness: rustc_hash::FxHashMap::default(),
776 defined_run: None,
777 }
778 }
779
780 /// Open the run real numbers the program defines by a function read their functions in, once.
781 /// Its evaluator calls a closure on a fresh machine over the same bytecode, which shares nothing
782 /// with this one but the program, so a digit read in the middle of an operation leaves this
783 /// machine's registers, frames and globals as they were.
784 fn open_defined_run(&mut self) -> &crate::semantics::defined::RunScope<'static> {
785 if self.defined_run.is_none() {
786 let program = std::rc::Rc::new(self.program.clone());
787 let evaluator: crate::semantics::defined::Evaluator<'static> =
788 std::rc::Rc::new(move |closure, n| {
789 Vm::new(&program).call_closure(closure, vec![crate::interpreter::RuntimeValue::Int(n)])
790 });
791 self.defined_run = Some(crate::semantics::defined::open_run(evaluator));
792 }
793 self.defined_run.as_ref().expect("the run is open")
794 }
795
796 /// Actual record-field copy work during this VM instance's lifetime:
797 /// (copies, elements copied), saturating at usize::MAX.
798 pub fn record_field_copy_work(&self) -> (usize, usize) {
799 self.record_field_copy_work
800 }
801
802 /// Install a re-optimized body as function `fi`'s warm tier (HOTSWAP §7 / P11):
803 /// append it to `warm_code` after `program.code`, rebasing its 0-relative jumps
804 /// into that unified pc space, and point `warm_entry[fi]` at it. Subsequent calls
805 /// to `fi` run this body. The body shares the program's constant pool (a
806 /// `FnBytecode` preserves constant indices), so only jumps are relocated.
807 pub fn install_warm_bytecode(
808 &mut self,
809 fi: usize,
810 fnbc: &super::fn_bytecode::FnBytecode,
811 ) -> bool {
812 // Refuse a structurally-invalid body (out-of-range jump/call, missing terminal
813 // op) or one whose arity disagrees with the baseline function — a corrupt cache
814 // entry or a buggy producer then falls back to baseline instead of fetching past
815 // the warm buffer (panic) or reading the wrong registers (HOTSWAP §P12 robustness).
816 if !fnbc.is_well_formed(self.program.functions.len()) {
817 return false;
818 }
819 match self.program.functions.get(fi) {
820 Some(f) if f.param_count == fnbc.param_count => {}
821 _ => return false,
822 }
823 let abs_base = self.program.code.len() + self.warm_code.len();
824 self.warm_code.extend(
825 fnbc.code
826 .iter()
827 .map(|&op| super::fn_bytecode::rebase(op, abs_base as isize)),
828 );
829 if fi >= self.warm_entry.len() {
830 self.warm_entry.resize(fi + 1, None);
831 }
832 self.warm_entry[fi] = Some(WarmEntry {
833 entry_pc: abs_base,
834 register_count: fnbc.register_count,
835 });
836 let name = self.fn_name(fi);
837 super::tier_trace::trace_transition(fi, &name, super::tier_trace::ExecTier::Warm);
838 true
839 }
840
841 /// Mark a loop head permanently `Failed` and record it in the per-pc
842 /// blacklist so the back-edge hook never probes `regions` for it again.
843 /// Every `RegionSlot::Failed` transition routes through here so the bitset
844 /// can never drift out of sync with the map.
845 fn mark_region_failed(&mut self, head: usize) {
846 self.regions
847 .insert(head, super::native_tier::RegionSlot::Failed);
848 if let Some(slot) = self.region_blacklist.get_mut(head) {
849 *slot = true;
850 }
851 }
852
853 /// The collection registers a region mutates IN PLACE (the collection
854 /// operand of every mutation op in its body).
855 fn region_mutated_collection_regs(body: &[Op]) -> rustc_hash::FxHashSet<u16> {
856 let mut s = rustc_hash::FxHashSet::default();
857 for op in body {
858 match op {
859 Op::ListPush { list: c, .. }
860 | Op::SetAdd { set: c, .. }
861 | Op::RemoveFrom { collection: c, .. }
862 | Op::SetIndex { collection: c, .. }
863 | Op::SetIndexUnchecked { collection: c, .. }
864 | Op::ListPop { list: c, .. } => {
865 s.insert(*c);
866 }
867 _ => {}
868 }
869 }
870 s
871 }
872
873 /// Collection registers that hold a FRESH, uniquely-owned collection for the
874 /// whole region: a `NewEmpty*{dst=C}` op DOMINATES every in-place mutation of
875 /// `C`. Such a collection is created anew on each entry to its live range, so its
876 /// mutation can NEVER alias — it needs no entry copy-on-write, and any use of
877 /// `C`'s register BEFORE the fresh definition is a disjoint (scalar) live range
878 /// that register-recycling left behind (fannkuch's `Set r to r-1` scratch landing
879 /// on `perm`'s slot before `perm` is created). Excluding these from the mutated
880 /// set keeps the region tier-able under value semantics WITHOUT weakening
881 /// soundness: a genuinely shared/aliased mutation has no dominating fresh
882 /// definition, so it stays in the set and is COW'd or declined.
883 ///
884 /// `body` is `program.code[head..=back]`; region-relative index `i` is pc `head+i`.
885 fn region_fresh_collection_regs(body: &[Op], head: usize) -> rustc_hash::FxHashSet<u16> {
886 let n = body.len();
887 let mut out = rustc_hash::FxHashSet::default();
888 if n == 0 {
889 return out;
890 }
891 // Region-relative successors (an edge leaving [head, back] is dropped — a
892 // fresh definition need only dominate mutations WITHIN the region).
893 let rel = |target: usize| -> Option<usize> { target.checked_sub(head).filter(|&r| r < n) };
894 let mut succs: Vec<Vec<usize>> = vec![Vec::new(); n];
895 for (i, op) in body.iter().enumerate() {
896 match op {
897 Op::Jump { target } => {
898 if let Some(r) = rel(*target) {
899 succs[i].push(r);
900 }
901 }
902 Op::JumpIfFalse { target, .. } | Op::JumpIfTrue { target, .. } => {
903 if let Some(r) = rel(*target) {
904 succs[i].push(r);
905 }
906 if i + 1 < n {
907 succs[i].push(i + 1);
908 }
909 }
910 Op::Return { .. } | Op::ReturnNothing | Op::Halt => {}
911 _ => {
912 if i + 1 < n {
913 succs[i].push(i + 1);
914 }
915 }
916 }
917 }
918 let mut preds: Vec<Vec<usize>> = vec![Vec::new(); n];
919 for (i, ss) in succs.iter().enumerate() {
920 for &s in ss {
921 preds[s].push(i);
922 }
923 }
924 // Iterative dominators over the region CFG (entry = relative 0 = `head`).
925 // `dom[i][k]` == node k dominates node i. Regions are small, so the O(n²) set
926 // representation is fine. Unreachable nodes keep the full (all-true) set —
927 // harmless: they never execute, so any "fresh" verdict on them is moot.
928 let mut dom: Vec<Vec<bool>> = vec![vec![true; n]; n];
929 dom[0] = vec![false; n];
930 dom[0][0] = true;
931 let mut changed = true;
932 while changed {
933 changed = false;
934 for i in 1..n {
935 if preds[i].is_empty() {
936 continue;
937 }
938 let mut new = vec![true; n];
939 for &p in &preds[i] {
940 for (k, nk) in new.iter_mut().enumerate() {
941 *nk &= dom[p][k];
942 }
943 }
944 new[i] = true;
945 if new != dom[i] {
946 dom[i] = new;
947 changed = true;
948 }
949 }
950 }
951 // Mutation positions per collection reg, and fresh-definition positions.
952 let mut muts: rustc_hash::FxHashMap<u16, Vec<usize>> = rustc_hash::FxHashMap::default();
953 let mut news: rustc_hash::FxHashMap<u16, Vec<usize>> = rustc_hash::FxHashMap::default();
954 for (i, op) in body.iter().enumerate() {
955 match op {
956 Op::ListPush { list: c, .. }
957 | Op::SetAdd { set: c, .. }
958 | Op::RemoveFrom { collection: c, .. }
959 | Op::SetIndex { collection: c, .. }
960 | Op::SetIndexUnchecked { collection: c, .. }
961 | Op::ListPop { list: c, .. } => muts.entry(*c).or_default().push(i),
962 Op::NewEmptyList { dst }
963 | Op::NewEmptyListWithCapacity { dst, .. }
964 | Op::NewEmptyListFixed { dst, .. }
965 | Op::NewEmptySet { dst }
966 | Op::NewEmptyMap { dst }
967 | Op::NewEmptyMapWithCapacity { dst, .. }
968 | Op::NewEmptyListI32 { dst } => news.entry(*dst).or_default().push(i),
969 _ => {}
970 }
971 }
972 for (c, mpos) in &muts {
973 if let Some(npos) = news.get(c) {
974 // Fresh iff SOME fresh-definition position dominates EVERY mutation.
975 if npos.iter().any(|&q| mpos.iter().all(|&m| dom[m][q])) {
976 out.insert(*c);
977 }
978 }
979 }
980 out
981 }
982
983 /// True if any mutated-collection register is COPIED, ALIASED, redefined, or
984 /// otherwise escapes the region — so region-entry copy-on-write alone cannot
985 /// keep it isolated and the region must run on the value-semantic VM. An
986 /// in-place collection mutation and a pure read use the collection soundly
987 /// (its buffer stays private to the region); ANY other operand use of a
988 /// mutated register — or any un-modelled op — fails closed.
989 fn region_mutation_escapes(body: &[Op], m: &rustc_hash::FxHashSet<u16>) -> bool {
990 let h = |r: &u16| m.contains(r);
991 let rng = |s: u16, c: u16| (s..s.saturating_add(c)).any(|r| m.contains(&r));
992 body.iter().any(|op| Self::op_escapes_mutated(op, &h, &rng))
993 }
994
995 fn op_escapes_mutated(
996 op: &Op,
997 h: &impl Fn(&u16) -> bool,
998 rng: &impl Fn(u16, u16) -> bool,
999 ) -> bool {
1000 match op {
1001 // In-place mutation: the collection operand is isolated by the entry
1002 // COW; only the OTHER operands can leak/redefine it.
1003 Op::ListPush { value, .. }
1004 | Op::SetAdd { value, .. }
1005 | Op::RemoveFrom { value, .. } => h(value),
1006 Op::SetIndex { index, value, .. } | Op::SetIndexUnchecked { index, value, .. } => {
1007 h(index) || h(value)
1008 }
1009 Op::ListPop { dst, .. } => h(dst),
1010 // Pure reads of a collection.
1011 Op::Index { dst, index, .. } | Op::IndexUnchecked { dst, index, .. } => {
1012 h(dst) || h(index)
1013 }
1014 Op::Length { dst, .. } => h(dst),
1015 Op::Contains { dst, value, .. } => h(dst) || h(value),
1016 Op::RegionBoundsGuard { bound, iv, .. } => h(bound) || h(iv),
1017 // Creating a FRESH collection in a mutated register is safe: the new
1018 // buffer is uniquely owned, so its in-place mutation cannot alias
1019 // (an aliasing copy would still be caught by the other arms). This is
1020 // the fresh-list-per-iteration pattern (`Let mutable p be a new Seq`).
1021 Op::NewEmptyList { .. }
1022 | Op::NewEmptyListFixed { .. }
1023 | Op::NewEmptySet { .. }
1024 | Op::NewEmptyMap { .. }
1025 | Op::NewEmptyListI32 { .. } => false,
1026 Op::NewEmptyListWithCapacity { capacity, .. }
1027 | Op::NewEmptyMapWithCapacity { capacity, .. } => h(capacity),
1028 Op::NewRange { start, end, .. } => h(start) || h(end),
1029 Op::NewList { start, count, .. } | Op::NewTuple { start, count, .. } => {
1030 rng(*start, *count)
1031 }
1032 // Scalars / control flow: decline only if a mutated reg is an operand
1033 // (a redefinition of the collection reg, or a scalar read of it).
1034 Op::LoadConst { dst, .. }
1035 | Op::GlobalGet { dst, .. }
1036 | Op::LoadToday { dst }
1037 | Op::LoadNow { dst }
1038 | Op::Args { dst }
1039 | Op::IterNext { dst, .. } => h(dst),
1040 // A call-site COW barrier may redefine (clone) the register — decline a
1041 // region if it targets a mutated collection reg. In practice it never
1042 // appears in a tier-able region (it sits beside a `Call`, and a region
1043 // with a call declines regardless).
1044 Op::EnsureOwned { reg } => h(reg),
1045 Op::Move { dst, src }
1046 | Op::Not { dst, src }
1047 | Op::AddAssign { dst, src }
1048 | Op::FormatValue { dst, src, .. } => h(dst) || h(src),
1049 Op::Add { dst, lhs, rhs }
1050 | Op::Sub { dst, lhs, rhs }
1051 | Op::Mul { dst, lhs, rhs }
1052 | Op::Div { dst, lhs, rhs }
1053 | Op::ExactDiv { dst, lhs, rhs }
1054 | Op::FloorDiv { dst, lhs, rhs }
1055 | Op::Mod { dst, lhs, rhs }
1056 | Op::Lt { dst, lhs, rhs }
1057 | Op::Gt { dst, lhs, rhs }
1058 | Op::LtEq { dst, lhs, rhs }
1059 | Op::GtEq { dst, lhs, rhs }
1060 | Op::Eq { dst, lhs, rhs }
1061 | Op::NotEq { dst, lhs, rhs }
1062 | Op::ApproxEq { dst, lhs, rhs }
1063 | Op::Pow { dst, lhs, rhs }
1064 | Op::BitXor { dst, lhs, rhs }
1065 | Op::BitAnd { dst, lhs, rhs }
1066 | Op::BitOr { dst, lhs, rhs }
1067 | Op::Shl { dst, lhs, rhs }
1068 | Op::Shr { dst, lhs, rhs } => h(dst) || h(lhs) || h(rhs),
1069 Op::MagicDivU { dst, lhs, .. } | Op::DivPow2 { dst, lhs, .. } => h(dst) || h(lhs),
1070 // Collection-producing binops READ their operands and yield a FRESH,
1071 // independent result — decline only if a mutated reg is involved.
1072 Op::Concat { dst, lhs, rhs }
1073 | Op::SeqConcat { dst, lhs, rhs }
1074 | Op::UnionOp { dst, lhs, rhs }
1075 | Op::IntersectOp { dst, lhs, rhs } => h(dst) || h(lhs) || h(rhs),
1076 // Enum-arm test/bind and struct-field read: scalar-shaped, no alias.
1077 Op::TestArm { dst, target, .. } | Op::BindArm { dst, target, .. } => {
1078 h(dst) || h(target)
1079 }
1080 Op::GetField { dst, obj, .. } => h(dst) || h(obj),
1081 Op::DestructureTuple { src, start, count } => h(src) || rng(*start, *count),
1082 Op::Jump { .. } | Op::ReturnNothing | Op::IterPop => false,
1083 Op::JumpIfFalse { cond, .. } | Op::JumpIfTrue { cond, .. } => h(cond),
1084 Op::IterPrepare { iterable } => h(iterable),
1085 Op::Sleep { duration } => h(duration),
1086 // Everything else — a Move/Concat producing a live copy, calls,
1087 // closures, spawns, channels, CRDTs, global stores, returns, struct/
1088 // tuple/inductive builders, Show, slices, deep-clones — could retain
1089 // or alias the collection. Fail closed.
1090 _ => true,
1091 }
1092 }
1093
1094 /// Back-edge hook for hot loops in ANY frame (`Jump` to an earlier pc):
1095 /// profile, compile when hot, and — when ready and the guard passes — run
1096 /// the region natively. `named`/`frame_regs` describe the ENCLOSING frame
1097 /// (Main's or a function's). `cur_func` is the enclosing function index (for
1098 /// the region-entry COW's mutable-param check). Returns the pc to resume at
1099 /// (the loop's exit).
1100 fn try_region(
1101 &mut self,
1102 head: usize,
1103 back_pc: usize,
1104 named: &[bool],
1105 frame_regs: usize,
1106 depth_now: usize,
1107 cur_func: Option<u16>,
1108 ) -> Option<RegionExit> {
1109 use super::native_tier::{RegionSlot, REGION_TIER_THRESHOLD};
1110 let tier = self.tier?;
1111 match self.regions.get(&head) {
1112 Some(RegionSlot::Failed) => return None,
1113 Some(RegionSlot::Ready { .. }) => {}
1114 None => {
1115 let n = self.region_hot.entry(head).or_insert(0);
1116 *n += 1;
1117 if *n < REGION_TIER_THRESHOLD {
1118 return None;
1119 }
1120 // Region extent: every jump leaving [head, back_pc] must
1121 // agree on ONE exit pc.
1122 let body = &self.program.code[head..=back_pc];
1123 let mut exit: Option<usize> = None;
1124 for op in body {
1125 if let Op::Jump { target }
1126 | Op::JumpIfFalse { target, .. }
1127 | Op::JumpIfTrue { target, .. } = *op
1128 {
1129 if !(head..=back_pc).contains(&target) {
1130 match exit {
1131 None => exit = Some(target),
1132 Some(e) if e == target => {}
1133 _ => {
1134 self.mark_region_failed(head);
1135 return None;
1136 }
1137 }
1138 }
1139 }
1140 }
1141 let Some(exit_pc) = exit else {
1142 self.mark_region_failed(head);
1143 return None;
1144 };
1145 // Value semantics: a region that mutates a collection IN PLACE
1146 // may be writing a SHARED (aliased) allocation — native code
1147 // writes through the `Rc` directly, a reference-semantics
1148 // miscompile. We tier it soundly by copy-on-write'ing each
1149 // mutated collection at region ENTRY (isolating it), PROVIDED no
1150 // mutated collection escapes the region (then entry-COW is not
1151 // enough — decline, run on the value-semantic VM). A `mutable`
1152 // param is intentionally shared with the caller, so its in-place
1153 // mutation is correct and it is NOT COW'd.
1154 let mut cow_regs: Vec<u16> = Vec::new();
1155 if crate::semantics::collections::value_semantics_enabled() {
1156 let mut mutated = Self::region_mutated_collection_regs(body);
1157 // A collection created FRESH in-region (its `NewEmpty` dominates
1158 // every mutation) is uniquely owned by construction: it needs no
1159 // entry-COW, and its register's earlier recycled-scratch uses no
1160 // longer read as a spurious alias-escape (the fannkuch `perm`
1161 // whose slot a `Set r to r-1` scratch reused before `perm` exists).
1162 for r in Self::region_fresh_collection_regs(body, head) {
1163 mutated.remove(&r);
1164 }
1165 if !mutated.is_empty() {
1166 if Self::region_mutation_escapes(body, &mutated) {
1167 self.mark_region_failed(head);
1168 return None;
1169 }
1170 let mutable_params = cur_func
1171 .and_then(|fi| self.program.functions.get(fi as usize))
1172 .map(|f| f.cow_exempt_regs.as_slice())
1173 .unwrap_or(&[]);
1174 cow_regs = mutated
1175 .into_iter()
1176 .filter(|r| !mutable_params.contains(r))
1177 .collect();
1178 }
1179 }
1180 let reg_count = u16::try_from(frame_regs).ok()?;
1181 // Speculation seed: the kinds sitting in this frame's
1182 // registers RIGHT NOW. The adapter compiles against them;
1183 // the guard set re-checks them on every entry.
1184 let observed: Vec<super::native_tier::ObservedKind> = (0..frame_regs)
1185 .map(|r| {
1186 use super::native_tier::ObservedKind;
1187 use crate::interpreter::{ListRepr, RuntimeValue};
1188 let rt = self.registers.get(self.base + r).map(|v| v.as_runtime());
1189 match rt.as_deref() {
1190 Some(RuntimeValue::Int(_)) => ObservedKind::Int,
1191 // A BigInt is a promoted (overflowed) integer — still an
1192 // integer kind, so the region tiers the slot as Int. The
1193 // entry guard re-checks the representation: a real BigInt in
1194 // an Int-guarded slot fails the guard and stays in the exact
1195 // VM, so the native i64 fast path is never entered with a box.
1196 Some(RuntimeValue::BigInt(_)) => ObservedKind::Int,
1197 Some(RuntimeValue::Float(_)) => ObservedKind::Float,
1198 Some(RuntimeValue::Bool(_)) => ObservedKind::Bool,
1199 Some(RuntimeValue::List(rc)) => match &*rc.borrow() {
1200 ListRepr::Ints(_) => ObservedKind::IntList,
1201 ListRepr::IntsI32(_) => ObservedKind::IntListI32,
1202 // A packed `Word32` list pins with the IntList buffer machinery (its masked
1203 // values are `i64`s); the forge tags an indexed read `Word32`.
1204 ListRepr::Words32(_) => ObservedKind::Word32List,
1205 ListRepr::Floats(_) => ObservedKind::FloatList,
1206 ListRepr::Bools(_) => ObservedKind::BoolList,
1207 ListRepr::Boxed(_)
1208 | ListRepr::Strings { .. }
1209 | ListRepr::Structs { .. }
1210 | ListRepr::Inductives { .. }
1211 | ListRepr::WireStructs { .. }
1212 | ListRepr::WireColumn { .. } => ObservedKind::Other,
1213 },
1214 Some(RuntimeValue::Map(_)) => ObservedKind::Map,
1215 // An ASCII Text rides the byte-pin lane (char index ==
1216 // byte index, char count == byte length). The metrics
1217 // cache makes the ASCII test O(1) per crossing. A
1218 // non-ASCII Text stays Other → the region bails and the
1219 // per-char decode path runs, so the JIT never diverges.
1220 Some(RuntimeValue::Text(rc))
1221 if crate::semantics::collections::text_is_ascii(rc) =>
1222 {
1223 ObservedKind::TextBytes
1224 }
1225 // A Word ring value carried unboxed as a masked i64 — lets a loop-carried Word
1226 // (a hash word `h0..h7`) enter the region as state. A narrow word's ring is
1227 // not a lane's: the region would wrap it at 2³², so it never enters unboxed.
1228 Some(RuntimeValue::Word(w)) => match w {
1229 logicaffeine_base::WordVal::W64(_) => ObservedKind::Word64,
1230 logicaffeine_base::WordVal::W32(_) => ObservedKind::Word32,
1231 logicaffeine_base::WordVal::W8(_)
1232 | logicaffeine_base::WordVal::W16(_) => ObservedKind::Other,
1233 },
1234 _ => ObservedKind::Other,
1235 }
1236 })
1237 .collect();
1238 let callees: Vec<super::native_tier::CalleeSig> = {
1239 let prog = &self.program;
1240 let code_len = prog.code.len();
1241 prog.functions
1242 .iter()
1243 .map(|f| {
1244 let end = prog
1245 .functions
1246 .iter()
1247 .map(|h| h.entry_pc)
1248 .filter(|&pc| pc > f.entry_pc)
1249 .min()
1250 .unwrap_or(code_len);
1251 let (list_params_stable, returns_list_param) = analyze_list_call_safety(
1252 &prog.code[f.entry_pc..end],
1253 f.param_count,
1254 &f.param_kinds,
1255 f.register_count,
1256 );
1257 super::native_tier::CalleeSig {
1258 param_kinds: f.param_kinds.clone(),
1259 inout_params: f
1260 .mutable_param_regs
1261 .iter()
1262 .copied()
1263 .filter(|r| !f.cow_exempt_regs.contains(r))
1264 .collect(),
1265 ret: f.ret_kind,
1266 list_ret: native_list_return(f.return_type.as_ref()),
1267 list_params_stable,
1268 returns_list_param,
1269 }
1270 })
1271 .collect()
1272 };
1273 // A fresh-list return normally REBINDS `dst`. The native
1274 // region adopts its contents into the destination's pinned
1275 // buffer, so isolate that buffer at entry like any other
1276 // in-place mutation to preserve value semantics for aliases.
1277 if crate::semantics::collections::value_semantics_enabled() {
1278 for op in body {
1279 let Op::Call { dst, func, .. } = *op else {
1280 continue;
1281 };
1282 if callees
1283 .get(func as usize)
1284 .is_some_and(|sig| sig.list_ret.is_some() && !sig.returns_list_param)
1285 && !cow_regs.contains(&dst)
1286 {
1287 cow_regs.push(dst);
1288 }
1289 }
1290 }
1291 // PRECISE REGION LIVE-OUT: a name bound INSIDE this loop is
1292 // lexically dead at the loop exit, so it must NOT be written
1293 // back — dropping it from `named` lets the JIT's copy-prop / CSE
1294 // / fusion treat it as true scratch. `loop_locals[head]` is the
1295 // compiler's exact per-loop set; absent (no loop record) keeps
1296 // the conservative full `named`.
1297 let liveout_off = std::env::var("LOGOS_LIVEOUT").as_deref() == Ok("0");
1298 if std::env::var_os("LOGOS_LIVEOUT_TRACE").is_some() {
1299 let ll = self.program.loop_locals.get(&head);
1300 let nnamed = named.iter().filter(|&&n| n).count();
1301 let freed = ll.map_or(0, |m| {
1302 named
1303 .iter()
1304 .enumerate()
1305 .filter(|(r, &n)| n && m.get(*r).copied().unwrap_or(false))
1306 .count()
1307 });
1308 eprintln!(
1309 "liveout-trace: head={head} named={nnamed} loop_locals={} freed={freed}",
1310 ll.is_some()
1311 );
1312 }
1313 let region_named: Vec<bool> = match self.program.loop_locals.get(&head) {
1314 Some(locals) if !liveout_off => named
1315 .iter()
1316 .enumerate()
1317 .map(|(r, &n)| n && !locals.get(r).copied().unwrap_or(false))
1318 .collect(),
1319 _ => named.to_vec(),
1320 };
1321 match tier.compile_region(
1322 body,
1323 head,
1324 exit_pc,
1325 &self.program.constants,
1326 reg_count,
1327 ®ion_named,
1328 &observed,
1329 &self.native_ctx,
1330 &callees,
1331 ) {
1332 Some(rf) => {
1333 #[cfg(not(target_arch = "wasm32"))]
1334 if super::perf_map::observed() {
1335 let enclosing = cur_func
1336 .map(|fi| self.fn_name(fi as usize))
1337 .unwrap_or_default();
1338 super::perf_map::record_code(
1339 &rf.code_extents(),
1340 &super::perf_map::region_symbol(&enclosing, head),
1341 );
1342 }
1343 self.regions.insert(
1344 head,
1345 RegionSlot::Ready {
1346 rf,
1347 exit_pc,
1348 misses: 0,
1349 },
1350 );
1351 if !cow_regs.is_empty() {
1352 self.region_cow_regs.insert(head, cow_regs);
1353 }
1354 }
1355 None => {
1356 self.mark_region_failed(head);
1357 return None;
1358 }
1359 }
1360 }
1361 }
1362 let result = self.run_ready_region(head, depth_now, cur_func);
1363 if result.is_none() {
1364 // Guard failure or side exit: count it; a region that keeps
1365 // missing re-runs work every entry — demote to pure bytecode.
1366 let mut demote = false;
1367 if let Some(RegionSlot::Ready { misses, .. }) = self.regions.get_mut(&head) {
1368 *misses += 1;
1369 if *misses >= super::native_tier::REGION_DEMOTE_AFTER {
1370 demote = true;
1371 }
1372 }
1373 if demote {
1374 self.mark_region_failed(head);
1375 }
1376 }
1377 result
1378 }
1379
1380 /// The Ready-path body of [`Vm::try_region`]: guards, pinning, the native
1381 /// run, and write-back. None = guard failure or side exit (the caller
1382 /// counts misses).
1383 fn run_ready_region(
1384 &mut self,
1385 head: usize,
1386 depth_now: usize,
1387 cur_func: Option<u16>,
1388 ) -> Option<RegionExit> {
1389 use super::native_tier::RegionSlot;
1390 // Region-entry copy-on-write: isolate each collection this region mutates
1391 // in place, so the native code's in-place writes cannot leak through a
1392 // shared `Rc`. A no-op when already uniquely owned; a one-time deep clone
1393 // when aliased. `mutable`-param collections were excluded at formation
1394 // (their sharing is intentional), so this only isolates value bindings.
1395 if let Some(regs) = self.region_cow_regs.get(&head) {
1396 for r in regs.clone() {
1397 self.ensure_reg_owned(r, head, cur_func);
1398 }
1399 }
1400 let Some(RegionSlot::Ready { rf, exit_pc, .. }) = self.regions.get(&head) else {
1401 unreachable!()
1402 };
1403 // Guard: every live-in slot must hold exactly the kind the region
1404 // speculated on; copy the raw representation in (floats as bits).
1405 {
1406 use super::native_tier::SlotKind;
1407 use crate::interpreter::RuntimeValue;
1408 for &(r, kind) in rf.guard_set() {
1409 let v = self.registers.get(self.base + r as usize)?;
1410 match (kind, &*v.as_runtime()) {
1411 (SlotKind::Int, RuntimeValue::Int(_)) => {}
1412 (SlotKind::Float, RuntimeValue::Float(_)) => {}
1413 (SlotKind::Bool, RuntimeValue::Bool(_)) => {}
1414 (SlotKind::Word32, RuntimeValue::Word(logicaffeine_base::WordVal::W32(_))) => {}
1415 (SlotKind::Word64, RuntimeValue::Word(logicaffeine_base::WordVal::W64(_))) => {}
1416 _ => return None,
1417 }
1418 }
1419 }
1420 // Frequently re-entered regions (sift-down loops) cannot afford a
1421 // heap allocation per entry — reuse one thread-local buffer.
1422 thread_local! {
1423 static REGION_FRAME: std::cell::RefCell<Vec<i64>> =
1424 const { std::cell::RefCell::new(Vec::new()) };
1425 }
1426 // `LOGOS_JIT_CANARY=1` guards the region frame with a sentinel
1427 // canary past its live span (`need` = frame proper + call-arena
1428 // headroom): any region-native write beyond `need` trips it loudly
1429 // at the source. Off by default (and in release) so normal runs
1430 // pay nothing.
1431 let frame_canary: usize = if jit_canary_enabled() { 64 } else { 0 };
1432 const FRAME_SENTINEL: i64 = 0x6262_6262_6262_6262u64 as i64;
1433 let need = rf.frame_size() + rf.arena_slots();
1434 let frame_cell = REGION_FRAME.with(|f| {
1435 let mut frame = f.take();
1436 // Zero only the region frame proper. The call-arena headroom is
1437 // REUSED untouched (16MiB for calling regions — zeroing it per
1438 // entry would memset megabytes every loop crossing): callee
1439 // chains write-before-read by the kind gates and the call
1440 // stencil plants each limit slot, so stale slots are
1441 // unobservable — the same contract as the function tier's
1442 // thread-local arena.
1443 if frame.len() < need + frame_canary {
1444 // Use the allocator's zero-filled path so the full safety
1445 // range is logically initialized without eagerly touching
1446 // every page. Native calls fault in only the recursion frames
1447 // they actually use.
1448 frame = vec![0; need + frame_canary];
1449 }
1450 frame[..rf.frame_size()].fill(0);
1451 for c in &mut frame[need..need + frame_canary] {
1452 *c = FRAME_SENTINEL;
1453 }
1454 frame
1455 });
1456 let mut frame = frame_cell;
1457 {
1458 use super::native_tier::SlotKind;
1459 use crate::interpreter::RuntimeValue;
1460 for &(r, kind) in rf.guard_set() {
1461 frame[r as usize] =
1462 match (kind, &*self.registers[self.base + r as usize].as_runtime()) {
1463 (SlotKind::Int, RuntimeValue::Int(n)) => *n,
1464 (SlotKind::Float, RuntimeValue::Float(f)) => f.to_bits() as i64,
1465 (SlotKind::Bool, RuntimeValue::Bool(b)) => *b as i64,
1466 // A Word rides UNBOXED as its masked value: W32 zero-extended (`0 ≤ x < 2³²`),
1467 // W64 the full bit pattern. Matches how `RegBox::Word{32,64}` re-boxes at exit.
1468 (
1469 SlotKind::Word32,
1470 RuntimeValue::Word(logicaffeine_base::WordVal::W32(w)),
1471 ) => w.0 as i64,
1472 (
1473 SlotKind::Word64,
1474 RuntimeValue::Word(logicaffeine_base::WordVal::W64(w)),
1475 ) => w.0 as i64,
1476 _ => unreachable!("guard verified the discriminant above"),
1477 };
1478 }
1479 }
1480 // Pin arrays: borrow each DISTINCT Rc once (held across the whole
1481 // native run — zero refcount/borrow traffic inside the loop), check
1482 // the speculated repr, and plant buffer pointer + length in the
1483 // dedicated frame slots. Aliased registers resolve to the same
1484 // buffer. Handles drop before write-back (in-place arrays need none;
1485 // the deopt replay is sound by prefix-idempotence).
1486 // The register-file base pointer, captured ONCE before any pin takes an
1487 // (immutable) borrow of `self.registers` through a list/map `Rc`. A
1488 // `TextMut` pin plants a `*mut Value` to a register CELL derived from
1489 // this pointer — the cell is stable across the native run (the register
1490 // file never reallocates while a region runs), so the append helper can
1491 // grow the accumulator through it. Reading/writing a cell through this
1492 // raw pointer does not conflict with the handles' shared borrows.
1493 let reg_base_ptr: *mut Value = self.registers.as_mut_ptr();
1494 let (outcome, text_mut_snapshots, array_rebindings, list_args) = {
1495 use crate::interpreter::{ListRepr, RuntimeValue};
1496 let pins = rf.array_set();
1497 // Entry identities for the small subset of pinned registers that
1498 // an in-region list `RevSwap` may rebind. The native loop swaps
1499 // only raw pin triples; after the live `RefMut`s drop we map those
1500 // final handles back to the original `Rc` values in O(pin count).
1501 // Calling regions also need these identities when a callee exits.
1502 // Ordinary array regions without calls or rebinds avoid the clones.
1503 let mut entry_pin_values: Vec<Option<Value>> = vec![None; pins.len()];
1504 let mut handles: Vec<(usize, std::cell::RefMut<'_, ListRepr>)> =
1505 Vec::with_capacity(pins.len());
1506 // Parallel to `handles`: a buffer is "mutated" if ANY pin aliasing it
1507 // writes in place under a deopt-capable, non-precise region — it needs
1508 // a full-content snapshot/restore across a classic replay deopt.
1509 let mut handle_mutated: Vec<bool> = Vec::with_capacity(pins.len());
1510 let mut map_handles: Vec<(
1511 usize,
1512 std::cell::RefMut<'_, crate::interpreter::MapStorage>,
1513 )> = Vec::new();
1514 // A pinned MUTABLE Text accumulator grows THROUGH the VM register
1515 // cell (the planted `*mut Value`). A classic replay-from-head Deopt
1516 // would re-run the appends the native prefix already landed in the
1517 // cell — a double-append — so snapshot each distinct accumulator's
1518 // entry `Value` and restore it before a classic `Deopt` replay
1519 // (precise regions resume at the faulting op and never replay, so
1520 // they keep the live grown value). `(register slot, entry Value)`.
1521 let mut text_mut_snapshots: Vec<(usize, Value)> = Vec::new();
1522 for (pin_index, pin) in pins.iter().enumerate() {
1523 if pin.elem == super::native_tier::PinElem::Map {
1524 let v = self.registers.get(self.base + pin.reg as usize)?;
1525 let Some(RuntimeValue::Map(rc)) = v.as_runtime_ref() else {
1526 return None;
1527 };
1528 let key = std::rc::Rc::as_ptr(rc) as usize;
1529 if !map_handles.iter().any(|(k, _)| *k == key) {
1530 let Ok(b) = rc.try_borrow_mut() else {
1531 return None;
1532 };
1533 map_handles.push((key, b));
1534 }
1535 let idx = map_handles.iter().position(|(k, _)| *k == key).unwrap();
1536 let storage = &mut *map_handles[idx].1;
1537 frame[pin.vec_slot as usize] =
1538 storage as *mut crate::interpreter::MapStorage as i64;
1539 frame[pin.ptr_slot as usize] = 0;
1540 frame[pin.len_slot as usize] = 0;
1541 continue;
1542 }
1543 if pin.elem == super::native_tier::PinElem::TextBytes {
1544 // A pinned ASCII Text rides its BYTE buffer: char index ==
1545 // byte index, char count == byte length. RE-CHECK ASCII at
1546 // every entry (the speculation seed is not a standing
1547 // guarantee — a region could be re-entered with a non-ASCII
1548 // Text in the same register) — decline (deopt to bytecode)
1549 // otherwise so the per-char decode path runs and the output
1550 // never diverges from the tree-walker. `Rc<String>` is
1551 // read-only (no RefCell): a TextBytes pin is never written,
1552 // so the snapshot/rollback machinery does not apply.
1553 let v = self.registers.get(self.base + pin.reg as usize)?;
1554 let Some(RuntimeValue::Text(rc)) = v.as_runtime_ref() else {
1555 return None;
1556 };
1557 if !crate::semantics::collections::text_is_ascii(rc) {
1558 return None;
1559 }
1560 frame[pin.vec_slot as usize] = 0;
1561 frame[pin.ptr_slot as usize] = rc.as_bytes().as_ptr() as i64;
1562 frame[pin.len_slot as usize] = rc.len() as i64;
1563 continue;
1564 }
1565 if pin.elem == super::native_tier::PinElem::TextMut {
1566 // A pinned MUTABLE Text accumulator: plant a `*mut Value` to
1567 // the VM REGISTER CELL (stable for the run; the `Rc<String>`
1568 // inside it reallocs/COWs on append). Decline (deopt to
1569 // bytecode) if the observed value is not a Text. Snapshot the
1570 // entry `Value` for the classic-Deopt rollback (one per
1571 // distinct accumulator register). The cell is reached through
1572 // `reg_base_ptr` (no `self.registers` borrow that would
1573 // conflict with the live list/map handles).
1574 if pin.reg as usize >= self.registers.len().saturating_sub(self.base) {
1575 return None;
1576 }
1577 let slot = self.base + pin.reg as usize;
1578 let cell: *mut Value = unsafe { reg_base_ptr.add(slot) };
1579 if !matches!(
1580 unsafe { (*cell).as_runtime_ref() },
1581 Some(RuntimeValue::Text(_))
1582 ) {
1583 return None;
1584 }
1585 if pin.mutated && !text_mut_snapshots.iter().any(|(s, _)| *s == slot) {
1586 text_mut_snapshots.push((slot, unsafe { (*cell).clone() }));
1587 }
1588 frame[pin.vec_slot as usize] = cell as i64;
1589 frame[pin.ptr_slot as usize] = 0;
1590 frame[pin.len_slot as usize] = 0;
1591 continue;
1592 }
1593 let v = self.registers.get(self.base + pin.reg as usize)?;
1594 let Some(RuntimeValue::List(rc)) = v.as_runtime_ref() else {
1595 return None;
1596 };
1597 if pin.rebound || rf.arena_slots() != 0 {
1598 entry_pin_values[pin_index] = Some(v.clone());
1599 }
1600 let key = std::rc::Rc::as_ptr(rc) as usize;
1601 if !handles.iter().any(|(k, _)| *k == key) {
1602 let Ok(b) = rc.try_borrow_mut() else {
1603 return None;
1604 };
1605 handles.push((key, b));
1606 handle_mutated.push(false);
1607 }
1608 let idx = handles.iter().position(|(k, _)| *k == key).unwrap();
1609 if pin.mutated {
1610 handle_mutated[idx] = true;
1611 }
1612 let payload = &mut *handles[idx].1;
1613 use super::native_tier::PinElem;
1614 let (vec_handle, ptr, len) = match (payload, pin.elem) {
1615 (ListRepr::Ints(v), PinElem::Int) => (
1616 v as *mut Vec<i64> as i64,
1617 v.as_mut_ptr() as *mut i64,
1618 v.len(),
1619 ),
1620 // A `Words32` buffer pins with the IntList machinery (8-byte masked elements).
1621 (ListRepr::Words32(v), PinElem::Word32) => (
1622 v as *mut Vec<i64> as i64,
1623 v.as_mut_ptr() as *mut i64,
1624 v.len(),
1625 ),
1626 (ListRepr::IntsI32(v), PinElem::IntI32) => (
1627 v as *mut Vec<i32> as i64,
1628 v.as_mut_ptr() as *mut i64,
1629 v.len(),
1630 ),
1631 // Maps never reach this arm (their pin path is below) —
1632 // a list register observed as Map is a guard failure.
1633 (_, PinElem::Map) => return None,
1634 (ListRepr::Floats(v), PinElem::Float) => (
1635 v as *mut Vec<f64> as i64,
1636 v.as_mut_ptr() as *mut i64,
1637 v.len(),
1638 ),
1639 (ListRepr::Bools(v), PinElem::Bool) => (
1640 v as *mut Vec<bool> as i64,
1641 v.as_mut_ptr() as *mut i64,
1642 v.len(),
1643 ),
1644 // Repr changed since compile (promotion) — guard failure.
1645 _ => return None,
1646 };
1647 frame[pin.vec_slot as usize] = vec_handle;
1648 frame[pin.ptr_slot as usize] = ptr as i64;
1649 frame[pin.len_slot as usize] = len as i64;
1650 // LEVER B calling-convention invariant (matches the function
1651 // tier): a list register's frame slot MIRRORS its vec handle, so
1652 // staging a pinned array into a call's argument window (a `Move`
1653 // from the register slot) passes the live `*mut Vec`, not the
1654 // zeroed register cell. Harmless for non-call regions (the slot
1655 // is never read for a pinned array, and the frame is discarded on
1656 // deopt — the VM register keeps the real Rc).
1657 frame[pin.reg as usize] = vec_handle;
1658 }
1659 let entry_pin_handles: Vec<i64> = pins
1660 .iter()
1661 .map(|pin| frame[pin.vec_slot as usize])
1662 .collect();
1663 // HOISTED bounds checks (V8 loop bound-check elimination): with
1664 // the pinned lengths in hand, verify ONCE that every covered loop
1665 // access stays in bounds for the whole run. Any failure declines
1666 // the region — the VM replays the loop on bytecode, where the
1667 // accesses are checked and produce the exact error.
1668 for hg in rf.hoist_guards() {
1669 let len = frame[hg.len_slot as usize];
1670 let bound = match &*self
1671 .registers
1672 .get(self.base + hg.bound_reg as usize)?
1673 .as_runtime()
1674 {
1675 RuntimeValue::Int(n) => *n,
1676 _ => return None,
1677 };
1678 let iv = match &*self
1679 .registers
1680 .get(self.base + hg.iv_reg as usize)?
1681 .as_runtime()
1682 {
1683 RuntimeValue::Int(n) => *n,
1684 _ => return None,
1685 };
1686 if len < bound.saturating_add(hg.add_max as i64)
1687 || iv.saturating_add(hg.add_min as i64) < 1
1688 {
1689 return None;
1690 }
1691 }
1692 // Entry lengths of every pinned list buffer — the rollback target
1693 // if a mid-region side-exit forces discard-and-replay. `ListPush`
1694 // APPENDS, so it is NOT replay-idempotent; on deopt each pushed
1695 // buffer is truncated back to its entry length before the VM
1696 // replays the loop on bytecode, which then re-pushes cleanly
1697 // instead of duplicating. Read-only and in-place (SetIndex) buffers
1698 // keep their entry length, so the truncate is a no-op for them.
1699 let entry_lens: Vec<usize> = handles.iter().map(|(_, h)| h.len()).collect();
1700 // A buffer written IN PLACE (SetIndex) replays unsoundly under the
1701 // classic discard-replay deopt — the write already landed in the
1702 // SHARED buffer, so the bytecode replay-from-head double-applies it
1703 // (a read-modify-write or swap is not idempotent). Snapshot its full
1704 // contents on entry; a classic `Deopt` restores them (subsuming the
1705 // length, so a buffer that BOTH pushes and writes in place is covered
1706 // too). Push-only / read-only buffers keep the cheap length truncate.
1707 let entry_snapshots: Vec<Option<ListRepr>> = handles
1708 .iter()
1709 .zip(handle_mutated.iter())
1710 .map(|((_, h), &mt)| if mt { Some((**h).clone()) } else { None })
1711 .collect();
1712 let out = rf.run_with_callees(&mut frame[..need], depth_now, &|fi| match self
1713 .native
1714 .get(fi as usize)
1715 {
1716 Some(super::native_tier::NativeSlot::Ready(nf)) => Some(nf.as_ref()),
1717 _ => None,
1718 });
1719 if matches!(out, super::native_tier::RegionOutcome::Deopt) {
1720 for (((_, h), &n), snap) in handles
1721 .iter_mut()
1722 .zip(entry_lens.iter())
1723 .zip(entry_snapshots.into_iter())
1724 {
1725 match snap {
1726 Some(s) => **h = s,
1727 None => h.truncate(n),
1728 }
1729 }
1730 }
1731 // The list/map handles drop here, releasing their `self.registers`
1732 // borrows; the text-accumulator rollback (which needs `&mut
1733 // self.registers`) runs after the block, gated on a classic Deopt.
1734 let mut array_rebindings = Vec::new();
1735 if !matches!(out, super::native_tier::RegionOutcome::Deopt) {
1736 for pin in pins.iter().filter(|pin| pin.rebound) {
1737 let final_handle = frame[pin.vec_slot as usize];
1738 let Some(source) = entry_pin_handles
1739 .iter()
1740 .position(|entry| *entry == final_handle)
1741 else {
1742 return None;
1743 };
1744 let Some(value) = entry_pin_values[source].clone() else {
1745 return None;
1746 };
1747 array_rebindings.push((self.base + pin.reg as usize, value));
1748 }
1749 }
1750 let list_args = if matches!(out, super::native_tier::RegionOutcome::DeoptCall { .. }) {
1751 pins.iter()
1752 .map(|pin| {
1753 let handle = frame[pin.vec_slot as usize];
1754 entry_pin_handles
1755 .iter()
1756 .position(|h| *h == handle)
1757 .and_then(|i| entry_pin_values[i].clone())
1758 .unwrap_or_else(Value::nothing)
1759 })
1760 .collect()
1761 } else {
1762 Vec::new()
1763 };
1764 (out, text_mut_snapshots, array_rebindings, list_args)
1765 };
1766 // Roll each pinned mutable-Text accumulator back to its entry `Value` on
1767 // a classic Deopt so the bytecode replay-from-head re-appends from the
1768 // pre-region prefix instead of doubling the native prefix's appends (the
1769 // appends landed directly in the VM register cell). Precise side exits
1770 // and successful completions keep the live grown value.
1771 if matches!(outcome, super::native_tier::RegionOutcome::Deopt) {
1772 for (slot, snap) in text_mut_snapshots {
1773 self.registers[slot] = snap;
1774 }
1775 }
1776 // A successful list `RevSwap` changes which original `Rc` each list
1777 // register names. Apply that identity-only rebind after every list
1778 // borrow has dropped. Precise deopt keeps the completed native prefix,
1779 // so it needs the same rebind; classic replay deliberately does not.
1780 for (slot, value) in array_rebindings {
1781 self.registers[slot] = value;
1782 }
1783 for (k, c) in frame[need..need + frame_canary].iter().enumerate() {
1784 assert_eq!(
1785 *c, FRAME_SENTINEL,
1786 "REGION_FRAME OVERFLOW: canary slot {k} (frame + {}) clobbered by region native code",
1787 need + k
1788 );
1789 }
1790 let (outcome, callee_exit) = match outcome {
1791 super::native_tier::RegionOutcome::DeoptCall {
1792 call_pc,
1793 resume_pc,
1794 frames,
1795 } => (
1796 super::native_tier::RegionOutcome::DeoptAt { resume_pc: call_pc },
1797 Some((call_pc, resume_pc, frames)),
1798 ),
1799 other => (other, None),
1800 };
1801 match outcome {
1802 super::native_tier::RegionOutcome::DeoptCall { .. } => unreachable!(),
1803 super::native_tier::RegionOutcome::Completed => {}
1804 // Side exit: discard the private frame — VM registers still hold
1805 // the state of this back-edge crossing, so falling back to
1806 // bytecode re-runs the remaining iterations deterministically up
1807 // to the faulting op and raises the exact kernel error there.
1808 // (In-place array writes already landed; the replay recomputes
1809 // the same prefix values, so they are unobservable.)
1810 super::native_tier::RegionOutcome::Deopt => return None,
1811 // PRECISE side exit (push+SetIndex regions): the buffers were NOT
1812 // truncated (the truncate above is gated on `Deopt`), so completed
1813 // iterations' pushes and in-place writes stand. Materialize every
1814 // touched non-array scalar — all-int by the adapter's gate — from
1815 // the frame into the VM registers, then resume the bytecode AT the
1816 // faulting op (NOT the loop head): the faulting op re-runs exactly
1817 // once, raising the precise error or continuing, with no replay of
1818 // the completed prefix. Array handle registers keep their live Rc
1819 // (the region mutated through their pins).
1820 super::native_tier::RegionOutcome::DeoptAt { resume_pc } => {
1821 use super::native_tier::SlotKind;
1822 // Re-box each touched register by ITS kind at the faulting op
1823 // (from the region's kind flow): Int/Bool/Float from the frame's
1824 // raw bits; `None` keeps the VM register's current value (a
1825 // pinned array mutated in place, or a read-only/unknown slot).
1826 // Cloned so the `rf` borrow ends before the register writes.
1827 let kinds: Option<Vec<Option<SlotKind>>> =
1828 rf.precise_kinds(resume_pc).map(|k| k.to_vec());
1829 let mut regs: Vec<u16> = rf
1830 .guard_set()
1831 .iter()
1832 .map(|(r, _)| *r)
1833 .chain(rf.free_set().iter().copied())
1834 .chain(rf.write_set().iter().map(|(r, _)| *r))
1835 .collect();
1836 regs.sort_unstable();
1837 regs.dedup();
1838 for r in regs {
1839 let bits = frame[r as usize];
1840 let v = match kinds
1841 .as_ref()
1842 .and_then(|k| k.get(r as usize).copied().flatten())
1843 {
1844 Some(SlotKind::Int) => Value::int(bits),
1845 Some(SlotKind::Bool) => Value::bool(bits != 0),
1846 Some(SlotKind::Float) => Value::float(f64::from_bits(bits as u64)),
1847 Some(SlotKind::CharText) => Value::text(
1848 char::from_u32(bits as u32)
1849 .map(|c| c.to_string())
1850 .unwrap_or_default(),
1851 ),
1852 Some(SlotKind::Word32) => {
1853 Value::from_runtime(crate::interpreter::RuntimeValue::Word(
1854 logicaffeine_base::WordVal::W32(logicaffeine_base::Word32(
1855 bits as u32,
1856 )),
1857 ))
1858 }
1859 Some(SlotKind::Word64) => {
1860 Value::from_runtime(crate::interpreter::RuntimeValue::Word(
1861 logicaffeine_base::WordVal::W64(logicaffeine_base::Word64(
1862 bits as u64,
1863 )),
1864 ))
1865 }
1866 None => continue,
1867 };
1868 self.set(r, v);
1869 }
1870 REGION_FRAME.with(|f| f.replace(frame));
1871 return Some(match callee_exit {
1872 Some((call_pc, resume_pc, frames)) => RegionExit::Call {
1873 call_pc,
1874 resume_pc,
1875 frames,
1876 list_args,
1877 },
1878 None => RegionExit::At(resume_pc),
1879 });
1880 }
1881 }
1882 let writes: Vec<(u16, super::native_tier::SlotKind)> = rf.write_set().to_vec();
1883 let region_return = rf.region_return();
1884 let exit = *exit_pc;
1885 for (r, kind) in writes {
1886 use super::native_tier::SlotKind;
1887 let bits = frame[r as usize];
1888 let v = match kind {
1889 SlotKind::Int => Value::int(bits),
1890 SlotKind::Bool => Value::bool(bits != 0),
1891 SlotKind::Float => Value::float(f64::from_bits(bits as u64)),
1892 SlotKind::CharText => Value::text(
1893 char::from_u32(bits as u32)
1894 .map(|c| c.to_string())
1895 .unwrap_or_default(),
1896 ),
1897 SlotKind::Word32 => Value::from_runtime(crate::interpreter::RuntimeValue::Word(
1898 logicaffeine_base::WordVal::W32(logicaffeine_base::Word32(bits as u32)),
1899 )),
1900 SlotKind::Word64 => Value::from_runtime(crate::interpreter::RuntimeValue::Word(
1901 logicaffeine_base::WordVal::W64(logicaffeine_base::Word64(bits as u64)),
1902 )),
1903 };
1904 self.set(r, v);
1905 }
1906 let result = match region_return {
1907 Some(rr) if frame[rr.flag_slot as usize] != 0 => {
1908 use super::native_tier::{RegionReturnKind, SlotKind};
1909 let bits = frame[rr.value_slot as usize];
1910 let v = match rr.kind {
1911 RegionReturnKind::Slot(SlotKind::Int) => Value::int(bits),
1912 RegionReturnKind::Slot(SlotKind::Bool) => Value::bool(bits != 0),
1913 RegionReturnKind::Slot(SlotKind::Float) => {
1914 Value::float(f64::from_bits(bits as u64))
1915 }
1916 RegionReturnKind::Slot(SlotKind::CharText) => Value::text(
1917 char::from_u32(bits as u32)
1918 .map(|c| c.to_string())
1919 .unwrap_or_default(),
1920 ),
1921 RegionReturnKind::Slot(SlotKind::Word32) => {
1922 Value::from_runtime(crate::interpreter::RuntimeValue::Word(
1923 logicaffeine_base::WordVal::W32(logicaffeine_base::Word32(bits as u32)),
1924 ))
1925 }
1926 RegionReturnKind::Slot(SlotKind::Word64) => {
1927 Value::from_runtime(crate::interpreter::RuntimeValue::Word(
1928 logicaffeine_base::WordVal::W64(logicaffeine_base::Word64(bits as u64)),
1929 ))
1930 }
1931 RegionReturnKind::Register => self.reg(bits as u16).clone(),
1932 };
1933 RegionExit::Return(v)
1934 }
1935 _ => RegionExit::At(exit),
1936 };
1937 REGION_FRAME.with(|f| f.replace(frame));
1938 Some(result)
1939 }
1940
1941 /// Install a native tier: hot functions in the integer subset run as
1942 /// JIT-compiled machine code, guarded per call (non-Int args deopt to
1943 /// the bytecode path).
1944 pub fn with_native_tier(mut self, tier: &'p dyn super::native_tier::NativeTier) -> Self {
1945 self.tier = Some(tier);
1946 self
1947 }
1948
1949 /// Pre-install an AOT-native function for `fi` (HOTSWAP §Axis-3): the VM dispatches
1950 /// to it via the existing `NativeSlot::Ready` path from the first call (it is not
1951 /// `Untried`, so it skips the hotness threshold and the forge compile). Requires a
1952 /// native tier to be installed (the dispatch is gated on `self.tier`); on desktop
1953 /// the forge tier is always present alongside. Absent ⇒ the function stays on
1954 /// VM+JIT — the AOT artifact is strictly optional, no gap at the seam.
1955 #[cfg(not(target_arch = "wasm32"))]
1956 pub fn install_aot_native(&mut self, fi: usize, nf: Box<dyn super::native_tier::NativeFn>) {
1957 if fi < self.native.len() {
1958 let name = self.fn_name(fi);
1959 super::tier_trace::trace_transition(fi, &name, super::tier_trace::ExecTier::NativeAot);
1960 self.native[fi] = super::native_tier::NativeSlot::Ready(nf);
1961 }
1962 }
1963
1964 /// Copy-on-write for value semantics (VM side; mirrors the tree-walker's
1965 /// `ensure_collection_owned`). Before mutating the collection in register `reg`
1966 /// at `pc`, deep-clone it if another holder shares the allocation (`Rc` strong
1967 /// count > 1). Only a proven consumed-and-returned borrow is exempt. In-out
1968 /// parameters copy their final values back and still isolate local copies.
1969 ///
1970 /// A holder that is a DEAD scratch register of this frame is not a holder: the
1971 /// statement that read the collection into it has finished with it, and nothing
1972 /// will read it again ([`Vm::release_dead_aliases`]). Counting it would deep-clone
1973 /// on every read-then-write of a collection — `Let v be item i of xs.` followed
1974 /// by `Set item i of xs to v + 1.` would copy the whole list each time round.
1975 ///
1976 /// Nor is the module-level binding the value is about to be written back into
1977 /// ([`Vm::put_back_global`]): mutating a global's collection reads it into a
1978 /// register, mutates the register, and stores it back, so the mutation in place IS
1979 /// the global's own. The global keeps its reference throughout — every mutating op
1980 /// either completes or fails before it writes — so a trap leaves it intact.
1981 fn ensure_reg_owned(&mut self, reg: Reg, pc: usize, cur_func: Option<u16>) {
1982 if !crate::semantics::collections::value_semantics_enabled() {
1983 return;
1984 }
1985 if self.is_cow_exempt(reg, cur_func) {
1986 return;
1987 }
1988 let di = self.base + reg as usize;
1989 let Some(target) = shared_collection(&self.registers[di]) else {
1990 return;
1991 };
1992 self.release_dead_aliases(reg, pc, cur_func);
1993 let returning = self.put_back_global(reg, pc).is_some_and(|g| {
1994 self.globals
1995 .get(g as usize)
1996 .and_then(|v| v.as_ref())
1997 .and_then(collection_ptr)
1998 == Some(target)
1999 });
2000 if holder_count(&self.registers[di]) <= 1 + usize::from(returning) {
2001 return;
2002 }
2003 let owned = self.registers[di].as_runtime().deep_clone();
2004 self.registers[di] = Value::from_runtime(owned);
2005 }
2006
2007 /// Whether ownership analysis proved that this register can be mutated
2008 /// without preserving another value held by the program.
2009 fn is_cow_exempt(&self, reg: Reg, cur_func: Option<u16>) -> bool {
2010 cur_func
2011 .and_then(|fi| self.program.functions.get(fi as usize))
2012 .is_some_and(|f| f.cow_exempt_regs.contains(®))
2013 }
2014
2015 /// Copy-on-write for a record's list field: when another value shares the list the `field` of
2016 /// the record in `reg` holds — a copy of the record, the caller's record behind a plain
2017 /// parameter — the record in `reg` takes a list of its own (one level, as the tree-walker's
2018 /// `own_collection` does) before a write reaches it.
2019 fn own_struct_field_list(&mut self, reg: Reg, field: &str, pc: usize, cur_func: Option<u16>) {
2020 use crate::interpreter::RuntimeValue;
2021 use std::rc::Rc;
2022 let slot = self.base + reg as usize;
2023 let shared = match self.registers[slot].as_runtime_ref() {
2024 Some(RuntimeValue::Struct(s)) => matches!(s.fields.get(field),
2025 Some(RuntimeValue::List(rc)) if Rc::strong_count(rc) > 1),
2026 _ => false,
2027 };
2028 if shared {
2029 // A dead projection or record temporary can still hold this field.
2030 // Release those temporaries before deciding whether a real second
2031 // owner requires a copy. Named and live registers remain intact.
2032 self.release_dead_scratch(Some(reg), pc, cur_func, None);
2033 }
2034 if let RuntimeValue::Struct(s) = self.registers[slot].as_runtime_mut() {
2035 if let Some(RuntimeValue::List(rc)) = s.fields.get_mut(field) {
2036 if Rc::strong_count(rc) > 1 || Rc::weak_count(rc) > 0 {
2037 self.record_field_copy_work.0 = self.record_field_copy_work.0.saturating_add(1);
2038 self.record_field_copy_work.1 = self
2039 .record_field_copy_work
2040 .1
2041 .saturating_add(rc.borrow().len());
2042 let own = rc.borrow().clone();
2043 *rc = Rc::new(std::cell::RefCell::new(own));
2044 }
2045 }
2046 }
2047 }
2048
2049 /// [`Vm::own_struct_field_list`] for every list field of the record in `reg`; nothing for any
2050 /// other value.
2051 fn own_struct_fields(&mut self, reg: Reg, pc: usize, cur_func: Option<u16>) {
2052 use crate::interpreter::RuntimeValue;
2053 let fields: Vec<String> = match &*self.reg(reg).as_runtime() {
2054 RuntimeValue::Struct(s) => s
2055 .fields
2056 .iter()
2057 .filter(|(_, v)| matches!(v, RuntimeValue::List(_)))
2058 .map(|(k, _)| k.clone())
2059 .collect(),
2060 _ => return,
2061 };
2062 for field in fields {
2063 self.own_struct_field_list(reg, &field, pc, cur_func);
2064 }
2065 }
2066
2067 /// The global the value in `reg` is stored back into right after the mutation at `pc` —
2068 /// the first `GlobalSet` of `reg` that follows in straight-line code, with nothing in
2069 /// between that could read a global or run other code. `None` when none follows.
2070 fn put_back_global(&self, reg: Reg, pc: usize) -> Option<u16> {
2071 for op in self.program.code.get(pc + 1..)? {
2072 match *op {
2073 Op::GlobalSet { idx, src } if src == reg => return Some(idx),
2074 Op::GlobalGet { .. }
2075 | Op::Call { .. }
2076 | Op::CallValue { .. }
2077 | Op::CallBuiltin { .. }
2078 | Op::Jump { .. }
2079 | Op::JumpIfFalse { .. }
2080 | Op::JumpIfTrue { .. }
2081 | Op::Return { .. }
2082 | Op::ReturnNothing
2083 | Op::Halt => return None,
2084 _ => {}
2085 }
2086 }
2087 None
2088 }
2089
2090 /// Release every DEAD scratch register of the current frame that references the
2091 /// same collection as `reg` — unnamed (no binding owns it) and not live entering
2092 /// `pc` ([`FrameLiveness`]), so no path reads it again before writing it.
2093 ///
2094 /// The compiler reuses scratch registers statement by statement but never clears
2095 /// them, so a read like `item i of xs` leaves a copy of `xs`'s reference in the
2096 /// scratch register the read went through until something else lands there.
2097 /// Releasing it here, on the path that was about to copy the whole collection
2098 /// anyway, costs one scan of the frame and nothing on the path that does not copy.
2099 fn release_dead_aliases(&mut self, reg: Reg, pc: usize, cur_func: Option<u16>) {
2100 let Some(target) = shared_collection(&self.registers[self.base + reg as usize]) else {
2101 return;
2102 };
2103 self.release_dead_scratch(Some(reg), pc, cur_func, Some(target));
2104 }
2105
2106 /// Release provably dead unnamed temporaries. Collection mutations may
2107 /// restrict this to direct aliases; a record field can also be retained
2108 /// inside an otherwise dead record temporary, so its ownership gate clears
2109 /// all dead scratch values. The active target and every program binding stay.
2110 fn release_dead_scratch(
2111 &mut self,
2112 keep: Option<Reg>,
2113 pc: usize,
2114 cur_func: Option<u16>,
2115 target: Option<usize>,
2116 ) {
2117 let Some(live) = self.frame_liveness(pc, cur_func) else {
2118 return;
2119 };
2120 let named: &[bool] = match cur_func {
2121 None => &self.program.named_regs,
2122 Some(f) => self
2123 .program
2124 .functions
2125 .get(f as usize)
2126 .map_or(&[][..], |f| &f.named_regs[..]),
2127 };
2128 let regs = live.words * 64;
2129 for r in 0..regs.min(self.registers.len().saturating_sub(self.base)) {
2130 let r = r as Reg;
2131 if keep == Some(r)
2132 || named.get(r as usize).copied().unwrap_or(true)
2133 || live.is_live(pc, r)
2134 {
2135 continue;
2136 }
2137 let slot = self.base + r as usize;
2138 if target.is_none_or(|target| collection_ptr(&self.registers[slot]) == Some(target)) {
2139 self.registers[slot] = Value::nothing();
2140 }
2141 }
2142 }
2143
2144 /// The liveness of the region `pc` lies in, when that region is the current frame's:
2145 /// Main's for a frame with no function, the function's own otherwise. `None` for a pc
2146 /// in re-optimized warm code or a layout that does not resolve — no register is known
2147 /// dead there.
2148 fn frame_liveness(
2149 &mut self,
2150 pc: usize,
2151 cur_func: Option<u16>,
2152 ) -> Option<std::rc::Rc<FrameLiveness>> {
2153 let program = self.program;
2154 let layout = self
2155 .code_layout
2156 .get_or_insert_with(|| super::reach::code_layout(program).ok())
2157 .as_ref()?;
2158 let (start, end, regs) = match cur_func {
2159 None => (0, layout.main_end, program.register_count),
2160 Some(f) => {
2161 let (start, end) = *layout.func_region.get(f as usize)?;
2162 (
2163 start,
2164 end,
2165 program.functions.get(f as usize)?.register_count,
2166 )
2167 }
2168 };
2169 if !(start..end).contains(&pc) {
2170 return None;
2171 }
2172 Some(
2173 self.liveness
2174 .entry(start)
2175 .or_insert_with(|| std::rc::Rc::new(FrameLiveness::of(program, start, end, regs)))
2176 .clone(),
2177 )
2178 }
2179
2180 /// Null this call's argument-window registers after it returns. Dead once the
2181 /// call is over, but as the callee's params they persist below `restore_len`;
2182 /// left set, a collection argument keeps a live `Rc` clone in the caller frame
2183 /// that spuriously inflates `strong_count` and forces later copy-on-write. Zero
2184 /// `arg_count` (native/scheduler frames) does nothing.
2185 ///
2186 /// A `mutable` parameter's slot is kept: it holds the value the callee last bound there, which
2187 /// the caller takes back into the binding it passed (the compiler's copy-out after the call).
2188 #[inline]
2189 fn clear_arg_window(&mut self, frame: &CallFrame) {
2190 let end = (frame.arg_lo + frame.arg_count as usize).min(self.registers.len());
2191 let kept = self
2192 .program
2193 .functions
2194 .get(frame.func as usize)
2195 .map_or(&[][..], |f| &f.mutable_param_regs[..]);
2196 for slot in frame.arg_lo..end {
2197 if !kept.contains(&((slot - frame.arg_lo) as Reg)) {
2198 self.registers[slot] = Value::nothing();
2199 }
2200 }
2201 }
2202
2203 /// Same as [`Vm::clear_arg_window`] for a call that completes INLINE (a native /
2204 /// WASM / builtin dispatch that never pushes a `CallFrame`): the argument window
2205 /// starts at the current base's `args_start`.
2206 /// A `mutable` parameter's slot of a user function `func` is kept, as in
2207 /// [`Vm::clear_arg_window`].
2208 #[inline]
2209 fn clear_args(&mut self, args_start: Reg, arg_count: u16, func: Option<u16>) {
2210 let lo = self.base + args_start as usize;
2211 let end = (lo + arg_count as usize).min(self.registers.len());
2212 let kept = func
2213 .and_then(|f| self.program.functions.get(f as usize))
2214 .map_or(&[][..], |f| &f.mutable_param_regs[..]);
2215 for slot in lo..end {
2216 if !kept.contains(&((slot - lo) as Reg)) {
2217 self.registers[slot] = Value::nothing();
2218 }
2219 }
2220 }
2221
2222 /// Resolve a function's source name for the tier trace; empty when no interner is
2223 /// available (the trace then prints just the index).
2224 /// Publish a forge-compiled native body for function `fi`: its entry in the program's `FnTable`,
2225 /// the `LOGOS_TIER_TRACE` line, the `LOGOS_PERF_MAP` symbol and `LOGOS_JIT_CODE` bytes, and the `Ready` slot.
2226 fn install_forge_native(&mut self, fi: usize, nf: Box<dyn super::native_tier::NativeFn>) {
2227 self.native_ctx
2228 .table
2229 .publish(fi, nf.entry_ptr(), nf.published_regc());
2230 let name = self.fn_name(fi);
2231 super::tier_trace::trace_transition(fi, &name, super::tier_trace::ExecTier::NativeForge);
2232 #[cfg(not(target_arch = "wasm32"))]
2233 super::perf_map::record_code(&nf.code_extents(), &super::perf_map::function_symbol(&name));
2234 self.native[fi] = super::native_tier::NativeSlot::Ready(nf);
2235 }
2236
2237 fn fn_name(&self, fi: usize) -> String {
2238 match (self.program.functions.get(fi), self.policy_ctx) {
2239 (Some(f), Some((_, interner))) => interner.resolve(f.name).to_string(),
2240 _ => String::new(),
2241 }
2242 }
2243
2244 /// Install the process tier AND a background compiler (HOTSWAP §6): hot functions
2245 /// are compiled on a worker thread instead of stalling the interpreter. The tier
2246 /// must be `&'static` (the process-installed forge backend) so it can cross to the
2247 /// worker — `&'static dyn NativeTier` is `Send` because `NativeTier: Sync`. The
2248 /// interpreter still runs the chains and is the sole `FnTable` writer; the worker
2249 /// only compiles. Falls back to [`Vm::with_native_tier`] (synchronous) for a
2250 /// borrowed `&'p` tier, which cannot be shared with a thread.
2251 #[cfg(not(target_arch = "wasm32"))]
2252 pub fn with_bg_native_tier(
2253 mut self,
2254 tier: &'static dyn super::native_tier::NativeTier,
2255 ) -> Self {
2256 self.tier = Some(tier);
2257 self.bg = Some(super::bg_compile::BgCompiler::new(tier));
2258 self
2259 }
2260
2261 /// Apply every background-compiled result that has come back: publish the native
2262 /// entry to the `FnTable` and flip the slot to `Ready` (or `Failed`). The
2263 /// interpreter is the sole `FnTable` writer, so this only ever runs on this
2264 /// thread, at the profiling points. No-op when there is no background compiler.
2265 #[cfg(not(target_arch = "wasm32"))]
2266 fn drain_bg_compiles(&mut self) {
2267 use super::bg_compile::CompileResult;
2268 use super::native_tier::NativeSlot;
2269 loop {
2270 let res = match self.bg.as_mut() {
2271 Some(b) => b.try_drain(),
2272 None => return,
2273 };
2274 let Some(res) = res else { return };
2275 match res {
2276 CompileResult::Function { fi, nf } => match nf {
2277 Some(nf) => self.install_forge_native(fi, nf),
2278 None => self.native[fi] = NativeSlot::Failed,
2279 },
2280 }
2281 }
2282 }
2283
2284 /// Block until every outstanding background compile has come back and been
2285 /// published — the determinism hook the differential tests use so the native tier
2286 /// engages predictably regardless of thread scheduling. No-op without a background
2287 /// compiler.
2288 #[cfg(not(target_arch = "wasm32"))]
2289 pub fn drain_pending_compiles(&mut self) {
2290 use super::bg_compile::CompileResult;
2291 use super::native_tier::NativeSlot;
2292 let results = match self.bg.as_mut() {
2293 Some(b) => b.drain_blocking(),
2294 None => return,
2295 };
2296 for res in results {
2297 match res {
2298 CompileResult::Function { fi, nf } => match nf {
2299 Some(nf) => self.install_forge_native(fi, nf),
2300 None => self.native[fi] = NativeSlot::Failed,
2301 },
2302 }
2303 }
2304 }
2305
2306 /// Supply the program arguments read by the `args()` system native. The
2307 /// vector is the full argv (index 0 is the program name), matching the
2308 /// compiled binary's `env::args()`.
2309 pub fn with_program_args(mut self, args: Vec<String>) -> Self {
2310 self.program_args = crate::semantics::argv_with_program_name(args);
2311 self
2312 }
2313
2314 /// A new instance of the same program, configured as this one was (native tier, policy
2315 /// context, argument vector), with nothing run and no global set — what a browser has after
2316 /// a page reload re-instantiates the module.
2317 pub fn reinstantiate(&self) -> Vm<'p> {
2318 let mut vm = Vm::new(self.program);
2319 vm.tier = self.tier;
2320 vm.policy_ctx = self.policy_ctx;
2321 vm.accel_pbkdf2 = self.accel_pbkdf2;
2322 vm.program_args = self.program_args.clone();
2323 vm
2324 }
2325
2326 /// Tier dispatch for `Call`: Some(result) = the native fast path ran.
2327 /// Precise-deopt frame materialization — deliberately OUT of the
2328 /// dispatch loop (cold path; keeping its body inline bloats the hot
2329 /// match and costs i-cache on every dispatched op).
2330 #[cold]
2331 #[inline(never)]
2332 #[allow(clippy::too_many_arguments)]
2333 fn materialize_native_frames(
2334 &mut self,
2335 frames: &[super::native_tier::NativeFrame],
2336 list_args: &[Value],
2337 args_start: super::instruction::Reg,
2338 dst: super::instruction::Reg,
2339 func: u16,
2340 return_pc: usize,
2341 call_stack: &mut Vec<CallFrame>,
2342 ) -> Result<(), String> {
2343 use super::native_tier::RegBox;
2344 let mut frame_base = self.base + args_start as usize;
2345 let mut caller_base = self.base;
2346 for (k, fr) in frames.iter().enumerate() {
2347 if k > 0 {
2348 caller_base = frame_base;
2349 let Some(Op::Call { args_start, .. }) = self.program.code.get(fr.return_pc - 1)
2350 else {
2351 return Err("vm: native frame has no call-site arguments".to_string());
2352 };
2353 frame_base += *args_start as usize;
2354 }
2355 let restore_len = self.registers.len();
2356 let needed = frame_base + fr.regs.len();
2357 if needed > MAX_REGISTER_FILE {
2358 return Err("vm: register file limit exceeded".to_string());
2359 }
2360 if self.registers.len() < needed {
2361 self.registers.resize(needed, Value::nothing());
2362 }
2363 call_stack.push(CallFrame {
2364 return_pc: if k == 0 { return_pc } else { fr.return_pc },
2365 return_reg: if k == 0 { dst } else { fr.return_reg },
2366 caller_base,
2367 restore_len,
2368 iter_depth: self.iter_stack.len(),
2369 func,
2370 arg_lo: frame_base,
2371 arg_count: self.program.functions[func as usize].param_count,
2372 });
2373 for (r, bits) in fr.regs.iter().enumerate() {
2374 let v = match fr.kinds[r] {
2375 RegBox::Dead | RegBox::Resolved => continue,
2376 RegBox::Nothing => Value::nothing(),
2377 RegBox::Int => Value::int(*bits),
2378 RegBox::Bool => Value::bool(*bits != 0),
2379 RegBox::Float => Value::float(f64::from_bits(*bits as u64)),
2380 RegBox::Word32 => Value::from_runtime(crate::interpreter::RuntimeValue::Word(
2381 logicaffeine_base::WordVal::W32(logicaffeine_base::Word32(*bits as u32)),
2382 )),
2383 RegBox::Word64 => Value::from_runtime(crate::interpreter::RuntimeValue::Word(
2384 logicaffeine_base::WordVal::W64(logicaffeine_base::Word64(*bits as u64)),
2385 )),
2386 // The producing `ChrGuard` deopts on an invalid code, so this scalar is always valid.
2387 RegBox::CharText => Value::text(
2388 char::from_u32(*bits as u32)
2389 .map(|c| c.to_string())
2390 .unwrap_or_default(),
2391 ),
2392 RegBox::ListParam(j) => match list_args.get(j as usize) {
2393 Some(v) => v.clone(),
2394 None => return Err("vm: deopt pin index out of range".to_string()),
2395 },
2396 };
2397 self.registers[frame_base + r] = v;
2398 }
2399 for (r, v) in &fr.resolved {
2400 self.registers[frame_base + *r as usize] = v.clone();
2401 }
2402 }
2403 self.base = frame_base;
2404 Ok(())
2405 }
2406
2407 fn try_native(
2408 &mut self,
2409 func: u16,
2410 args_start: super::instruction::Reg,
2411 arg_count: u16,
2412 bytecode_depth: usize,
2413 ) -> NativeDisposition {
2414 use super::native_tier::{NativeSlot, ParamKind, NATIVE_TIER_THRESHOLD};
2415 let Some(tier) = self.tier else {
2416 return NativeDisposition::Interpret;
2417 };
2418 let fi = func as usize;
2419 // Publish any background-compiled chains that have come back (sole writer).
2420 #[cfg(not(target_arch = "wasm32"))]
2421 self.drain_bg_compiles();
2422 match self.native.get(fi) {
2423 None | Some(NativeSlot::Failed) => return NativeDisposition::Interpret,
2424 // Background compile in flight — keep running bytecode until it lands.
2425 Some(NativeSlot::Pending) => return NativeDisposition::Interpret,
2426 _ => {}
2427 }
2428 if matches!(self.native[fi], NativeSlot::Untried) {
2429 self.hot[fi] += 1;
2430 if self.hot[fi] < NATIVE_TIER_THRESHOLD {
2431 return NativeDisposition::Interpret;
2432 }
2433 let f = &self.program.functions[fi];
2434 if !f.captures.is_empty() {
2435 crate::optimize::mark_backend_fallback(
2436 crate::optimization::OptimizationBackend::Vm,
2437 "function captures values outside the forge ABI",
2438 );
2439 self.native[fi] = NativeSlot::Failed;
2440 return NativeDisposition::Interpret;
2441 }
2442 // A parameter whose declared type has no native representation
2443 // (Map, Text, nested Seq, …) can never enter native code —
2444 // fail once instead of bumping the hot counter forever.
2445 if f.param_kinds.iter().any(|k| k.is_none()) {
2446 crate::optimize::mark_backend_fallback(
2447 crate::optimization::OptimizationBackend::Vm,
2448 "function parameter has no forge representation",
2449 );
2450 self.native[fi] = NativeSlot::Failed;
2451 return NativeDisposition::Interpret;
2452 }
2453 // The VM/JIT boundary marshals arguments in a fixed stack buffer.
2454 // Refuse once at tier-up instead of silently retrying bytecode.
2455 if f.param_count as usize > 16 {
2456 crate::optimize::mark_backend_fallback(
2457 crate::optimization::OptimizationBackend::Vm,
2458 "function has more than 16 forge arguments",
2459 );
2460 self.native[fi] = NativeSlot::Failed;
2461 return NativeDisposition::Interpret;
2462 }
2463 let end = self
2464 .program
2465 .functions
2466 .iter()
2467 .map(|g| g.entry_pc)
2468 .filter(|&e| e > f.entry_pc)
2469 .min()
2470 .unwrap_or(self.program.code.len());
2471 let callees: Vec<super::native_tier::CalleeSig> = {
2472 let prog = &self.program;
2473 let code_len = prog.code.len();
2474 prog.functions
2475 .iter()
2476 .map(|g| {
2477 let end = prog
2478 .functions
2479 .iter()
2480 .map(|h| h.entry_pc)
2481 .filter(|&pc| pc > g.entry_pc)
2482 .min()
2483 .unwrap_or(code_len);
2484 let (list_params_stable, returns_list_param) = analyze_list_call_safety(
2485 &prog.code[g.entry_pc..end],
2486 g.param_count,
2487 &g.param_kinds,
2488 g.register_count,
2489 );
2490 super::native_tier::CalleeSig {
2491 param_kinds: g.param_kinds.clone(),
2492 inout_params: g
2493 .mutable_param_regs
2494 .iter()
2495 .copied()
2496 .filter(|r| !g.cow_exempt_regs.contains(r))
2497 .collect(),
2498 ret: g.ret_kind,
2499 list_ret: native_list_return(g.return_type.as_ref()),
2500 list_params_stable,
2501 returns_list_param,
2502 }
2503 })
2504 .collect()
2505 };
2506 // With a background compiler, ship the compile off-thread and keep
2507 // running bytecode (HOTSWAP §6); the result is drained + published on a
2508 // later call. Without one (a borrowed `&'p` tier, or wasm), compile
2509 // synchronously — the retained fallback.
2510 #[cfg(not(target_arch = "wasm32"))]
2511 if self.bg.is_some() {
2512 let req = super::bg_compile::CompileRequest::Function(
2513 super::bg_compile::FunctionRequest {
2514 fi,
2515 code: self.program.code[f.entry_pc..end].to_vec(),
2516 entry_pc: f.entry_pc,
2517 constants: std::sync::Arc::from(self.program.constants.clone()),
2518 enums: std::sync::Arc::from(self.program.enum_types.clone()),
2519 param_count: f.param_count,
2520 register_count: f.register_count as u16,
2521 param_kinds: f.param_kinds.clone(),
2522 cow_exempt_regs: f.cow_exempt_regs.clone(),
2523 ret_kind: f.ret_kind,
2524 callees,
2525 ctx: self.native_ctx.clone(),
2526 },
2527 );
2528 self.bg.as_mut().unwrap().submit(req);
2529 self.native[fi] = NativeSlot::Pending;
2530 return NativeDisposition::Interpret;
2531 }
2532 match tier.compile_function(
2533 &self.program.code[f.entry_pc..end],
2534 f.entry_pc,
2535 &self.program.constants,
2536 &self.program.enum_types,
2537 f.param_count,
2538 f.register_count as u16,
2539 func,
2540 &f.param_kinds,
2541 &f.cow_exempt_regs,
2542 f.ret_kind,
2543 &self.native_ctx,
2544 &callees,
2545 ) {
2546 Some(nf) => self.install_forge_native(fi, nf),
2547 None => {
2548 self.native[fi] = NativeSlot::Failed;
2549 return NativeDisposition::Interpret;
2550 }
2551 }
2552 }
2553 // The per-call guard: every argument must match its DECLARED kind
2554 // (floats travel as raw bits in the i64 slot; lists pin), else the
2555 // call stays interpreted.
2556 let base = self.base + args_start as usize;
2557 // Hot boundary: a stack buffer instead of a per-call Vec — functions
2558 // like gcd cross bytecode→native hundreds of thousands of times.
2559 if arg_count as usize > 16 {
2560 return NativeDisposition::Interpret;
2561 }
2562 let kinds = &self.program.functions[fi].param_kinds;
2563 let mut args = [0i64; 16];
2564 for k in 0..arg_count as usize {
2565 let Some(v) = self.registers.get(base + k) else {
2566 return NativeDisposition::Interpret;
2567 };
2568 args[k] = match kinds.get(k).copied().flatten() {
2569 Some(ParamKind::Scalar(super::native_tier::SlotKind::Int)) | None => {
2570 match v.as_int() {
2571 Some(n) => n,
2572 None => return NativeDisposition::Interpret,
2573 }
2574 }
2575 Some(ParamKind::Scalar(super::native_tier::SlotKind::Bool)) => match v.as_bool() {
2576 Some(b) => b as i64,
2577 None => return NativeDisposition::Interpret,
2578 },
2579 Some(ParamKind::Scalar(super::native_tier::SlotKind::Float)) => {
2580 match v.as_float() {
2581 Some(f) => f.to_bits() as i64,
2582 None => return NativeDisposition::Interpret,
2583 }
2584 }
2585 // `CharText` is a forge-only write-back carrier, never a declared param type; if one ever
2586 // reaches here, decline to the interpreter (there is no Text → code-point entry marshalling).
2587 Some(ParamKind::Scalar(super::native_tier::SlotKind::CharText)) => {
2588 return NativeDisposition::Interpret;
2589 }
2590 // A Word param arrives UNBOXED as its masked value (W32 zero-extended, W64 full bits) — the
2591 // same carrier the region-internal Word ops use; a mismatched width declines to the VM.
2592 Some(ParamKind::Scalar(super::native_tier::SlotKind::Word32)) => {
2593 match v.as_runtime_ref() {
2594 Some(crate::interpreter::RuntimeValue::Word(
2595 logicaffeine_base::WordVal::W32(w),
2596 )) => w.0 as i64,
2597 _ => return NativeDisposition::Interpret,
2598 }
2599 }
2600 Some(ParamKind::Scalar(super::native_tier::SlotKind::Word64)) => {
2601 match v.as_runtime_ref() {
2602 Some(crate::interpreter::RuntimeValue::Word(
2603 logicaffeine_base::WordVal::W64(w),
2604 )) => w.0 as i64,
2605 _ => return NativeDisposition::Interpret,
2606 }
2607 }
2608 // List params ride the pin lane; the register slot is a
2609 // placeholder native code never reads as a scalar.
2610 Some(ParamKind::List(_)) => 0,
2611 // An enum node is lent for the call: this register keeps it alive until the call ends.
2612 Some(ParamKind::Inductive) => match v.as_runtime_ref() {
2613 Some(crate::interpreter::RuntimeValue::Inductive(node)) => {
2614 std::rc::Rc::as_ptr(node) as i64
2615 }
2616 _ => return NativeDisposition::Interpret,
2617 },
2618 };
2619 }
2620 // Pin list parameters: one borrow per DISTINCT Rc for the whole
2621 // call (recursion reuses the same pins via pass-through identity).
2622 // Empty lists retag in place to the declared element repr.
2623 let output_slots: Vec<u16> = self.program.functions[fi]
2624 .mutable_param_regs
2625 .iter()
2626 .copied()
2627 .filter(|r| *r < arg_count && !self.program.functions[fi].cow_exempt_regs.contains(r))
2628 .collect();
2629 let mut writeback = Vec::new();
2630 let outcome = {
2631 use super::native_tier::PinElem;
2632 use crate::interpreter::{ListRepr, RuntimeValue};
2633 let mut handles: Vec<(usize, std::cell::RefMut<'_, ListRepr>)> = Vec::new();
2634 let mut pins: Vec<i64> = Vec::new();
2635 let mut pin_args: Vec<Value> = Vec::new();
2636 for (k, pk) in kinds.iter().enumerate().take(arg_count as usize) {
2637 let Some(ParamKind::List(elem)) = pk else {
2638 continue;
2639 };
2640 let Some(v) = self.registers.get(base + k) else {
2641 return NativeDisposition::Interpret;
2642 };
2643 let Some(RuntimeValue::List(rc)) = v.as_runtime_ref() else {
2644 return NativeDisposition::Interpret;
2645 };
2646 pin_args.push(v.clone());
2647 let key = std::rc::Rc::as_ptr(rc) as usize;
2648 if !handles.iter().any(|(hk, _)| *hk == key) {
2649 let Ok(mut b) = rc.try_borrow_mut() else {
2650 return NativeDisposition::Interpret;
2651 };
2652 // Declared-elem retag for the empty list (the shared
2653 // empty starts as Ints).
2654 let empty = match &*b {
2655 ListRepr::Ints(v) => v.is_empty(),
2656 _ => false,
2657 };
2658 if empty {
2659 match elem {
2660 PinElem::Float => *b = ListRepr::Floats(Vec::new()),
2661 PinElem::Bool => *b = ListRepr::Bools(Vec::new()),
2662 PinElem::IntI32 => *b = ListRepr::IntsI32(Vec::new()),
2663 PinElem::Word32 => *b = ListRepr::Words32(Vec::new()),
2664 PinElem::Int => {}
2665 // Function params never pin maps or texts (declared
2666 // kinds only produce Int/Float/Bool list elems).
2667 PinElem::Map | PinElem::TextBytes | PinElem::TextMut => {
2668 return NativeDisposition::Interpret
2669 }
2670 }
2671 }
2672 handles.push((key, b));
2673 }
2674 let idx = handles.iter().position(|(hk, _)| *hk == key).unwrap();
2675 let payload = &mut *handles[idx].1;
2676 let (vec_handle, ptr, len) = match (payload, elem) {
2677 (ListRepr::Ints(v), PinElem::Int) => {
2678 (v as *mut Vec<i64> as i64, v.as_mut_ptr() as i64, v.len())
2679 }
2680 (ListRepr::IntsI32(v), PinElem::IntI32) => {
2681 (v as *mut Vec<i32> as i64, v.as_mut_ptr() as i64, v.len())
2682 }
2683 // A `Words32` buffer pins with the IntList (`Vec<i64>`) machinery — 8-byte elements.
2684 (ListRepr::Words32(v), PinElem::Word32) => {
2685 (v as *mut Vec<i64> as i64, v.as_mut_ptr() as i64, v.len())
2686 }
2687 (ListRepr::Floats(v), PinElem::Float) => {
2688 (v as *mut Vec<f64> as i64, v.as_mut_ptr() as i64, v.len())
2689 }
2690 (ListRepr::Bools(v), PinElem::Bool) => {
2691 (v as *mut Vec<bool> as i64, v.as_mut_ptr() as i64, v.len())
2692 }
2693 _ => return NativeDisposition::Interpret,
2694 };
2695 pins.push(vec_handle);
2696 pins.push(ptr);
2697 pins.push(len as i64);
2698 // The marshalled argument slot mirrors the vec handle —
2699 // native list registers always carry their handle.
2700 args[k] = vec_handle;
2701 }
2702 let NativeSlot::Ready(nf) = &self.native[fi] else {
2703 unreachable!()
2704 };
2705 let args_slice = &args[..arg_count as usize];
2706 // The native callee occupies one LOGOS frame on top of the
2707 // bytecode stack; its self-calls count from there against
2708 // MAX_CALL_DEPTH.
2709 let out = nf.call_with_writeback(
2710 args_slice,
2711 &pins,
2712 bytecode_depth + 1,
2713 &output_slots,
2714 &mut writeback,
2715 );
2716 drop(handles);
2717 (out, pin_args, pins)
2718 };
2719 let (out, pin_args, pins_for_ret) = outcome;
2720 if matches!(
2721 &out,
2722 super::native_tier::NativeOutcome::Return(_)
2723 | super::native_tier::NativeOutcome::ReturnValue(_)
2724 ) {
2725 for (slot, written) in writeback {
2726 use super::native_tier::{NativeWriteback, SlotKind};
2727 let value = match written {
2728 NativeWriteback::Value(value) => value,
2729 NativeWriteback::Raw(raw) => match kinds[slot as usize] {
2730 Some(ParamKind::Scalar(SlotKind::Int)) => Value::int(raw),
2731 Some(ParamKind::Scalar(SlotKind::Bool)) => Value::bool(raw != 0),
2732 Some(ParamKind::Scalar(SlotKind::Float)) => {
2733 Value::float(f64::from_bits(raw as u64))
2734 }
2735 Some(ParamKind::Scalar(SlotKind::Word32)) => {
2736 Value::from_runtime(crate::interpreter::RuntimeValue::Word(
2737 logicaffeine_base::WordVal::W32(logicaffeine_base::Word32(
2738 raw as u32,
2739 )),
2740 ))
2741 }
2742 Some(ParamKind::Scalar(SlotKind::Word64)) => {
2743 Value::from_runtime(crate::interpreter::RuntimeValue::Word(
2744 logicaffeine_base::WordVal::W64(logicaffeine_base::Word64(
2745 raw as u64,
2746 )),
2747 ))
2748 }
2749 Some(ParamKind::Scalar(SlotKind::CharText)) => Value::text(
2750 char::from_u32(raw as u32)
2751 .map(|c| c.to_string())
2752 .unwrap_or_default(),
2753 ),
2754 Some(ParamKind::List(_)) => {
2755 let index = pins_for_ret.chunks(3)
2756 .position(|pin| pin.first() == Some(&raw))
2757 .expect("native mutable output must own its list or return a boundary pin");
2758 pin_args[index].clone()
2759 }
2760 Some(ParamKind::Inductive) => {
2761 unreachable!("the native tier keeps a function with an in-out enum parameter on the VM")
2762 }
2763 None => unreachable!(
2764 "native mutable output passed the declared-kind entry guard"
2765 ),
2766 },
2767 };
2768 self.registers[base + slot as usize] = value;
2769 }
2770 }
2771
2772 let NativeSlot::Ready(nf) = &self.native[fi] else {
2773 unreachable!()
2774 };
2775 match out {
2776 // The backend already re-boxed (list-returning functions own
2777 // their allocation registry).
2778 super::native_tier::NativeOutcome::ReturnValue(v) => NativeDisposition::Done(v),
2779 super::native_tier::NativeOutcome::Return(raw) => {
2780 NativeDisposition::Done(match nf.ret() {
2781 super::native_tier::NativeRet::Scalar(k) => match k {
2782 super::native_tier::SlotKind::Bool => Value::bool(raw != 0),
2783 super::native_tier::SlotKind::Float => {
2784 Value::float(f64::from_bits(raw as u64))
2785 }
2786 super::native_tier::SlotKind::Int => Value::int(raw),
2787 super::native_tier::SlotKind::CharText => Value::text(
2788 char::from_u32(raw as u32)
2789 .map(|c| c.to_string())
2790 .unwrap_or_default(),
2791 ),
2792 super::native_tier::SlotKind::Word32 => {
2793 Value::from_runtime(crate::interpreter::RuntimeValue::Word(
2794 logicaffeine_base::WordVal::W32(logicaffeine_base::Word32(
2795 raw as u32,
2796 )),
2797 ))
2798 }
2799 super::native_tier::SlotKind::Word64 => {
2800 Value::from_runtime(crate::interpreter::RuntimeValue::Word(
2801 logicaffeine_base::WordVal::W64(logicaffeine_base::Word64(
2802 raw as u64,
2803 )),
2804 ))
2805 }
2806 },
2807 // By-handle return that was NOT registry-owned: it is
2808 // one of the caller's list arguments — match the pin
2809 // handles (every triple's first slot) and clone that
2810 // argument, preserving identity.
2811 super::native_tier::NativeRet::ListByHandle => {
2812 let mut found: Option<Value> = None;
2813 for (k, chunk) in pins_for_ret.chunks(3).enumerate() {
2814 if chunk.first() == Some(&raw) {
2815 found = pin_args.get(k).cloned();
2816 break;
2817 }
2818 }
2819 match found {
2820 Some(v) => v,
2821 None => return NativeDisposition::Interpret,
2822 }
2823 }
2824 // SAFETY: `NativeRet::Inductive` hands back an `Rc::into_raw` pointer carrying one strong
2825 // count of its own, which this `Rc` takes over.
2826 super::native_tier::NativeRet::Inductive => {
2827 Value::from_runtime(crate::interpreter::RuntimeValue::Inductive(unsafe {
2828 std::rc::Rc::from_raw(raw as *const crate::interpreter::InductiveValue)
2829 }))
2830 }
2831 // Return-by-parameter: the result IS the caller's list
2832 // argument (same Rc — identity preserved).
2833 super::native_tier::NativeRet::ListParam(j) => {
2834 let mut nth = 0usize;
2835 let mut found: Option<Value> = None;
2836 for (k, pk) in kinds.iter().enumerate().take(arg_count as usize) {
2837 if matches!(pk, Some(ParamKind::List(_))) {
2838 if k == j as usize {
2839 found = pin_args.get(nth).cloned();
2840 break;
2841 }
2842 nth += 1;
2843 }
2844 }
2845 match found {
2846 Some(v) => v,
2847 None => return NativeDisposition::Interpret,
2848 }
2849 }
2850 })
2851 }
2852 // Plain side exit: every effect was confined to the private
2853 // frame — replaying the whole call on bytecode is sound and
2854 // raises the exact kernel error at the exact point.
2855 super::native_tier::NativeOutcome::Deopt => NativeDisposition::Interpret,
2856 // Precise side exit: effects landed; materialize the chain.
2857 super::native_tier::NativeOutcome::DeoptAt { resume_pc, frames } => {
2858 NativeDisposition::Materialize {
2859 resume_pc,
2860 frames,
2861 list_args: pin_args,
2862 }
2863 }
2864 }
2865 }
2866
2867 /// Provide the policy registry (and the interner its symbols live in) for
2868 /// `Check` statements.
2869 pub fn with_policy_ctx(
2870 mut self,
2871 registry: &'p crate::analysis::PolicyRegistry,
2872 interner: &'p crate::intern::Interner,
2873 ) -> Self {
2874 self.policy_ctx = Some((registry, interner));
2875 // Resolve the pbkdf2Sha256 acceleration handle now that the interner is available — only
2876 // when that function IS crypto.lg's definition (`loader::is_library_function`): the native
2877 // reference is byte-identical to the library body (crypto_accel_lock.rs), and to nothing
2878 // else. A program's own `pbkdf2Sha256` runs as written.
2879 self.accel_pbkdf2 = crate::loader::is_library_function("pbkdf2Sha256")
2880 .then(|| {
2881 self.program
2882 .functions
2883 .iter()
2884 .position(|f| interner.resolve(f.name) == "pbkdf2Sha256")
2885 .map(|i| i as FuncIdx)
2886 })
2887 .flatten();
2888 self
2889 }
2890
2891 /// The program this machine runs.
2892 pub fn program(&self) -> &'p CompiledProgram {
2893 self.program
2894 }
2895
2896 /// The output lines, one per `Show`.
2897 pub fn lines(&self) -> &[String] {
2898 &self.lines
2899 }
2900
2901 /// The output as one string (one trailing newline per `Show`).
2902 pub fn output(&self) -> String {
2903 let mut s = String::new();
2904 for l in &self.lines {
2905 s.push_str(l);
2906 s.push('\n');
2907 }
2908 s
2909 }
2910
2911 /// Consume the VM, returning its output lines.
2912 pub fn into_lines(self) -> Vec<String> {
2913 self.lines
2914 }
2915
2916 /// Take this slice's output lines (the scheduler driver merges each task's
2917 /// output into a shared sink as it is produced, preserving per-task order).
2918 pub(crate) fn drain_lines(&mut self) -> Vec<String> {
2919 std::mem::take(&mut self.lines)
2920 }
2921
2922 /// Run the whole program to completion (the non-concurrent entry). A
2923 /// concurrent program never reaches here — it is driven through
2924 /// `Vm::run_until_block` by the scheduler.
2925 pub fn run(&mut self) -> Result<(), String> {
2926 // Hermetic program start: no ambient exchange rates carried in from a prior run on this
2927 // thread (mirrors a fresh AOT process), and a stream of its own for the document the run
2928 // draws into. The resumable `run_until_block` path is left alone so rates installed
2929 // mid-program survive across concurrency suspensions.
2930 logicaffeine_base::money::clear_ambient_rates();
2931 crate::semantics::dom::retire_stream();
2932 match self.run_until_block()? {
2933 VmStep::Done(_) => Ok(()),
2934 VmStep::Blocked => Err("vm: concurrency op requires the scheduler driver".to_string()),
2935 VmStep::Paused => unreachable!("run_until_block (STEPPED = false) never pauses"),
2936 }
2937 }
2938
2939 /// The `Stmt::Site` id in force at the pc a failed run's `Err` propagated from (Wave 3:
2940 /// "runtime failures carry a location") — `None` outside any component's action/handler
2941 /// (`## Main`/`## Test` own top-level statements, which have no marker), or when the failing pc
2942 /// lies in a hot-swapped warm body `site_at` was never built to cover. Reads `sched_pc`, which
2943 /// `run_until_block_impl`'s dispatch loop saves before every op — the last write it sees before
2944 /// an `Err` from that op propagates via `?` straight out of the loop, so this is only meaningful
2945 /// to call once the caller already has that `Err` in hand; a successful run's `sched_pc` is
2946 /// simply wherever the loop happened to stop.
2947 pub fn failing_site(&self) -> Option<u32> {
2948 if let Some(site) = self.ended_at_site {
2949 return site;
2950 }
2951 if self.sched_pc >= self.program.code.len() {
2952 return None;
2953 }
2954 let idx = self
2955 .program
2956 .site_at
2957 .partition_point(|&(pc, _)| pc as usize <= self.sched_pc);
2958 if idx == 0 {
2959 return None;
2960 }
2961 let (_, id) = self.program.site_at[idx - 1];
2962 (id != crate::vm::instruction::NO_SITE).then_some(id)
2963 }
2964
2965 /// Call function `fi` from the host, after the program has run: what a browser does when it
2966 /// calls one of a module's exports. The call enters through the same path `Op::Call` takes
2967 /// (native tier, warm body, baseline) and runs against the globals the program left behind.
2968 ///
2969 /// An `Err` is the callee's failure, and it leaves the machine idle and callable with every
2970 /// global exactly as the failure found it — a wasm trap unwinds to the host the same way.
2971 pub fn invoke_function(
2972 &mut self,
2973 fi: FuncIdx,
2974 args: Vec<crate::interpreter::RuntimeValue>,
2975 ) -> Result<crate::interpreter::RuntimeValue, String> {
2976 let f = self
2977 .program
2978 .functions
2979 .get(fi as usize)
2980 .ok_or_else(|| format!("vm: no function at index {fi}"))?;
2981 if args.len() != f.param_count as usize {
2982 let name = match self.fn_name(fi as usize) {
2983 n if n.is_empty() => format!("function #{fi}"),
2984 n => format!("`{n}`"),
2985 };
2986 return Err(format!(
2987 "{name} expects {} arguments, got {}",
2988 f.param_count,
2989 args.len()
2990 ));
2991 }
2992 self.host_call(args, |vm, args_start, arg_count, return_pc, stack| {
2993 vm.enter_call::<false>(0, fi, args_start, arg_count, return_pc, stack)
2994 })
2995 }
2996
2997 /// Call a closure value from the host: what a browser does when it fires a handler the module
2998 /// handed it earlier (a fetch completion, a listener, a route handler). Same failure contract
2999 /// as [`Vm::invoke_function`].
3000 pub fn call_closure(
3001 &mut self,
3002 callee: &crate::interpreter::RuntimeValue,
3003 args: Vec<crate::interpreter::RuntimeValue>,
3004 ) -> Result<crate::interpreter::RuntimeValue, String> {
3005 let closure = match callee {
3006 crate::interpreter::RuntimeValue::Function(c) => (**c).clone(),
3007 other => return Err(format!("Cannot call value of type {}", other.type_name())),
3008 };
3009 self.host_call(args, |vm, args_start, arg_count, return_pc, stack| {
3010 vm.enter_closure::<false>(0, &closure, args_start, arg_count, return_pc, stack)
3011 })
3012 }
3013
3014 /// Bring a machine whose run stopped on a failure back to the idle state a host call starts
3015 /// from: Main's own frame, no open iterator, nothing suspended. Globals and output keep
3016 /// whatever the failure left, as a trapped wasm instance keeps its memory.
3017 pub(super) fn quiesce(&mut self) {
3018 self.base = 0;
3019 self.registers.truncate(self.program.register_count);
3020 self.iter_stack.clear();
3021 self.sched_active = false;
3022 self.sched_call_stack.clear();
3023 self.pending = None;
3024 self.resume_slot = None;
3025 self.resume_wraps_option = false;
3026 self.select_pending.clear();
3027 }
3028
3029 /// Run one host-initiated call to completion on top of the idle machine.
3030 ///
3031 /// The host frame sits past the register file's live end: one register the callee returns
3032 /// into, then the argument window, so the callee's frame is laid out exactly as if a caller
3033 /// had executed `Op::Call`. Its return pc is `program.code.len()`, where the dispatch loop
3034 /// stops once the call stack is empty. Whatever the outcome, the register file, the base and
3035 /// the iterator stack go back to what they were, so neither a clean return nor a trap leaves
3036 /// anything behind for the next call.
3037 fn host_call(
3038 &mut self,
3039 args: Vec<crate::interpreter::RuntimeValue>,
3040 enter: impl FnOnce(&mut Self, Reg, u16, usize, &mut Vec<CallFrame>) -> Result<usize, String>,
3041 ) -> Result<crate::interpreter::RuntimeValue, String> {
3042 if self.sched_active || self.pending.is_some() {
3043 return Err(
3044 "vm: a host call needs an idle machine, and this one is suspended mid-run"
3045 .to_string(),
3046 );
3047 }
3048 let arg_count =
3049 u16::try_from(args.len()).map_err(|_| "vm: too many arguments".to_string())?;
3050 let saved_base = self.base;
3051 let saved_iters = self.iter_stack.len();
3052 let host_base = self.registers.len();
3053 if host_base + 1 + args.len() > MAX_REGISTER_FILE {
3054 return Err("vm: register file limit exceeded".to_string());
3055 }
3056 self.registers.push(Value::nothing());
3057 self.registers
3058 .extend(args.into_iter().map(Value::from_runtime));
3059 self.base = host_base;
3060 let finish = self.program.code.len();
3061 let mut stack: Vec<CallFrame> = Vec::new();
3062 let outcome = match enter(self, 1, arg_count, finish, &mut stack) {
3063 Ok(_) if stack.is_empty() => Ok(()),
3064 Ok(pc) => {
3065 self.sched_pc = pc;
3066 self.sched_call_stack = stack;
3067 self.sched_active = true;
3068 match self.run_until_block_impl::<false, false>(u64::MAX) {
3069 Ok(VmStep::Done(_)) => Ok(()),
3070 Ok(VmStep::Blocked) => {
3071 Err("vm: concurrency op requires the scheduler driver".to_string())
3072 }
3073 Ok(VmStep::Paused) => {
3074 unreachable!("run_until_block (STEPPED = false) never pauses")
3075 }
3076 Err(e) => Err(e),
3077 }
3078 }
3079 Err(e) => Err(e),
3080 };
3081 let result = outcome.map(|()| {
3082 std::mem::replace(&mut self.registers[host_base], Value::nothing()).into_runtime()
3083 });
3084 self.base = saved_base;
3085 self.registers.truncate(host_base);
3086 self.iter_stack.truncate(saved_iters);
3087 self.sched_active = false;
3088 self.sched_call_stack.clear();
3089 self.pending = None;
3090 self.resume_slot = None;
3091 self.resume_wraps_option = false;
3092 self.select_pending.clear();
3093 result
3094 }
3095
3096 /// Run forward to completion WITH reversibility recording, capturing the history tape (retrieve
3097 /// it with [`Vm::take_journal`], then reconstruct the pre-run state with [`Vm::run_reverse`]).
3098 ///
3099 /// A cold path (verification / adiabatic reverse execution): the production [`Vm::run`]
3100 /// monomorph (`RECORDING = false`) dead-strips every recording block, so the 2.5×-C hot loop is
3101 /// byte-for-byte unchanged — this method merely instantiates a *separate* `RECORDING = true`
3102 /// copy of the loop that prod never calls. Declines with a clear error (never a silent
3103 /// mis-reverse) if the program uses an op outside the currently-reversible subset
3104 /// ([`crate::vm::reverse::is_reversible_supported`]).
3105 pub fn run_recording(&mut self) -> Result<(), String> {
3106 self.run_recording_mode(super::reverse::ReverseMode::Observable)
3107 }
3108
3109 /// Like [`Vm::run_recording`] but at an explicit [`ReverseMode`](super::reverse::ReverseMode) —
3110 /// the pebbling fidelity ⇄ space ⇄ time point. `FullState` journals every destroyed value;
3111 /// `Observable`/`Adiabatic` compute a per-pc [`plan`](super::pebble::plan) and skip journaling
3112 /// scratch the reverse never reads, shrinking the tape toward the Landauer floor.
3113 pub fn run_recording_mode(&mut self, mode: super::reverse::ReverseMode) -> Result<(), String> {
3114 if let Some(op) = self
3115 .program
3116 .code
3117 .iter()
3118 .find(|op| !super::reverse::is_reversible_supported(op))
3119 {
3120 return Err(match super::reverse::external_effect_barrier(op) {
3121 // A truly-external effect: name the irreversibility barrier (internal state up to it
3122 // reverses; the effect itself cannot be un-done) — never a silent lie.
3123 Some(barrier) => format!(
3124 "vm: `{}` is an irreversible {barrier} effect — not yet reversible past the honest Landauer wall (an external effect cannot be un-done)",
3125 op.name()
3126 ),
3127 None => format!("vm: op `{}` is not yet reversible", op.name()),
3128 });
3129 }
3130 logicaffeine_base::money::clear_ambient_rates();
3131 self.install_reverse_recording(mode);
3132 match self.run_until_block_impl::<false, true>(u64::MAX)? {
3133 VmStep::Done(_) => Ok(()),
3134 VmStep::Blocked => Err("vm: concurrency op requires the scheduler driver".to_string()),
3135 VmStep::Paused => unreachable!("run_until_block (STEPPED = false) never pauses"),
3136 }
3137 }
3138
3139 /// Like [`Vm::run_recording_mode`] but with an explicit pebble CHECKPOINT budget (corner 2):
3140 /// `budget` recomputable chain intermediates are kept journaled, so a reverse read stops its
3141 /// re-walk at the nearest checkpoint instead of the chain root. `budget = 0` is exactly
3142 /// [`Vm::run_recording_mode`] (the recompute-everything corner).
3143 pub fn run_recording_budgeted(
3144 &mut self,
3145 mode: super::reverse::ReverseMode,
3146 budget: usize,
3147 ) -> Result<(), String> {
3148 self.pebble_budget = budget;
3149 self.run_recording_mode(mode)
3150 }
3151
3152 /// The number of recompute re-executions performed by the last reverse pass (corner 2) — the
3153 /// time-cost instrument for the pebble time/space schedule.
3154 pub fn recompute_ops(&self) -> usize {
3155 self.recompute_ops
3156 }
3157
3158 /// Arm this VM for a reversibility RECORDING pass in `mode`: a fresh tape, the per-pc pebbling
3159 /// plan, the mode, and (Adiabatic only) the reverse-live recompute recipes keyed by `(frame,
3160 /// register)`. Shared by the single-VM [`Vm::run_recording_mode`] and each task VM of the
3161 /// concurrency scheduler ([`RevCoop::record_mode`]) — independent frames make per-task recompute
3162 /// sound.
3163 fn install_reverse_recording(&mut self, mode: super::reverse::ReverseMode) {
3164 let budget = self.pebble_budget;
3165 self.journal = Some(super::journal::HistoryTape::new());
3166 self.journal_plan = Some(super::pebble::plan_budgeted(self.program, mode, budget));
3167 self.reverse_mode = mode;
3168 self.recompute_ops = 0;
3169 self.recompute = if mode == super::reverse::ReverseMode::Adiabatic {
3170 // A checkpointed chain intermediate stays JOURNALED (out of the recompute map), so
3171 // `recompute_into` stops at it (its live forward value serves the read) instead of
3172 // re-walking to the chain root — the corner-2 space-for-time trade.
3173 let checkpoints = super::pebble::checkpoint_defs(self.program, budget);
3174 super::pebble::recomputable(self.program)
3175 .into_iter()
3176 .filter(|(_frame, _r, pc, _op)| !checkpoints.contains(pc))
3177 .map(|(frame, r, _pc, op)| ((frame, r), op))
3178 .collect()
3179 } else {
3180 std::collections::HashMap::new()
3181 };
3182 }
3183
3184 /// Whether the pebbling plan elides the journal entry for the write at `pc` (its destroyed value
3185 /// is program-invisible scratch no reverse step reads). `false` when there is no plan.
3186 #[inline]
3187 fn journal_elided(&self, pc: usize) -> bool {
3188 // Both `Elide` (invisible scratch) and `Recompute` (reverse-live scratch reconstructed on
3189 // reverse) skip journaling forward and skip the tape-pop on reverse.
3190 matches!(
3191 self.journal_plan.as_ref().and_then(|p| p.get(pc)),
3192 Some(super::pebble::JournalDecision::Elide | super::pebble::JournalDecision::Recompute)
3193 )
3194 }
3195
3196 /// (`Adiabatic`, Piece 2) Reconstruct a reverse-live scratch register by RE-RUNNING its pure
3197 /// defining op forward — Bennett uncompute. RECURSIVE: any recomputable INPUT of the def is
3198 /// reconstructed first, so a whole recomputable CHAIN (`t3=t2+d`, `t2=t1+c`, `t1=a+b`) is rebuilt
3199 /// bottom-up before the top step runs — the pebble "recompute" strategy (O(1) tape, chain-length
3200 /// time). A no-op for a register that was not marked recomputable.
3201 fn recompute_reg(&mut self, frame: Option<usize>, r: Reg) -> Result<(), String> {
3202 self.recompute_into(frame, r, &mut Vec::new())
3203 }
3204
3205 fn recompute_into(
3206 &mut self,
3207 frame: Option<usize>,
3208 r: Reg,
3209 seen: &mut Vec<Reg>,
3210 ) -> Result<(), String> {
3211 let Some(op) = self.recompute.get(&(frame, r)).copied() else {
3212 return Ok(());
3213 };
3214 if seen.contains(&r) {
3215 return Ok(()); // recomputable is a DAG (a def precedes its use); guard against any cycle
3216 }
3217 seen.push(r);
3218 // The pure two-operand family (corner 3) — kept in lockstep with `pebble::recomputable`.
3219 let (lhs, rhs) = match op {
3220 Op::Add { lhs, rhs, .. }
3221 | Op::Sub { lhs, rhs, .. }
3222 | Op::Mul { lhs, rhs, .. }
3223 | Op::BitXor { lhs, rhs, .. }
3224 | Op::Div { lhs, rhs, .. }
3225 | Op::ExactDiv { lhs, rhs, .. }
3226 | Op::FloorDiv { lhs, rhs, .. }
3227 | Op::Mod { lhs, rhs, .. }
3228 | Op::Pow { lhs, rhs, .. }
3229 | Op::BitAnd { lhs, rhs, .. }
3230 | Op::BitOr { lhs, rhs, .. }
3231 | Op::Shl { lhs, rhs, .. }
3232 | Op::Shr { lhs, rhs, .. } => (lhs, rhs),
3233 _ => return Ok(()),
3234 };
3235 // Rebuild recomputable inputs FIRST (the chain), then run this def from live inputs.
3236 self.recompute_into(frame, lhs, seen)?;
3237 self.recompute_into(frame, rhs, seen)?;
3238 self.recompute_ops += 1; // corner 2: count each re-execution (the time cost of the schedule)
3239 match op {
3240 Op::Add { dst, lhs, rhs } => self.binop(dst, lhs, rhs, Value::add)?,
3241 Op::Sub { dst, lhs, rhs } => self.binop(dst, lhs, rhs, Value::sub)?,
3242 Op::Mul { dst, lhs, rhs } => self.binop(dst, lhs, rhs, Value::mul)?,
3243 Op::BitXor { dst, lhs, rhs } => self.binop(dst, lhs, rhs, Value::bitxor)?,
3244 Op::Div { dst, lhs, rhs } => self.binop(dst, lhs, rhs, Value::div)?,
3245 Op::ExactDiv { dst, lhs, rhs } => self.binop(dst, lhs, rhs, Value::exact_div)?,
3246 Op::FloorDiv { dst, lhs, rhs } => self.binop(dst, lhs, rhs, Value::floor_div)?,
3247 Op::Mod { dst, lhs, rhs } => self.binop(dst, lhs, rhs, Value::modulo)?,
3248 Op::Pow { dst, lhs, rhs } => self.binop(dst, lhs, rhs, Value::pow)?,
3249 Op::BitAnd { dst, lhs, rhs } => self.binop(dst, lhs, rhs, Value::bitand)?,
3250 Op::BitOr { dst, lhs, rhs } => self.binop(dst, lhs, rhs, Value::bitor)?,
3251 Op::Shl { dst, lhs, rhs } => self.binop(dst, lhs, rhs, Value::shl)?,
3252 Op::Shr { dst, lhs, rhs } => self.binop(dst, lhs, rhs, Value::shr)?,
3253 _ => {}
3254 }
3255 Ok(())
3256 }
3257
3258 /// Take the history tape recorded by [`Vm::run_recording`].
3259 pub fn take_journal(&mut self) -> Option<super::journal::HistoryTape> {
3260 self.journal.take()
3261 }
3262
3263 /// Run forward to completion WITH recording, DRIVING the task through its concurrency blocks —
3264 /// the single-task reversible-scheduler path. Accumulates one history tape across every slice; a
3265 /// `Sleep` (virtual time) resumes with nothing. Multi-task/channel blocks are declined here (the
3266 /// coordinator-driven reversible scheduler over several task VMs is the next layer). Declines a
3267 /// program with any op outside the reversible subset before running.
3268 pub fn run_recording_driven(&mut self) -> Result<(), String> {
3269 if let Some(op) = self
3270 .program
3271 .code
3272 .iter()
3273 .find(|op| !super::reverse::is_reversible_supported(op))
3274 {
3275 return Err(match super::reverse::external_effect_barrier(op) {
3276 // A truly-external effect: name the irreversibility barrier (internal state up to it
3277 // reverses; the effect itself cannot be un-done) — never a silent lie.
3278 Some(barrier) => format!(
3279 "vm: `{}` is an irreversible {barrier} effect — not yet reversible past the honest Landauer wall (an external effect cannot be un-done)",
3280 op.name()
3281 ),
3282 None => format!("vm: op `{}` is not yet reversible", op.name()),
3283 });
3284 }
3285 logicaffeine_base::money::clear_ambient_rates();
3286 self.journal = Some(super::journal::HistoryTape::new());
3287 loop {
3288 match self.run_until_block_impl::<false, true>(u64::MAX)? {
3289 VmStep::Done(_) => return Ok(()),
3290 VmStep::Blocked => match self.take_pending() {
3291 // Virtual time: no observable effect, resume with nothing (the loop re-enters and
3292 // continues from the saved slice).
3293 Some(VmBlock::Sleep(_)) => {}
3294 Some(_) => {
3295 return Err(
3296 "vm: reversible single-task driver does not yet service channel/task blocks"
3297 .to_string(),
3298 )
3299 }
3300 None => return Err("vm: blocked with no pending request".to_string()),
3301 },
3302 VmStep::Paused => unreachable!("recording run is not stepped"),
3303 }
3304 }
3305 }
3306
3307 /// Run BACKWARD: reconstruct the EXACT pre-run state by replaying the executed op path in strict
3308 /// reverse order and applying each op's inverse. The control-flow trace (`steps`) gives the exact
3309 /// executed sequence — so branches and loops reverse with no special-casing (a loop is just the
3310 /// trace with repeated pcs). A [`crate::vm::reverse::RevClass::Bijection`] op self-inverts
3311 /// algebraically with NO data-tape interaction (the zero-garbage core, even inside a loop); every
3312 /// other op that recorded a delta pops it and restores what it destroyed. The data tape stays
3313 /// aligned because journaled ops are visited in exact reverse push order.
3314 ///
3315 /// Sound because reversing in exact reverse order leaves the machine in each op's POST-state when
3316 /// its inverse is applied, so every operand the inverse reads holds its forward value.
3317 pub fn run_reverse(&mut self, mut tape: super::journal::HistoryTape) -> Result<(), String> {
3318 while self.reverse_one_step(&mut tape)? {}
3319 self.adiabatic_reset();
3320 Ok(())
3321 }
3322
3323 /// Adiabatic (the best-of-both-worlds mode): the elided non-reverse-read scratch was never
3324 /// journaled — RECOMPUTE it as its known default (`Nothing`, the pristine initial value every
3325 /// register begins at). This lifts the Observable-floor tape to FULL machine fidelity: every
3326 /// register, scratch included, returns bit-exact. Bennett uncompute in its cheapest form — the
3327 /// recomputed value is a constant. A no-op outside `Adiabatic`. Shared by `run_reverse` and the
3328 /// per-task reversal of the concurrency scheduler (`RevCoop::reverse`).
3329 fn adiabatic_reset(&mut self) {
3330 if self.reverse_mode != super::reverse::ReverseMode::Adiabatic {
3331 return;
3332 }
3333 let named = &self.program.named_regs;
3334 for i in 0..self.registers.len() {
3335 let observable = named.is_empty() || named.get(i).copied().unwrap_or(true);
3336 if !observable {
3337 self.registers[i] = Value::nothing();
3338 }
3339 }
3340 }
3341
3342 /// Reverse the TOPMOST recorded step of `tape`; returns `false` when its step trace is exhausted.
3343 /// The composable primitive — `run_reverse` loops it to completion, and the reversible scheduler
3344 /// reverses each task's SLICE by calling it a slice's-worth of times (schedule-backward).
3345 fn reverse_one_step(&mut self, tape: &mut super::journal::HistoryTape) -> Result<bool, String> {
3346 use super::journal::JournalEntry;
3347 use super::reverse::{records, reversibility, RevClass};
3348 let (pc, base) = match tape.pop_step() {
3349 Some(pair) => pair,
3350 None => return Ok(false),
3351 };
3352 {
3353 // Restore the register window this op ran in, so bijection inverses (which recompute
3354 // `base + reg`) target the right registers even inside a called function's frame.
3355 self.base = base;
3356 let op = *self.program.code.get(pc).ok_or(
3357 "vm: reverse trace references a warm-body pc (unsupported in this subset)",
3358 )?;
3359 // Pebbling: this write's journal entry was ELIDED forward (program-invisible scratch no
3360 // reverse step reads), so there is nothing to pop — the register keeps its value. Elided
3361 // ops are always plain single-dst overwrites, so skipping their reverse is exact.
3362 if self.journal_elided(pc) {
3363 return Ok(true);
3364 }
3365 if matches!(
3366 op,
3367 Op::Call { .. } | Op::CallValue { .. } | Op::Return { .. } | Op::ReturnNothing
3368 ) {
3369 self.reverse_call_op(&op, tape)?;
3370 } else if matches!(
3371 op,
3372 Op::IterPrepare { .. } | Op::IterNext { .. } | Op::IterPop
3373 ) {
3374 self.reverse_iter_op(&op, tape)?;
3375 } else if matches!(
3376 op,
3377 Op::LoadNow { .. } | Op::LoadToday { .. } | Op::NewCrdt { .. }
3378 ) {
3379 // A nondeterministic read (clock / drawn CRDT replica id) reverses by restoring dst;
3380 // the drawn entropy stays recorded.
3381 match tape.pop() {
3382 Some(JournalEntry::NondetRead {
3383 dst_slot, dst_old, ..
3384 }) => {
3385 self.registers[dst_slot] = dst_old;
3386 }
3387 other => return Err(format!("vm: reverse expected NondetRead, got {other:?}")),
3388 }
3389 } else if matches!(op, Op::CrdtAppend { .. }) {
3390 // Restore the CRDT interior THROUGH the register's live handle (aliases observe it), or
3391 // fall back to the collection restore when the append was onto a plain list.
3392 match tape.pop() {
3393 Some(JournalEntry::CrdtInterior { slot, snapshot }) => {
3394 use crate::interpreter::RuntimeValue;
3395 match (
3396 self.registers[slot].as_runtime_ref(),
3397 snapshot.as_runtime_ref(),
3398 ) {
3399 (Some(RuntimeValue::Crdt(cur)), Some(RuntimeValue::Crdt(snap))) => {
3400 *cur.borrow_mut() = snap.borrow().clone();
3401 }
3402 _ => {
3403 return Err(
3404 "vm: reverse CrdtInterior on a non-CRDT register".to_string()
3405 )
3406 }
3407 }
3408 }
3409 Some(JournalEntry::CollectionMutate { slot, old }) => {
3410 self.reverse_collection_mutate(slot, old)?;
3411 }
3412 other => {
3413 return Err(format!(
3414 "vm: reverse expected CrdtInterior/CollectionMutate, got {other:?}"
3415 ))
3416 }
3417 }
3418 } else if matches!(op, Op::CrdtResolve { .. }) {
3419 // Restore the resolved field: a nested CRDT field through its live handle, or a plain
3420 // field via the Box snapshot.
3421 match tape.pop() {
3422 Some(JournalEntry::CrdtFieldInterior {
3423 obj_slot,
3424 field,
3425 snapshot,
3426 }) => {
3427 use crate::interpreter::RuntimeValue;
3428 let restored = match (
3429 self.registers[obj_slot].as_runtime_ref(),
3430 snapshot.as_runtime_ref(),
3431 ) {
3432 (Some(RuntimeValue::Struct(s)), Some(RuntimeValue::Crdt(snap))) => {
3433 match s.fields.get(&field) {
3434 Some(RuntimeValue::Crdt(cur)) => {
3435 *cur.borrow_mut() = snap.borrow().clone();
3436 true
3437 }
3438 _ => false,
3439 }
3440 }
3441 _ => false,
3442 };
3443 if !restored {
3444 return Err(
3445 "vm: reverse CrdtFieldInterior on a non-CRDT field".to_string()
3446 );
3447 }
3448 }
3449 Some(JournalEntry::CollectionMutate { slot, old }) => {
3450 self.reverse_collection_mutate(slot, old)?;
3451 }
3452 other => {
3453 return Err(format!(
3454 "vm: reverse expected CrdtFieldInterior/CollectionMutate, got {other:?}"
3455 ))
3456 }
3457 }
3458 } else if matches!(op, Op::Div { dst, lhs, .. } if dst == lhs) {
3459 // Reverse an in-place division: reconstruct `a_old = q·b + r` from the kept quotient
3460 // and divisor, or restore the full old value if `record_op` fell back to an overwrite.
3461 match tape.pop() {
3462 Some(JournalEntry::DivReconstruct {
3463 dst_slot,
3464 divisor,
3465 remainder,
3466 }) => {
3467 use crate::interpreter::RuntimeValue;
3468 let q = self.registers[dst_slot].as_int().unwrap_or(0);
3469 let b = divisor.as_int().unwrap_or(0);
3470 let r = remainder.as_int().unwrap_or(0);
3471 self.registers[dst_slot] = Value::from_runtime(RuntimeValue::Int(
3472 q.wrapping_mul(b).wrapping_add(r),
3473 ));
3474 }
3475 Some(JournalEntry::RegOverwrite { slot, old }) => self.registers[slot] = old,
3476 other => {
3477 return Err(format!(
3478 "vm: reverse expected DivReconstruct/RegOverwrite, got {other:?}"
3479 ))
3480 }
3481 }
3482 } else if matches!(op, Op::Shr { dst, lhs, .. } | Op::Shl { dst, lhs, .. } if dst == lhs)
3483 || matches!(op, Op::DivPow2 { dst, lhs, .. } if dst == lhs)
3484 {
3485 // Reverse an in-place shift: recombine the kept result with the `k` saved shifted-out
3486 // bits — `(a << k) | low` for a right shift, `(a >> k) | (high << (64−k))` for a left
3487 // shift — or restore the full old value if `record_op` fell back to an overwrite.
3488 match tape.pop() {
3489 Some(JournalEntry::ShiftReconstruct {
3490 dst_slot,
3491 dropped,
3492 k,
3493 left,
3494 }) => {
3495 use crate::interpreter::RuntimeValue;
3496 let cur = self.registers[dst_slot].as_int().unwrap_or(0);
3497 let restored = if left {
3498 (((cur as u64) >> k) | ((dropped as u64) << (64 - k))) as i64
3499 } else {
3500 cur.wrapping_shl(k) | dropped
3501 };
3502 self.registers[dst_slot] = Value::from_runtime(RuntimeValue::Int(restored));
3503 }
3504 Some(JournalEntry::RegOverwrite { slot, old }) => self.registers[slot] = old,
3505 other => {
3506 return Err(format!(
3507 "vm: reverse expected ShiftReconstruct/RegOverwrite, got {other:?}"
3508 ))
3509 }
3510 }
3511 } else if matches!(op, Op::BitAnd { dst, lhs, .. } | Op::BitOr { dst, lhs, .. } if dst == lhs)
3512 {
3513 // Reverse an in-place mask: re-merge the saved bits under the complementary mask —
3514 // `a | saved` for AND (saved = the cleared bits), `(a & !mask) | saved` for OR.
3515 match tape.pop() {
3516 Some(JournalEntry::MaskReconstruct {
3517 dst_slot,
3518 saved,
3519 mask,
3520 and,
3521 }) => {
3522 use crate::interpreter::RuntimeValue;
3523 let cur = self.registers[dst_slot].as_int().unwrap_or(0);
3524 let restored = if and {
3525 cur | saved
3526 } else {
3527 (cur & !mask) | saved
3528 };
3529 self.registers[dst_slot] = Value::from_runtime(RuntimeValue::Int(restored));
3530 }
3531 Some(JournalEntry::RegOverwrite { slot, old }) => self.registers[slot] = old,
3532 other => {
3533 return Err(format!(
3534 "vm: reverse expected MaskReconstruct/RegOverwrite, got {other:?}"
3535 ))
3536 }
3537 }
3538 } else if matches!(op, Op::Mod { dst, lhs, .. } if dst == lhs) {
3539 // Reverse an in-place modulo: `a_old = q·b + r` from the saved quotient, the live
3540 // divisor, and the kept remainder still in `dst`.
3541 match tape.pop() {
3542 Some(JournalEntry::ModReconstruct {
3543 dst_slot,
3544 quotient,
3545 divisor,
3546 }) => {
3547 use crate::interpreter::RuntimeValue;
3548 let r = self.registers[dst_slot].as_int().unwrap_or(0);
3549 let b = divisor.as_int().unwrap_or(0);
3550 self.registers[dst_slot] = Value::from_runtime(RuntimeValue::Int(
3551 quotient.wrapping_mul(b).wrapping_add(r),
3552 ));
3553 }
3554 Some(JournalEntry::RegOverwrite { slot, old }) => self.registers[slot] = old,
3555 other => {
3556 return Err(format!(
3557 "vm: reverse expected ModReconstruct/RegOverwrite, got {other:?}"
3558 ))
3559 }
3560 }
3561 } else if let RevClass::Bijection(_) = reversibility(&op) {
3562 // Adiabatic (Piece 2): reconstruct any recomputed reverse-live operand by re-running
3563 // its pure defining op (in its frame, so `self.base` resolves the registers) from the
3564 // current live inputs, BEFORE the inverse reads it.
3565 if !self.recompute.is_empty() {
3566 let frame = super::pebble::frame_of(self.program, pc);
3567 for r in super::reverse::reverse_reads(&op) {
3568 self.recompute_reg(frame, r)?;
3569 }
3570 }
3571 self.apply_inverse(&op)?;
3572 } else if records(&op) {
3573 match tape.pop() {
3574 Some(JournalEntry::RegOverwrite { slot, old }) => self.registers[slot] = old,
3575 Some(JournalEntry::GlobalOverwrite { idx, old }) => self.globals[idx] = old,
3576 Some(JournalEntry::MultiRegOverwrite { slots }) => {
3577 for (slot, old) in slots {
3578 self.registers[slot] = old;
3579 }
3580 }
3581 Some(JournalEntry::ShowLine) => {
3582 self.lines.pop();
3583 }
3584 Some(JournalEntry::CollectionMutate { slot, old }) => {
3585 self.reverse_collection_mutate(slot, old)?;
3586 }
3587 Some(JournalEntry::ListPop { list_slot, list_old, dst_slot, dst_old }) => {
3588 self.reverse_collection_mutate(list_slot, list_old)?;
3589 self.registers[dst_slot] = dst_old;
3590 }
3591 Some(JournalEntry::Branch { .. }) => {}
3592 // Frame / iterator entries are consumed by their own reverse handlers, never here.
3593 Some(
3594 JournalEntry::CallUndo { .. }
3595 | JournalEntry::CallValueUndo { .. }
3596 | JournalEntry::ReturnUndo { .. }
3597 | JournalEntry::IterNextUndo { .. }
3598 | JournalEntry::IterPopUndo { .. }
3599 | JournalEntry::NondetRead { .. }
3600 // Handled by the dedicated Crdt / in-place arithmetic branches, never here.
3601 | JournalEntry::CrdtInterior { .. }
3602 | JournalEntry::CrdtFieldInterior { .. }
3603 | JournalEntry::DivReconstruct { .. }
3604 | JournalEntry::ShiftReconstruct { .. }
3605 | JournalEntry::MaskReconstruct { .. }
3606 | JournalEntry::ModReconstruct { .. },
3607 ) => {
3608 return Err("vm: control-frame entry reached the data-tape reverse path".to_string());
3609 }
3610 None => return Err("vm: reverse data-tape underflow".to_string()),
3611 }
3612 }
3613 }
3614 Ok(true)
3615 }
3616
3617 /// Reverse the next `n` recorded steps of `tape` (a scheduled SLICE of one task's execution), or
3618 /// until its trace runs out. The reversible scheduler calls this per schedule entry, walking the
3619 /// schedule backward across all task VMs.
3620 pub(crate) fn reverse_slice(
3621 &mut self,
3622 tape: &mut super::journal::HistoryTape,
3623 n: usize,
3624 ) -> Result<(), String> {
3625 for _ in 0..n {
3626 if !self.reverse_one_step(tape)? {
3627 break;
3628 }
3629 }
3630 Ok(())
3631 }
3632
3633 /// Apply the inverse of a [`crate::vm::reverse::RevClass::Bijection`] op — the zero-garbage,
3634 /// tape-free reversal. Must handle exactly the bijections
3635 /// [`crate::vm::reverse::is_reversible_supported`] admits. Sound because the reverse-order
3636 /// invariant guarantees the machine is in the op's exact POST-state when the inverse is applied,
3637 /// so every operand the inverse reads holds its forward value.
3638 fn apply_inverse(&mut self, op: &Op) -> Result<(), String> {
3639 match op {
3640 // Involutions — the inverse IS the op itself, re-applied to the post-state.
3641 Op::RevSwap { a, b } => {
3642 let sa = self.base + *a as usize;
3643 let sb = self.base + *b as usize;
3644 self.registers.swap(sa, sb);
3645 Ok(())
3646 }
3647 Op::RevXor { place, delta } => self.binop(*place, *place, *delta, Value::bitxor),
3648 Op::RevNeg { place } => self.rev_int_neg(*place),
3649 // The additive translations invert by the opposite operation, no tape needed.
3650 Op::RevAdd { place, delta } => self.rev_int_update(*place, *delta, i64::wrapping_sub),
3651 Op::RevSub { place, delta } => self.rev_int_update(*place, *delta, i64::wrapping_add),
3652 _ => Ok(()),
3653 }
3654 }
3655
3656 /// In-place modular integer update `R[place] = f(R[place], R[delta])` (wrapping) — the shared
3657 /// kernel of the reversible additive ops. Requires `Int` operands, like the other numeric ops.
3658 /// The SAME wrapping semantics run forward and in reverse, so `RevAdd`/`RevSub` are exact mutual
3659 /// inverses over (ℤ/2⁶⁴, +).
3660 fn rev_int_update(
3661 &mut self,
3662 place: Reg,
3663 delta: Reg,
3664 f: fn(i64, i64) -> i64,
3665 ) -> Result<(), String> {
3666 use crate::interpreter::RuntimeValue;
3667 let p = match &*self.reg(place).as_runtime() {
3668 RuntimeValue::Int(n) => *n,
3669 _ => return Err("reversible add/subtract requires Int operands".to_string()),
3670 };
3671 let d = match &*self.reg(delta).as_runtime() {
3672 RuntimeValue::Int(n) => *n,
3673 _ => return Err("reversible add/subtract requires Int operands".to_string()),
3674 };
3675 self.set(place, Value::int(f(p, d)));
3676 Ok(())
3677 }
3678
3679 /// Reverse an in-place collection mutation by restoring the pristine pre-mutation snapshot `old`.
3680 /// Sound because journaling `old` forced the op's copy-on-write, so `R[slot]` now holds a
3681 /// DIFFERENT `Rc` (the mutated clone) while `old` is the untouched original — restoring it is
3682 /// bit-identical, including aliasing (a sibling handle that never saw the mutation is left
3683 /// exactly as it was). If instead `R[slot]` still shares `old`'s `Rc` (a genuine in-place
3684 /// mutation — only reachable with value-semantics OFF), we cannot un-mutate it from the snapshot,
3685 /// so we decline rather than mis-restore.
3686 fn reverse_collection_mutate(&mut self, slot: usize, old: Value) -> Result<(), String> {
3687 use crate::interpreter::RuntimeValue;
3688 use std::rc::Rc;
3689 let shares_rc = matches!(
3690 (self.registers[slot].as_runtime_ref(), old.as_runtime_ref()),
3691 (Some(RuntimeValue::List(a)), Some(RuntimeValue::List(b))) if Rc::ptr_eq(a, b)
3692 ) || matches!(
3693 (self.registers[slot].as_runtime_ref(), old.as_runtime_ref()),
3694 (Some(RuntimeValue::Map(a)), Some(RuntimeValue::Map(b))) if Rc::ptr_eq(a, b)
3695 ) || matches!(
3696 (self.registers[slot].as_runtime_ref(), old.as_runtime_ref()),
3697 (Some(RuntimeValue::Set(a)), Some(RuntimeValue::Set(b))) if Rc::ptr_eq(a, b)
3698 );
3699 if shares_rc {
3700 return Err(
3701 "vm: reverse of an in-place collection mutation requires value semantics"
3702 .to_string(),
3703 );
3704 }
3705 self.registers[slot] = old;
3706 Ok(())
3707 }
3708
3709 /// In-place modular negation `R[place] = -R[place]` (wrapping) — self-inverse.
3710 fn rev_int_neg(&mut self, place: Reg) -> Result<(), String> {
3711 use crate::interpreter::RuntimeValue;
3712 let p = match &*self.reg(place).as_runtime() {
3713 RuntimeValue::Int(n) => *n,
3714 _ => return Err("reversible negate requires an Int operand".to_string()),
3715 };
3716 self.set(place, Value::int(p.wrapping_neg()));
3717 Ok(())
3718 }
3719
3720 /// Journal a function frame's teardown before a `Return`/`ReturnNothing` dismantles it, so the
3721 /// reverse pass can rebuild the callee window exactly. Captures the callee's saved register
3722 /// window, the iterator-stack tail, the return-value slot's prior value, and the argument window
3723 /// (about to be cleared) — all BEFORE any mutation. Called only from the RECORDING monomorph.
3724 fn record_return(&mut self, frame: &CallFrame) {
3725 let rv_slot = frame.caller_base + frame.return_reg as usize;
3726 let arg_hi = (frame.arg_lo + frame.arg_count as usize).min(self.registers.len());
3727 let frame_from = frame.restore_len;
3728 let frame_vals = self.registers[frame_from..].to_vec();
3729 let iter_from = frame.iter_depth;
3730 let iter_vals = self.iter_stack[iter_from..].to_vec();
3731 let rv_old = self.registers[rv_slot].clone();
3732 let arg_old = self.registers[frame.arg_lo..arg_hi].to_vec();
3733 if let Some(j) = self.journal.as_mut() {
3734 j.push(super::journal::JournalEntry::ReturnUndo {
3735 frame_from,
3736 frame_vals,
3737 iter_from,
3738 iter_vals,
3739 rv_slot,
3740 rv_old,
3741 arg_lo: frame.arg_lo,
3742 arg_old,
3743 });
3744 }
3745 }
3746
3747 /// Reverse a `Call` / `Return` / `ReturnNothing` by consuming its frame-undo entry — the dual of
3748 /// [`Vm::record_return`] and the `CallUndo` push. `self.base` was already restored from the step
3749 /// trace by the caller, so this only rebuilds the register file and iterator stack.
3750 fn reverse_call_op(
3751 &mut self,
3752 op: &Op,
3753 tape: &mut super::journal::HistoryTape,
3754 ) -> Result<(), String> {
3755 use super::journal::JournalEntry;
3756 match op {
3757 Op::Call { .. } => match tape.pop() {
3758 // Undo the callee window growth (the body has already been reversed).
3759 Some(JournalEntry::CallUndo { restore_len }) => {
3760 self.registers.truncate(restore_len);
3761 Ok(())
3762 }
3763 other => Err(format!("vm: reverse expected CallUndo, got {other:?}")),
3764 },
3765 Op::CallValue { .. } => match tape.pop() {
3766 // Restore any overlap capture slots (survive the truncate), then undo the growth.
3767 Some(JournalEntry::CallValueUndo {
3768 restore_len,
3769 captures,
3770 }) => {
3771 for (slot, old) in captures {
3772 self.registers[slot] = old;
3773 }
3774 self.registers.truncate(restore_len);
3775 Ok(())
3776 }
3777 other => Err(format!("vm: reverse expected CallValueUndo, got {other:?}")),
3778 },
3779 Op::Return { .. } | Op::ReturnNothing => match tape.pop() {
3780 Some(JournalEntry::ReturnUndo {
3781 frame_from,
3782 frame_vals,
3783 iter_from,
3784 iter_vals,
3785 rv_slot,
3786 rv_old,
3787 arg_lo,
3788 arg_old,
3789 }) => {
3790 // Undo the return-value write and the argument-window clear (surviving region).
3791 self.registers[rv_slot] = rv_old;
3792 for (i, v) in arg_old.into_iter().enumerate() {
3793 self.registers[arg_lo + i] = v;
3794 }
3795 // Rebuild the callee's register window and iterator stack.
3796 self.registers.truncate(frame_from);
3797 self.registers.extend(frame_vals);
3798 self.iter_stack.truncate(iter_from);
3799 self.iter_stack.extend(iter_vals);
3800 Ok(())
3801 }
3802 other => Err(format!("vm: reverse expected ReturnUndo, got {other:?}")),
3803 },
3804 _ => Ok(()),
3805 }
3806 }
3807
3808 /// Journal a nondeterministic read (clock / random): the destination's prior value AND the drawn
3809 /// entropy. Called only from the RECORDING monomorph. Reverse restores `dst_old`; `drawn` stays on
3810 /// the tape as the captured entropy (so the recorded execution is fully determined).
3811 fn record_nondet(&mut self, dst: Reg, drawn: &Value) {
3812 let dst_slot = self.base + dst as usize;
3813 let dst_old = self.registers[dst_slot].clone();
3814 if let Some(j) = self.journal.as_mut() {
3815 j.push(super::journal::JournalEntry::NondetRead {
3816 dst_slot,
3817 dst_old,
3818 drawn: drawn.clone(),
3819 });
3820 }
3821 }
3822
3823 /// Reverse an iterator op (`Repeat` machinery) by reconstructing the iterator stack: `IterPop`
3824 /// re-pushes the dropped iterator, `IterNext` rewinds one element (restoring dst and the cursor)
3825 /// or does nothing if it was the exhausted exit, and `IterPrepare` pops the (now index-0)
3826 /// iterator. Walked in reverse execution order, this exactly unwinds a `Repeat` loop.
3827 fn reverse_iter_op(
3828 &mut self,
3829 op: &Op,
3830 tape: &mut super::journal::HistoryTape,
3831 ) -> Result<(), String> {
3832 use super::journal::JournalEntry;
3833 match op {
3834 Op::IterPrepare { .. } => {
3835 self.iter_stack
3836 .pop()
3837 .ok_or("vm: reverse IterPrepare with no live iterator")?;
3838 Ok(())
3839 }
3840 Op::IterNext { .. } => match tape.pop() {
3841 Some(JournalEntry::IterNextUndo {
3842 advanced,
3843 dst_slot,
3844 dst_old,
3845 }) => {
3846 if advanced {
3847 self.registers[dst_slot] = dst_old;
3848 let (_, idx) = self
3849 .iter_stack
3850 .last_mut()
3851 .ok_or("vm: reverse IterNext with no live iterator")?;
3852 *idx -= 1;
3853 }
3854 Ok(())
3855 }
3856 other => Err(format!("vm: reverse expected IterNextUndo, got {other:?}")),
3857 },
3858 Op::IterPop => match tape.pop() {
3859 Some(JournalEntry::IterPopUndo { items, idx }) => {
3860 self.iter_stack.push((items, idx));
3861 Ok(())
3862 }
3863 other => Err(format!("vm: reverse expected IterPopUndo, got {other:?}")),
3864 },
3865 _ => Ok(()),
3866 }
3867 }
3868
3869 /// Record what `op` is about to DESTROY, before it executes. Called only from the
3870 /// `RECORDING = true` monomorph, so it is entirely absent from the production loop. Pushes iff
3871 /// [`crate::vm::reverse::records`] (the dual of `run_reverse`'s pop), keyed off the authoritative
3872 /// reversibility helpers, never the lossy `disasm::op_io`.
3873 fn record_op(&mut self, op: &Op, pc: usize) {
3874 use super::journal::JournalEntry;
3875 if !super::reverse::records(op) {
3876 return;
3877 }
3878 // Pebbling: the plan elides this write — its destroyed value is program-invisible scratch no
3879 // reverse step reads, so leave it off the tape (reverse skips it in lockstep via the plan).
3880 if self.journal_elided(pc) {
3881 return;
3882 }
3883 let entry = match op {
3884 Op::GlobalSet { idx, .. } => JournalEntry::GlobalOverwrite {
3885 idx: *idx as usize,
3886 old: self.globals[*idx as usize].clone(),
3887 },
3888 Op::Show { .. } => JournalEntry::ShowLine,
3889 // A pure builtin writes dst AND clears its argument registers — journal all of them.
3890 Op::CallBuiltin {
3891 dst,
3892 args_start,
3893 arg_count,
3894 ..
3895 } => {
3896 let base = self.base;
3897 let dst_slot = base + *dst as usize;
3898 let mut slots = Vec::with_capacity(1 + *arg_count as usize);
3899 slots.push((dst_slot, self.registers[dst_slot].clone()));
3900 for i in 0..*arg_count as usize {
3901 let s = base + *args_start as usize + i;
3902 slots.push((s, self.registers[s].clone()));
3903 }
3904 JournalEntry::MultiRegOverwrite { slots }
3905 }
3906 // A tuple destructure writes several registers at once — journal each prior value.
3907 Op::DestructureTuple { start, count, .. } => {
3908 let base = self.base;
3909 let slots = (0..*count as usize)
3910 .map(|i| {
3911 let slot = base + *start as usize + i;
3912 (slot, self.registers[slot].clone())
3913 })
3914 .collect();
3915 JournalEntry::MultiRegOverwrite { slots }
3916 }
3917 // A pop mutates the list AND overwrites a dst — journal both pristine snapshots.
3918 Op::ListPop { list, dst } => {
3919 let list_slot = self.base + *list as usize;
3920 let dst_slot = self.base + *dst as usize;
3921 JournalEntry::ListPop {
3922 list_slot,
3923 list_old: self.registers[list_slot].clone(),
3924 dst_slot,
3925 dst_old: self.registers[dst_slot].clone(),
3926 }
3927 }
3928 // A CRDT sequence append mutates the shared `Rc<RefCell<CrdtValue>>` interior IN PLACE, so
3929 // an Rc-bump can't force a copy-on-write — take a DEEP snapshot of the interior instead.
3930 // (A `CrdtAppend` onto a plain list IS Rc-bump COW-forced, like `ListPush`.)
3931 Op::CrdtAppend { seq, .. } => {
3932 use crate::interpreter::RuntimeValue;
3933 let slot = self.base + *seq as usize;
3934 match self.registers[slot].as_runtime_ref() {
3935 Some(RuntimeValue::Crdt(rc)) => {
3936 let deep = rc.borrow().clone();
3937 let snapshot = Value::from_runtime(RuntimeValue::Crdt(std::rc::Rc::new(
3938 std::cell::RefCell::new(deep),
3939 )));
3940 JournalEntry::CrdtInterior { slot, snapshot }
3941 }
3942 _ => JournalEntry::CollectionMutate {
3943 slot,
3944 old: self.registers[slot].clone(),
3945 },
3946 }
3947 }
3948 // A CRDT resolve onto a nested register FIELD mutates that field's `Rc` interior in place
3949 // (deep field snapshot); onto a plain field it replaces the value (a Box snapshot is exact).
3950 Op::CrdtResolve { obj, field, .. } => {
3951 use crate::interpreter::RuntimeValue;
3952 let obj_slot = self.base + *obj as usize;
3953 let field_name = match &self.program.constants[*field as usize] {
3954 Constant::Text(s) => s.clone(),
3955 _ => String::new(),
3956 };
3957 let field_crdt = match self.registers[obj_slot].as_runtime_ref() {
3958 Some(RuntimeValue::Struct(s)) => match s.fields.get(&field_name) {
3959 Some(RuntimeValue::Crdt(rc)) => Some(rc.borrow().clone()),
3960 _ => None,
3961 },
3962 _ => None,
3963 };
3964 if let Some(deep) = field_crdt {
3965 let snapshot = Value::from_runtime(RuntimeValue::Crdt(std::rc::Rc::new(
3966 std::cell::RefCell::new(deep),
3967 )));
3968 JournalEntry::CrdtFieldInterior {
3969 obj_slot,
3970 field: field_name,
3971 snapshot,
3972 }
3973 } else {
3974 JournalEntry::CollectionMutate {
3975 slot: obj_slot,
3976 old: self.registers[obj_slot].clone(),
3977 }
3978 }
3979 }
3980 // An IN-PLACE integer division `a = a / b` discards only the remainder — record just that
3981 // (reconstruct `a_old = q·b + r` on reverse from the kept quotient + divisor), not the
3982 // whole dividend word. A non-integer or zero divisor falls back to the full overwrite.
3983 Op::Div { dst, lhs, rhs } if dst == lhs => {
3984 use crate::interpreter::RuntimeValue;
3985 let dst_slot = self.base + *dst as usize;
3986 let divisor = self.registers[self.base + *rhs as usize].clone();
3987 match (self.registers[dst_slot].as_int(), divisor.as_int()) {
3988 (Some(a), Some(b)) if b != 0 => JournalEntry::DivReconstruct {
3989 dst_slot,
3990 remainder: Value::from_runtime(RuntimeValue::Int(a.wrapping_rem(b))),
3991 divisor,
3992 },
3993 _ => JournalEntry::RegOverwrite {
3994 slot: dst_slot,
3995 old: self.registers[dst_slot].clone(),
3996 },
3997 }
3998 }
3999 // An IN-PLACE right shift `a = a >> k` destroys only the low `k` bits — journal just those
4000 // (reconstruct `a_old = (a << k) | dropped` on reverse), not the whole word. `k` is masked
4001 // to the machine width; `k == 0` (identity) or a non-integer falls back to a full overwrite.
4002 Op::Shr { dst, lhs, rhs } if dst == lhs => {
4003 let dst_slot = self.base + *dst as usize;
4004 let k = self.registers[self.base + *rhs as usize]
4005 .as_int()
4006 .map(|s| (s as u64 & 63) as u32);
4007 match (self.registers[dst_slot].as_int(), k) {
4008 (Some(a), Some(k)) if k != 0 => {
4009 let mask = ((1u64 << k) - 1) as i64;
4010 JournalEntry::ShiftReconstruct {
4011 dst_slot,
4012 dropped: a & mask,
4013 k,
4014 left: false,
4015 }
4016 }
4017 _ => JournalEntry::RegOverwrite {
4018 slot: dst_slot,
4019 old: self.registers[dst_slot].clone(),
4020 },
4021 }
4022 }
4023 // An IN-PLACE `a = a / 2^k` (`DivPow2`) equals the arithmetic right shift only for a_old ≥ 0
4024 // (negatives truncate toward zero, not −∞) — restrict the low-bit reconstruct to that case.
4025 Op::DivPow2 { dst, lhs, k } if dst == lhs => {
4026 let dst_slot = self.base + *dst as usize;
4027 let k = *k as u32;
4028 match self.registers[dst_slot].as_int() {
4029 Some(a) if a >= 0 && k != 0 && k < 64 => {
4030 let mask = ((1u64 << k) - 1) as i64;
4031 JournalEntry::ShiftReconstruct {
4032 dst_slot,
4033 dropped: a & mask,
4034 k,
4035 left: false,
4036 }
4037 }
4038 _ => JournalEntry::RegOverwrite {
4039 slot: dst_slot,
4040 old: self.registers[dst_slot].clone(),
4041 },
4042 }
4043 }
4044 // An IN-PLACE left shift `a = a << k` destroys only the top `k` bits (shifted out) — journal
4045 // just those (right-aligned), reconstruct the low bits from the kept result on reverse.
4046 Op::Shl { dst, lhs, rhs } if dst == lhs => {
4047 let dst_slot = self.base + *dst as usize;
4048 let k = self.registers[self.base + *rhs as usize]
4049 .as_int()
4050 .map(|s| (s as u64 & 63) as u32);
4051 match (self.registers[dst_slot].as_int(), k) {
4052 (Some(a), Some(k)) if k != 0 => {
4053 let dropped = ((a as u64) >> (64 - k)) as i64;
4054 JournalEntry::ShiftReconstruct {
4055 dst_slot,
4056 dropped,
4057 k,
4058 left: true,
4059 }
4060 }
4061 _ => JournalEntry::RegOverwrite {
4062 slot: dst_slot,
4063 old: self.registers[dst_slot].clone(),
4064 },
4065 }
4066 }
4067 // An IN-PLACE `a = a & b` destroys the bits where `b = 0`; `a = a | b` the bits where
4068 // `b = 1`. Journal only those (the complementary mask recovers the rest from the result).
4069 Op::BitAnd { dst, lhs, rhs } if dst == lhs => {
4070 let dst_slot = self.base + *dst as usize;
4071 match (
4072 self.registers[dst_slot].as_int(),
4073 self.registers[self.base + *rhs as usize].as_int(),
4074 ) {
4075 (Some(a), Some(m)) => JournalEntry::MaskReconstruct {
4076 dst_slot,
4077 saved: a & !m,
4078 mask: m,
4079 and: true,
4080 },
4081 _ => JournalEntry::RegOverwrite {
4082 slot: dst_slot,
4083 old: self.registers[dst_slot].clone(),
4084 },
4085 }
4086 }
4087 Op::BitOr { dst, lhs, rhs } if dst == lhs => {
4088 let dst_slot = self.base + *dst as usize;
4089 match (
4090 self.registers[dst_slot].as_int(),
4091 self.registers[self.base + *rhs as usize].as_int(),
4092 ) {
4093 (Some(a), Some(m)) => JournalEntry::MaskReconstruct {
4094 dst_slot,
4095 saved: a & m,
4096 mask: m,
4097 and: false,
4098 },
4099 _ => JournalEntry::RegOverwrite {
4100 slot: dst_slot,
4101 old: self.registers[dst_slot].clone(),
4102 },
4103 }
4104 }
4105 // An IN-PLACE `a = a % b` keeps the remainder, discards the QUOTIENT — journal just the
4106 // quotient, reconstruct `a_old = q·b + r` from the live divisor on reverse.
4107 Op::Mod { dst, lhs, rhs } if dst == lhs => {
4108 let dst_slot = self.base + *dst as usize;
4109 let divisor = self.registers[self.base + *rhs as usize].clone();
4110 match (self.registers[dst_slot].as_int(), divisor.as_int()) {
4111 (Some(a), Some(b)) if b != 0 => JournalEntry::ModReconstruct {
4112 dst_slot,
4113 quotient: a.wrapping_div(b),
4114 divisor,
4115 },
4116 _ => JournalEntry::RegOverwrite {
4117 slot: dst_slot,
4118 old: self.registers[dst_slot].clone(),
4119 },
4120 }
4121 }
4122 // Journal the pre-mutation collection value (an Rc bump for a shared container). That
4123 // very bump raises the strong count, forcing the op's copy-on-write, so the original
4124 // stays pristine for the reverse to restore.
4125 _ if super::reverse::mutated_collection_reg(op).is_some() => {
4126 let slot = self.base + super::reverse::mutated_collection_reg(op).unwrap() as usize;
4127 JournalEntry::CollectionMutate {
4128 slot,
4129 old: self.registers[slot].clone(),
4130 }
4131 }
4132 _ => {
4133 let dst = super::reverse::overwritten_reg(op)
4134 .expect("records() ⇒ writes a global/output line or has an overwritten_reg");
4135 let slot = self.base + dst as usize;
4136 JournalEntry::RegOverwrite {
4137 slot,
4138 old: self.registers[slot].clone(),
4139 }
4140 }
4141 };
4142 if let Some(j) = self.journal.as_mut() {
4143 j.push(entry);
4144 }
4145 }
4146
4147 /// Run one slice: from a fresh start (or resumed from a prior block) until the
4148 /// program completes ([`VmStep::Done`]) or a concurrency op suspends it
4149 /// ([`VmStep::Blocked`], request in [`Vm::take_pending`]). Keeping `pc` and the
4150 /// call stack as loop-locals (restored once on entry, saved once on a block)
4151 /// leaves the hot dispatch path byte-for-byte identical to the old `run`.
4152 pub(crate) fn run_until_block(&mut self) -> Result<VmStep, String> {
4153 let step = self.run_until_block_impl::<false, false>(u64::MAX);
4154 self.end_with_unhandled(step)
4155 }
4156
4157 /// A program that has finished (`Done`) with a contained failure no handler absorbed has
4158 /// failed — the page's own failure is the program's once nothing is left to run — and the
4159 /// failure site of that end is the one the failure trapped at.
4160 fn end_with_unhandled(&mut self, step: Result<VmStep, String>) -> Result<VmStep, String> {
4161 match step {
4162 Ok(VmStep::Done(_)) if self.unhandled.is_some() => {
4163 let (message, site) = self.unhandled.take().expect("checked");
4164 self.ended_at_site = Some(site);
4165 Err(message)
4166 }
4167 other => other,
4168 }
4169 }
4170
4171 /// The failure a page entry the program took itself contained and no handler absorbed, taken
4172 /// by the host that is carrying the page on — whose own record of the page's failure it
4173 /// becomes ([`crate::page_host::LoweredCalls::take_unhandled`]).
4174 pub fn take_unhandled(&mut self) -> Option<(String, Option<u32>)> {
4175 self.unhandled.take()
4176 }
4177
4178 /// The main program, run to its end with any contained failure left for the host to take
4179 /// ([`Vm::take_unhandled`]) rather than made the run's own: the start of a page a host keeps
4180 /// driving.
4181 pub fn run_keeping_entries(&mut self) -> Result<(), String> {
4182 logicaffeine_base::money::clear_ambient_rates();
4183 crate::semantics::dom::retire_stream();
4184 match self.run_until_block_impl::<false, false>(u64::MAX)? {
4185 VmStep::Done(_) => Ok(()),
4186 VmStep::Blocked => Err("vm: concurrency op requires the scheduler driver".to_string()),
4187 VmStep::Paused => unreachable!("run_until_block (STEPPED = false) never pauses"),
4188 }
4189 }
4190
4191 /// `dispatchEntry(dispatcher, context, hook, node, event, value)` read from the argument window
4192 /// at `args_start` — [`crate::semantics::builtins::BuiltinId::DomDispatchEntry`]: the page's
4193 /// dispatcher run as the host runs an entry ([`Vm::invoke_function`], which leaves the machine
4194 /// as a failure found it), a failure heard through the page's failure door exactly as
4195 /// `page_host`'s guarded door hears one — the context text first, then the handler, whose own
4196 /// failure never replaces the one being reported — and recorded for the program's end when no
4197 /// handler absorbed it. A failed turn was heard.
4198 #[cold]
4199 #[inline(never)]
4200 fn dispatch_entry(
4201 &mut self,
4202 args_start: Reg,
4203 ) -> Result<crate::interpreter::RuntimeValue, String> {
4204 use crate::interpreter::RuntimeValue;
4205 let function = |vm: &Self, k: Reg| {
4206 vm.reg(args_start + k)
4207 .as_int()
4208 .and_then(|i| u16::try_from(i).ok())
4209 };
4210 let dispatcher =
4211 function(self, 0).ok_or("dispatchEntry: the page has no dispatcher to enter")?;
4212 let (context, hook) = (function(self, 1), function(self, 2));
4213 let args: Vec<RuntimeValue> = (3..6)
4214 .map(|k| self.reg(args_start + k).as_runtime().clone())
4215 .collect();
4216 let message = match self.invoke_function(dispatcher, args) {
4217 Ok(answer) => return Ok(answer),
4218 Err(message) => message,
4219 };
4220 let site = self.failing_site();
4221 let context = match context.map(|f| self.invoke_function(f, Vec::new())) {
4222 Some(Ok(RuntimeValue::Text(text))) => text.to_string(),
4223 _ => String::new(),
4224 };
4225 let message = format!("{context}{message}");
4226 let absorbed = hook.is_some_and(|f| {
4227 matches!(
4228 self.invoke_function(f, vec![RuntimeValue::Text(message.clone().into())]),
4229 Ok(RuntimeValue::Bool(true))
4230 )
4231 });
4232 if !absorbed && self.unhandled.is_none() {
4233 self.unhandled = Some((message, site));
4234 }
4235 Ok(RuntimeValue::Bool(true))
4236 }
4237
4238 /// Like [`Vm::run_until_block`] but with reversibility RECORDING enabled — the per-task recording
4239 /// primitive for a reversible scheduler. Runs one slice (from a fresh start or resumed from a
4240 /// prior block) with journaling on, ACCUMULATING the history tape across slices, and returns at
4241 /// the next concurrency block or completion. The scheduler drives each task through its blocks;
4242 /// on reverse it walks the schedule backward and reverses each task's slice from this tape (plus
4243 /// the channel-op deltas the scheduler journals). Zero production cost — a separate monomorph the
4244 /// hot `run_until_block` (`RECORDING = false`) never instantiates.
4245 pub(crate) fn run_until_block_recording(&mut self) -> Result<VmStep, String> {
4246 if self.journal.is_none() {
4247 self.journal = Some(super::journal::HistoryTape::new());
4248 }
4249 self.run_until_block_impl::<false, true>(u64::MAX)
4250 }
4251
4252 /// Step forward by at most `step_budget` ops, then pause ([`VmStep::Paused`],
4253 /// resumable on the next call). Two callers: the Studio debug drawer, and the
4254 /// fueled run path behind `largo run --max-steps` / the MCP `step_budget`
4255 /// (`ui_bridge::interpret_for_ui_sync_with_args`). Production unbudgeted
4256 /// callers use [`Vm::run_until_block`] (`STEPPED = false`), whose
4257 /// monomorphization elides every budget check — the hot dispatch path stays
4258 /// the byte-for-byte old loop.
4259 pub(crate) fn run_steps(&mut self, step_budget: u64) -> Result<VmStep, String> {
4260 let step = self.run_until_block_impl::<true, false>(step_budget);
4261 self.end_with_unhandled(step)
4262 }
4263
4264 /// Ops run by every [`Vm::run_steps`] slice so far.
4265 pub(crate) fn steps_run(&self) -> u64 {
4266 self.stepped
4267 }
4268
4269 fn run_until_block_impl<const STEPPED: bool, const RECORDING: bool>(
4270 &mut self,
4271 step_budget: u64,
4272 ) -> Result<VmStep, String> {
4273 self.ended_at_site = None;
4274 let mut pc;
4275 let mut call_stack: Vec<CallFrame>;
4276 if self.sched_active {
4277 pc = self.sched_pc;
4278 call_stack = std::mem::take(&mut self.sched_call_stack);
4279 self.sched_active = false;
4280 } else {
4281 pc = 0usize;
4282 call_stack = Vec::new();
4283 }
4284
4285 // The loop ends when the top-level program code is exhausted. A warm body
4286 // lives past `program.code.len()` but is only ever entered via a `Call` (which
4287 // pushes a frame), so `!call_stack.is_empty()` keeps the loop alive while one
4288 // is executing; without any warm body installed a live frame already implies
4289 // `pc < program.code.len()`, so this disjunct is a no-op for the baseline path.
4290 let mut executed: u64 = 0;
4291 while pc < self.program.code.len() || !call_stack.is_empty() {
4292 if STEPPED {
4293 if executed >= step_budget {
4294 // Pause exactly as a concurrency block saves its slice (pc +
4295 // call stack into the scheduler slots), but with no pending
4296 // request — the debugger resumes on the next `run_steps`.
4297 self.sched_pc = pc;
4298 self.sched_call_stack = call_stack;
4299 self.sched_active = true;
4300 return Ok(VmStep::Paused);
4301 }
4302 executed += 1;
4303 self.stepped += 1;
4304 }
4305 let op = if pc < self.program.code.len() {
4306 self.program.code[pc]
4307 } else {
4308 self.warm_code[pc - self.program.code.len()]
4309 };
4310 // Wave 3 ("runtime failures carry a location"): the pc this op is ABOUT to run at,
4311 // saved before it can fail. An `Err` from any op below propagates via `?` straight out
4312 // of this loop, so this is the last write `sched_pc` sees before that happens —
4313 // `failing_site` reads it once the caller has `Err` in hand.
4314 self.sched_pc = pc;
4315 // Reversibility recording — trace the executed pc (the control skeleton) and journal what
4316 // this op is about to destroy, BEFORE it runs. Behind the `const RECORDING` monomorph:
4317 // absent from the production loop (dead-stripped when `RECORDING = false`, exactly like
4318 // the `STEPPED` budget check above).
4319 if RECORDING {
4320 let base = self.base;
4321 if let Some(j) = self.journal.as_mut() {
4322 j.push_step(pc, base);
4323 }
4324 self.record_op(&op, pc);
4325 }
4326 match op {
4327 Op::LoadConst { dst, idx } => {
4328 let v = self.const_pool[idx as usize].clone();
4329 self.set(dst, v);
4330 pc += 1;
4331 }
4332 Op::Move { dst, src } => {
4333 self.set(dst, self.reg(src).clone());
4334 pc += 1;
4335 }
4336 Op::RevSwap { a, b } => {
4337 let sa = self.base + a as usize;
4338 let sb = self.base + b as usize;
4339 self.registers.swap(sa, sb);
4340 pc += 1;
4341 }
4342 Op::RevXor { place, delta } => {
4343 self.binop(place, place, delta, Value::bitxor)?;
4344 pc += 1;
4345 }
4346 Op::RevNeg { place } => {
4347 self.rev_int_neg(place)?;
4348 pc += 1;
4349 }
4350 Op::RevAdd { place, delta } => {
4351 self.rev_int_update(place, delta, i64::wrapping_add)?;
4352 pc += 1;
4353 }
4354 Op::RevSub { place, delta } => {
4355 self.rev_int_update(place, delta, i64::wrapping_sub)?;
4356 pc += 1;
4357 }
4358 Op::EnsureOwned { reg } => {
4359 // Call-site copy-on-write barrier: isolate a shared collection — or each list
4360 // field of a record — before it is passed to a `mutable` or mutable-borrow
4361 // callee. No-op when the register is a `mutable`-exempt param (its writes are
4362 // its caller's) or the value is already uniquely owned.
4363 let cur_func = call_stack.last().map(|f| f.func);
4364 self.ensure_reg_owned(reg, pc, cur_func);
4365 if crate::semantics::collections::value_semantics_enabled()
4366 && !self.is_cow_exempt(reg, cur_func)
4367 {
4368 self.own_struct_fields(reg, pc, cur_func);
4369 }
4370 pc += 1;
4371 }
4372 Op::Add { dst, lhs, rhs } => {
4373 self.binop(dst, lhs, rhs, Value::add)?;
4374 pc += 1;
4375 }
4376 Op::AddAssign { dst, src } => {
4377 self.add_assign(dst, src)?;
4378 pc += 1;
4379 }
4380 Op::Sub { dst, lhs, rhs } => {
4381 self.binop(dst, lhs, rhs, Value::sub)?;
4382 pc += 1;
4383 }
4384 Op::Mul { dst, lhs, rhs } => {
4385 self.binop(dst, lhs, rhs, Value::mul)?;
4386 pc += 1;
4387 }
4388 Op::Div { dst, lhs, rhs } => {
4389 self.binop(dst, lhs, rhs, Value::div)?;
4390 pc += 1;
4391 }
4392 Op::ExactDiv { dst, lhs, rhs } => {
4393 self.binop(dst, lhs, rhs, Value::exact_div)?;
4394 pc += 1;
4395 }
4396 Op::FloorDiv { dst, lhs, rhs } => {
4397 self.binop(dst, lhs, rhs, Value::floor_div)?;
4398 pc += 1;
4399 }
4400 Op::Mod { dst, lhs, rhs } => {
4401 self.binop(dst, lhs, rhs, Value::modulo)?;
4402 pc += 1;
4403 }
4404 Op::DivPow2 { dst, lhs, k } => {
4405 // `lhs / 2^k` (lhs is Oracle-proven Int) — identical result
4406 // to `Op::Div` by `2^k`, so it matches the tree-walker.
4407 let v = self.reg(lhs).div(&Value::int(1i64 << k))?;
4408 self.set(dst, v);
4409 pc += 1;
4410 }
4411 Op::MagicDivU {
4412 dst,
4413 lhs,
4414 magic,
4415 more,
4416 mul_back,
4417 divisor,
4418 wrap,
4419 } => {
4420 // `lhs / c` / `lhs % c` by the precomputed magic reciprocal
4421 // (`magic`/`more`). Emitted only for an Oracle-proven Int,
4422 // non-negative `lhs`, so the result is bit-identical to
4423 // `Op::Div`/`Op::Mod` by the constant `c`. A `wrap` remainder's
4424 // `lhs` is also below `2c`: one subtraction at most.
4425 let v = match self.reg(lhs).as_int() {
4426 Some(x) if wrap && mul_back != 0 => {
4427 Value::int(if x >= divisor { x - divisor } else { x })
4428 }
4429 Some(x) => {
4430 Value::int(crate::vm::compiler::magic_eval(x, magic, more, mul_back))
4431 }
4432 // The optimistic gate does not prove `lhs` fits i64 — a widening loop can make
4433 // it a `BigInt` the u64 reciprocal cannot represent. Fall back to the exact
4434 // op by the carried `divisor`: `mul_back == 0` is division, else modulo.
4435 // Bit-identical to `Op::Div`/`Op::Mod`, so the tier differential holds.
4436 None => {
4437 let d = Value::int(divisor);
4438 if mul_back == 0 {
4439 self.reg(lhs).div(&d)?
4440 } else {
4441 self.reg(lhs).modulo(&d)?
4442 }
4443 }
4444 };
4445 self.set(dst, v);
4446 pc += 1;
4447 }
4448 Op::Lt { dst, lhs, rhs } => {
4449 self.binop(dst, lhs, rhs, Value::lt)?;
4450 pc += 1;
4451 }
4452 Op::Gt { dst, lhs, rhs } => {
4453 self.binop(dst, lhs, rhs, Value::gt)?;
4454 pc += 1;
4455 }
4456 Op::LtEq { dst, lhs, rhs } => {
4457 self.binop(dst, lhs, rhs, Value::lte)?;
4458 pc += 1;
4459 }
4460 Op::GtEq { dst, lhs, rhs } => {
4461 self.binop(dst, lhs, rhs, Value::gte)?;
4462 pc += 1;
4463 }
4464 Op::Eq { dst, lhs, rhs } => {
4465 let v = self.reg(lhs).eq_op(self.reg(rhs))?;
4466 self.set(dst, v);
4467 pc += 1;
4468 }
4469 Op::ApproxEq { dst, lhs, rhs } => {
4470 let v = crate::semantics::arith::approx_eq(
4471 self.reg(lhs).as_runtime().clone(),
4472 self.reg(rhs).as_runtime().clone(),
4473 )
4474 .map(Value::from_runtime)?;
4475 self.set(dst, v);
4476 pc += 1;
4477 }
4478 Op::NotEq { dst, lhs, rhs } => {
4479 let v = self.reg(lhs).neq_op(self.reg(rhs))?;
4480 self.set(dst, v);
4481 pc += 1;
4482 }
4483 Op::Not { dst, src } => {
4484 let v = self.reg(src).not_op()?;
4485 self.set(dst, v);
4486 pc += 1;
4487 }
4488 Op::Concat { dst, lhs, rhs } => {
4489 self.binop(dst, lhs, rhs, Value::concat)?;
4490 pc += 1;
4491 }
4492 Op::SeqConcat { dst, lhs, rhs } => {
4493 self.binop(dst, lhs, rhs, Value::seq_concat)?;
4494 pc += 1;
4495 }
4496 Op::Pow { dst, lhs, rhs } => {
4497 self.binop(dst, lhs, rhs, Value::pow)?;
4498 pc += 1;
4499 }
4500 Op::BitXor { dst, lhs, rhs } => {
4501 self.binop(dst, lhs, rhs, Value::bitxor)?;
4502 pc += 1;
4503 }
4504 Op::BitAnd { dst, lhs, rhs } => {
4505 self.binop(dst, lhs, rhs, Value::bitand)?;
4506 pc += 1;
4507 }
4508 Op::BitOr { dst, lhs, rhs } => {
4509 self.binop(dst, lhs, rhs, Value::bitor)?;
4510 pc += 1;
4511 }
4512 Op::Shl { dst, lhs, rhs } => {
4513 self.binop(dst, lhs, rhs, Value::shl)?;
4514 pc += 1;
4515 }
4516 Op::Shr { dst, lhs, rhs } => {
4517 self.binop(dst, lhs, rhs, Value::shr)?;
4518 pc += 1;
4519 }
4520 Op::Jump { target } => {
4521 // A back-edge is a hot-loop candidate in EVERY frame
4522 // (OSR everywhere); the enclosing frame picks the
4523 // named-register map the write-back contract consults.
4524 // Skip the whole region machinery (the per-frame named-map
4525 // selection + the `regions` hashmap probe) once this loop
4526 // head is blacklisted — an un-tierable / demoted region pays
4527 // only this O(1) `Vec<bool>` index per back-edge instead of
4528 // re-hashing every iteration.
4529 // `target < program.code.len()` keeps the region machinery
4530 // (blacklist indexed by program pc, `program.code[head..]` scans)
4531 // off warm-body back-edges; always true on the baseline path.
4532 if target < pc
4533 && target < self.program.code.len()
4534 && self.tier.is_some()
4535 && !self.region_blacklist[target]
4536 {
4537 let (named, frame_regs): (&[bool], usize) = match call_stack.last() {
4538 None => (&self.program.named_regs, self.program.register_count),
4539 Some(f) => {
4540 let fun = &self.program.functions[f.func as usize];
4541 (&fun.named_regs, fun.register_count)
4542 }
4543 };
4544 let cur_func = call_stack.last().map(|f| f.func);
4545 match self.try_region(
4546 target,
4547 pc,
4548 named,
4549 frame_regs,
4550 call_stack.len(),
4551 cur_func,
4552 ) {
4553 Some(RegionExit::At(exit)) => {
4554 pc = exit;
4555 continue;
4556 }
4557 Some(RegionExit::Call {
4558 call_pc,
4559 resume_pc,
4560 frames,
4561 list_args,
4562 }) => {
4563 let Some(Op::Call {
4564 dst,
4565 func,
4566 args_start,
4567 ..
4568 }) = self.program.code.get(call_pc).copied()
4569 else {
4570 return Err(
4571 "vm: native region exit has no call site".to_string()
4572 );
4573 };
4574 self.materialize_native_frames(
4575 &frames,
4576 &list_args,
4577 args_start,
4578 dst,
4579 func,
4580 call_pc + 1,
4581 &mut call_stack,
4582 )?;
4583 pc = resume_pc;
4584 continue;
4585 }
4586 Some(RegionExit::Return(value)) => {
4587 // The region hit a `Return` — perform the
4588 // actual function return, exactly like the
4589 // Op::Return arm.
4590 let frame = call_stack.pop().ok_or("vm: return with no caller")?;
4591 self.iter_stack.truncate(frame.iter_depth);
4592 self.registers.truncate(frame.restore_len);
4593 self.base = frame.caller_base;
4594 self.set(frame.return_reg, value);
4595 self.clear_arg_window(&frame);
4596 pc = frame.return_pc;
4597 continue;
4598 }
4599 None => {}
4600 }
4601 }
4602 pc = target;
4603 }
4604 Op::JumpIfFalse { cond, target } => {
4605 if !self.reg(cond).decided_truth()? {
4606 pc = target;
4607 } else {
4608 pc += 1;
4609 }
4610 }
4611 Op::JumpIfTrue { cond, target } => {
4612 if self.reg(cond).decided_truth()? {
4613 pc = target;
4614 } else {
4615 pc += 1;
4616 }
4617 }
4618 Op::GlobalGet { dst, idx } => {
4619 match &self.globals[idx as usize] {
4620 Some(v) => {
4621 let v = v.clone();
4622 self.set(dst, v);
4623 }
4624 None => {
4625 return Err(format!(
4626 "Undefined variable: {}",
4627 self.program.globals[idx as usize]
4628 ));
4629 }
4630 }
4631 pc += 1;
4632 }
4633 Op::GlobalSet { idx, src } => {
4634 self.globals[idx as usize] = Some(self.reg(src).clone());
4635 pc += 1;
4636 }
4637 Op::MakeClosure {
4638 dst,
4639 func,
4640 locals_start,
4641 } => {
4642 use crate::interpreter::{ClosureValue, RuntimeValue};
4643 let f = self
4644 .program
4645 .functions
4646 .get(func as usize)
4647 .ok_or("vm: MakeClosure on undefined function index")?;
4648 let mut captured_env = std::collections::HashMap::new();
4649 let mut local_k: Reg = 0;
4650 for (sym, global_idx) in &f.captures {
4651 match global_idx {
4652 Some(gidx) => {
4653 // Snapshot the global IF it is defined; an
4654 // undefined one is simply not captured — the
4655 // body falls through to the live global.
4656 if let Some(v) = &self.globals[*gidx as usize] {
4657 captured_env.insert(*sym, v.as_runtime().deep_clone());
4658 }
4659 }
4660 None => {
4661 let v = self.reg(locals_start + local_k).as_runtime().deep_clone();
4662 captured_env.insert(*sym, v);
4663 local_k += 1;
4664 }
4665 }
4666 }
4667 let param_names =
4668 vec![crate::intern::Symbol::default(); f.param_count as usize];
4669 self.set(
4670 dst,
4671 Value::from_runtime(RuntimeValue::Function(Box::new(ClosureValue {
4672 body_index: func as usize,
4673 captured_env,
4674 param_names,
4675 generated: None,
4676 }))),
4677 );
4678 pc += 1;
4679 }
4680 Op::CallValue {
4681 dst,
4682 callee,
4683 args_start,
4684 arg_count,
4685 name_for_err,
4686 } => {
4687 use crate::interpreter::RuntimeValue;
4688 let closure = match &*self.reg(callee).as_runtime() {
4689 RuntimeValue::Function(c) => (**c).clone(),
4690 other => {
4691 return Err(if name_for_err == u32::MAX {
4692 format!("Cannot call value of type {}", other.type_name())
4693 } else {
4694 match &self.program.constants[name_for_err as usize] {
4695 Constant::Text(n) => format!("Unknown function: {}", n),
4696 _ => format!("Cannot call value of type {}", other.type_name()),
4697 }
4698 });
4699 }
4700 };
4701 pc = self.enter_closure::<RECORDING>(
4702 dst,
4703 &closure,
4704 args_start,
4705 arg_count,
4706 pc + 1,
4707 &mut call_stack,
4708 )?;
4709 }
4710 Op::CallBuiltin {
4711 dst,
4712 builtin: crate::semantics::builtins::BuiltinId::DomDispatchEntry,
4713 args_start,
4714 arg_count,
4715 } => {
4716 let v = self.dispatch_entry(args_start)?;
4717 self.set(dst, Value::from_runtime(v));
4718 self.clear_args(args_start, arg_count, None);
4719 pc += 1;
4720 }
4721 Op::CallBuiltin {
4722 dst,
4723 builtin,
4724 args_start,
4725 arg_count,
4726 } => {
4727 let mut args = Vec::with_capacity(arg_count as usize);
4728 for k in 0..arg_count {
4729 args.push(self.reg(args_start + k).as_runtime().clone());
4730 }
4731 let v = if builtin == crate::semantics::builtins::BuiltinId::DefinedReal {
4732 self.open_defined_run().define(args)?
4733 } else {
4734 crate::semantics::builtins::call_builtin(builtin, args)?
4735 };
4736 self.set(dst, Value::from_runtime(v));
4737 self.clear_args(args_start, arg_count, None);
4738 pc += 1;
4739 }
4740 Op::Call {
4741 dst,
4742 func,
4743 args_start,
4744 arg_count,
4745 } => {
4746 // A suspended caller must not retain dead construction
4747 // temporaries as extra owners of a callee's global values.
4748 // Liveness includes the whole argument window; named
4749 // bindings and arguments needed after nested calls survive.
4750 // The old call-destination value needs no separate pin:
4751 // if it is also an argument, liveness already protects it.
4752 if !RECORDING && crate::semantics::collections::value_semantics_enabled() {
4753 self.release_dead_scratch(
4754 None,
4755 pc,
4756 call_stack.last().map(|frame| frame.func),
4757 None,
4758 );
4759 }
4760 pc = self.enter_call::<RECORDING>(
4761 dst,
4762 func,
4763 args_start,
4764 arg_count,
4765 pc + 1,
4766 &mut call_stack,
4767 )?;
4768 }
4769 Op::Return { src } => {
4770 let frame = call_stack.pop().ok_or("vm: return with no caller")?;
4771 let rv = self.reg(src).clone();
4772 if RECORDING {
4773 self.record_return(&frame);
4774 }
4775 self.iter_stack.truncate(frame.iter_depth);
4776 self.registers.truncate(frame.restore_len);
4777 self.base = frame.caller_base;
4778 let slot = self.base + frame.return_reg as usize;
4779 self.registers[slot] = rv;
4780 self.clear_arg_window(&frame);
4781 pc = frame.return_pc;
4782 }
4783 Op::ReturnNothing => {
4784 let frame = call_stack.pop().ok_or("vm: return with no caller")?;
4785 if RECORDING {
4786 self.record_return(&frame);
4787 }
4788 self.iter_stack.truncate(frame.iter_depth);
4789 self.registers.truncate(frame.restore_len);
4790 self.base = frame.caller_base;
4791 let slot = self.base + frame.return_reg as usize;
4792 self.registers[slot] = Value::nothing();
4793 self.clear_arg_window(&frame);
4794 pc = frame.return_pc;
4795 }
4796 Op::NewList { dst, start, count } => {
4797 let mut items = Vec::with_capacity(count as usize);
4798 for k in 0..count {
4799 items.push(self.reg(start + k).clone());
4800 }
4801 self.set(dst, Value::list(items));
4802 pc += 1;
4803 }
4804 Op::NewEmptyList { dst } => {
4805 // Allocation reuse: if `dst` already holds a SOLE-OWNED
4806 // Ints list (e.g. the previous loop iteration's, now dead),
4807 // clear it in place and reuse its buffer/capacity instead
4808 // of allocating a fresh Rc + Vec. Sound: refcount 1 means
4809 // no other holder can observe the clear.
4810 use crate::interpreter::{ListRepr, RuntimeValue};
4811 use std::rc::Rc;
4812 let di = self.base + dst as usize;
4813 let reused = matches!(
4814 self.registers.get(di).map(|v| v.as_runtime()).as_deref(),
4815 Some(RuntimeValue::List(rc))
4816 if Rc::strong_count(rc) == 1
4817 && Rc::weak_count(rc) == 0
4818 && matches!(&*rc.borrow(), ListRepr::Ints(_))
4819 );
4820 if reused {
4821 if let RuntimeValue::List(rc) = &*self.registers[di].as_runtime() {
4822 if let ListRepr::Ints(buf) = &mut *rc.borrow_mut() {
4823 buf.clear();
4824 }
4825 }
4826 } else {
4827 self.set(dst, Value::empty_list());
4828 }
4829 pc += 1;
4830 }
4831 Op::NewEmptyListFixed { dst, capacity } => {
4832 // Preserve the shared fixed-size proof in the VM: reuse a
4833 // unique buffer when possible, otherwise reserve exactly
4834 // the proven capacity up front.
4835 use crate::interpreter::{ListRepr, RuntimeValue};
4836 use std::rc::Rc;
4837 let di = self.base + dst as usize;
4838 let reused = matches!(
4839 self.registers.get(di).map(|v| v.as_runtime()).as_deref(),
4840 Some(RuntimeValue::List(rc))
4841 if Rc::strong_count(rc) == 1
4842 && Rc::weak_count(rc) == 0
4843 && matches!(&*rc.borrow(), ListRepr::Ints(_))
4844 );
4845 if reused {
4846 if let RuntimeValue::List(rc) = &*self.registers[di].as_runtime() {
4847 if let ListRepr::Ints(buf) = &mut *rc.borrow_mut() {
4848 buf.clear();
4849 if buf.capacity() < capacity as usize {
4850 buf.reserve_exact(capacity as usize);
4851 }
4852 }
4853 }
4854 } else {
4855 self.set(dst, Value::empty_list_with_capacity(capacity as usize));
4856 }
4857 pc += 1;
4858 }
4859 Op::NewEmptyListWithCapacity { dst, capacity } => {
4860 let capacity = self
4861 .reg(capacity)
4862 .as_int()
4863 .ok_or_else(|| "Sequence capacity requires an Int".to_string())?
4864 .max(0) as usize;
4865 use crate::interpreter::{ListRepr, RuntimeValue};
4866 use std::rc::Rc;
4867 let di = self.base + dst as usize;
4868 let reused = matches!(
4869 self.registers.get(di).map(|v| v.as_runtime()).as_deref(),
4870 Some(RuntimeValue::List(rc))
4871 if Rc::strong_count(rc) == 1
4872 && Rc::weak_count(rc) == 0
4873 && matches!(&*rc.borrow(), ListRepr::Ints(_))
4874 );
4875 if reused {
4876 if let RuntimeValue::List(rc) = &*self.registers[di].as_runtime() {
4877 if let ListRepr::Ints(buf) = &mut *rc.borrow_mut() {
4878 buf.clear();
4879 if buf.capacity() < capacity {
4880 let _ = buf.try_reserve_exact(capacity);
4881 }
4882 }
4883 }
4884 } else {
4885 let mut buf = Vec::new();
4886 let _ = buf.try_reserve_exact(capacity);
4887 self.set(
4888 dst,
4889 Value::from_runtime(RuntimeValue::List(Rc::new(
4890 std::cell::RefCell::new(ListRepr::Ints(buf)),
4891 ))),
4892 );
4893 }
4894 pc += 1;
4895 }
4896 Op::NewEmptyListI32 { dst } => {
4897 // Mirror NewEmptyList's allocation reuse, but for the
4898 // half-width `IntsI32` repr (the narrowing-proven buffer).
4899 use crate::interpreter::{ListRepr, RuntimeValue};
4900 use std::rc::Rc;
4901 let di = self.base + dst as usize;
4902 let reused = matches!(
4903 self.registers.get(di).map(|v| v.as_runtime()).as_deref(),
4904 Some(RuntimeValue::List(rc))
4905 if Rc::strong_count(rc) == 1
4906 && Rc::weak_count(rc) == 0
4907 && matches!(&*rc.borrow(), ListRepr::IntsI32(_))
4908 );
4909 if reused {
4910 if let RuntimeValue::List(rc) = &*self.registers[di].as_runtime() {
4911 if let ListRepr::IntsI32(buf) = &mut *rc.borrow_mut() {
4912 buf.clear();
4913 }
4914 }
4915 } else {
4916 self.set(dst, Value::empty_list_i32());
4917 }
4918 pc += 1;
4919 }
4920 Op::NewEmptySet { dst } => {
4921 self.set(dst, Value::empty_set());
4922 pc += 1;
4923 }
4924 Op::NewEmptyMap { dst } => {
4925 self.set(dst, Value::empty_map());
4926 pc += 1;
4927 }
4928 Op::NewEmptyMapWithCapacity { dst, capacity } => {
4929 let capacity = self
4930 .reg(capacity)
4931 .as_int()
4932 .ok_or_else(|| "Map capacity requires an Int".to_string())?
4933 .max(0) as usize;
4934 self.set(dst, Value::empty_map_with_capacity(capacity));
4935 pc += 1;
4936 }
4937 Op::NewRange { dst, start, end } => {
4938 let (lo, hi) = match (self.reg(start).as_int(), self.reg(end).as_int()) {
4939 (Some(lo), Some(hi)) => (lo, hi),
4940 _ => return Err("Range requires Int bounds".to_string()),
4941 };
4942 self.set(dst, Value::int_range(lo, hi));
4943 pc += 1;
4944 }
4945 Op::ListPush { list, value } => {
4946 let v = self.reg(value).clone();
4947 self.ensure_reg_owned(list, pc, call_stack.last().map(|f| f.func));
4948 self.reg(list).list_push(v)?;
4949 pc += 1;
4950 }
4951 Op::SetAdd { set, value } => {
4952 let v = self.reg(value).clone();
4953 self.ensure_reg_owned(set, pc, call_stack.last().map(|f| f.func));
4954 self.reg(set).set_add(v)?;
4955 pc += 1;
4956 }
4957 Op::RemoveFrom { collection, value } => {
4958 self.ensure_reg_owned(collection, pc, call_stack.last().map(|f| f.func));
4959 self.reg(collection).remove_from(self.reg(value))?;
4960 pc += 1;
4961 }
4962 Op::SetIndex {
4963 collection,
4964 index,
4965 value,
4966 }
4967 | Op::SetIndexUnchecked {
4968 collection,
4969 index,
4970 value,
4971 } => {
4972 use crate::interpreter::RuntimeValue;
4973 // Struct field set via index syntax (`Set item "f" of s to
4974 // v`) — VALUE semantics, mirroring the tree-walker: clone
4975 // the struct, insert, write the new struct back.
4976 let is_struct_text = matches!(
4977 (
4978 &*self.reg(collection).as_runtime(),
4979 &*self.reg(index).as_runtime()
4980 ),
4981 (RuntimeValue::Struct(_), RuntimeValue::Text(_))
4982 );
4983 if is_struct_text {
4984 let field = match &*self.reg(index).as_runtime() {
4985 RuntimeValue::Text(t) => t.to_string(),
4986 _ => unreachable!(),
4987 };
4988 let new_val = self.reg(value).as_runtime().clone();
4989 let target = self.reg_mut(collection);
4990 match target.as_runtime_mut() {
4991 RuntimeValue::Struct(st) => {
4992 st.fields.insert(field, new_val);
4993 }
4994 _ => unreachable!(),
4995 }
4996 } else {
4997 let v = self.reg(value).clone();
4998 self.ensure_reg_owned(collection, pc, call_stack.last().map(|f| f.func));
4999 self.reg(collection).index_set(self.reg(index), v)?;
5000 }
5001 pc += 1;
5002 }
5003 // The bytecode interpreter checks both: a sound proof makes
5004 // the `IndexUnchecked` check never fire, so keeping it is
5005 // free defense-in-depth. Only the JIT elides.
5006 Op::Index {
5007 dst,
5008 collection,
5009 index,
5010 }
5011 | Op::IndexUnchecked {
5012 dst,
5013 collection,
5014 index,
5015 } => {
5016 let v = self.reg(collection).index_get(self.reg(index))?;
5017 self.set(dst, v);
5018 pc += 1;
5019 }
5020 Op::Length { dst, collection } => {
5021 let n = self.reg(collection).len()?;
5022 self.set(dst, Value::int(n));
5023 pc += 1;
5024 }
5025 // Pure metadata for the native region tier — the interpreter's
5026 // checked accesses make it a no-op (the hoist it enables only
5027 // applies inside a compiled region, verified at region entry).
5028 Op::RegionBoundsGuard { .. } => {
5029 pc += 1;
5030 }
5031 Op::Contains {
5032 dst,
5033 collection,
5034 value,
5035 } => {
5036 let b = self.reg(collection).contains(self.reg(value))?;
5037 self.set(dst, Value::bool(b));
5038 pc += 1;
5039 }
5040 Op::ListPushField { obj, field, src } => {
5041 let field_name = match &self.program.constants[field as usize] {
5042 Constant::Text(s) => s.clone(),
5043 other => return Err(format!("vm: field name is not Text: {:?}", other)),
5044 };
5045 let val = self.reg(src).as_runtime().clone();
5046 // A `mutable` record parameter is its own copy too: what it holds reaches the
5047 // caller through the call's copy-out, never through a list another copy shares.
5048 if crate::semantics::collections::value_semantics_enabled() {
5049 self.own_struct_field_list(
5050 obj,
5051 &field_name,
5052 pc,
5053 call_stack.last().map(|f| f.func),
5054 );
5055 }
5056 crate::semantics::collections::push_to_struct_field(
5057 &self.reg(obj).as_runtime(),
5058 &field_name,
5059 val,
5060 )?;
5061 pc += 1;
5062 }
5063 Op::CheckPolicy {
5064 subject,
5065 predicate,
5066 is_capability,
5067 object,
5068 source_text,
5069 } => {
5070 let (registry, interner) = match self.policy_ctx {
5071 Some(ctx) => ctx,
5072 None => {
5073 return Err(crate::semantics::policy::NO_POLICIES.to_string());
5074 }
5075 };
5076 let source = match &self.program.constants[source_text as usize] {
5077 Constant::Text(s) => s.clone(),
5078 other => return Err(format!("vm: check source is not Text: {:?}", other)),
5079 };
5080 let obj_val = if object != Reg::MAX {
5081 Some(self.reg(object).as_runtime().clone())
5082 } else {
5083 None
5084 };
5085 crate::semantics::policy::check_policy(
5086 registry,
5087 interner,
5088 &self.reg(subject).as_runtime(),
5089 predicate,
5090 is_capability,
5091 obj_val.as_ref(),
5092 &source,
5093 )?;
5094 pc += 1;
5095 }
5096 Op::FormatValue {
5097 dst,
5098 src,
5099 spec,
5100 debug_prefix,
5101 } => {
5102 let mut out = String::new();
5103 if debug_prefix != u32::MAX {
5104 match &self.program.constants[debug_prefix as usize] {
5105 Constant::Text(p) => {
5106 out.push_str(p);
5107 out.push('=');
5108 }
5109 other => {
5110 return Err(format!("vm: debug prefix is not Text: {:?}", other));
5111 }
5112 }
5113 }
5114 if spec != u32::MAX {
5115 let spec_s = match &self.program.constants[spec as usize] {
5116 Constant::Text(s) => s.as_str(),
5117 other => {
5118 return Err(format!("vm: format spec is not Text: {:?}", other))
5119 }
5120 };
5121 out.push_str(&crate::semantics::format::apply_format_spec(
5122 &self.reg(src).as_runtime(),
5123 spec_s,
5124 ));
5125 } else {
5126 out.push_str(&self.reg(src).to_display_string());
5127 }
5128 self.set(dst, Value::text(out));
5129 pc += 1;
5130 }
5131 Op::SliceOp {
5132 dst,
5133 collection,
5134 start,
5135 end,
5136 } => {
5137 let v = crate::semantics::collections::slice(
5138 &self.reg(collection).as_runtime(),
5139 &self.reg(start).as_runtime(),
5140 &self.reg(end).as_runtime(),
5141 )?;
5142 self.set(dst, Value::from_runtime(v));
5143 pc += 1;
5144 }
5145 Op::DeepClone { dst, src } => {
5146 let v = self.reg(src).as_runtime().deep_clone();
5147 self.set(dst, Value::from_runtime(v));
5148 pc += 1;
5149 }
5150 Op::NewTuple { dst, start, count } => {
5151 use crate::interpreter::RuntimeValue;
5152 let mut items = Vec::with_capacity(count as usize);
5153 for k in 0..count {
5154 items.push(self.reg(start + k).as_runtime().clone());
5155 }
5156 self.set(
5157 dst,
5158 Value::from_runtime(RuntimeValue::Tuple(std::rc::Rc::new(items))),
5159 );
5160 pc += 1;
5161 }
5162 Op::UnionOp { dst, lhs, rhs } => {
5163 let v = crate::semantics::collections::union(
5164 &self.reg(lhs).as_runtime(),
5165 &self.reg(rhs).as_runtime(),
5166 )?;
5167 self.set(dst, Value::from_runtime(v));
5168 pc += 1;
5169 }
5170 Op::IntersectOp { dst, lhs, rhs } => {
5171 let v = crate::semantics::collections::intersection(
5172 &self.reg(lhs).as_runtime(),
5173 &self.reg(rhs).as_runtime(),
5174 )?;
5175 self.set(dst, Value::from_runtime(v));
5176 pc += 1;
5177 }
5178 Op::LoadToday { dst } => {
5179 let v = Value::from_runtime(crate::semantics::temporal::today());
5180 if RECORDING {
5181 self.record_nondet(dst, &v);
5182 }
5183 self.set(dst, v);
5184 pc += 1;
5185 }
5186 Op::LoadNow { dst } => {
5187 let v = Value::from_runtime(crate::semantics::temporal::now());
5188 if RECORDING {
5189 self.record_nondet(dst, &v);
5190 }
5191 self.set(dst, v);
5192 pc += 1;
5193 }
5194 Op::NewStruct { dst, type_name } => {
5195 use crate::interpreter::{RuntimeValue, StructValue};
5196 let name = match &self.program.constants[type_name as usize] {
5197 Constant::Text(s) => s.clone(),
5198 other => {
5199 return Err(format!("vm: NewStruct name is not Text: {:?}", other))
5200 }
5201 };
5202 self.set(
5203 dst,
5204 Value::from_runtime(RuntimeValue::Struct(Box::new(StructValue {
5205 type_name: name,
5206 fields: std::collections::HashMap::new(),
5207 }))),
5208 );
5209 pc += 1;
5210 }
5211 Op::StructInsert { obj, field, value } => {
5212 use crate::interpreter::RuntimeValue;
5213 let field_name = match &self.program.constants[field as usize] {
5214 Constant::Text(s) => s.clone(),
5215 other => return Err(format!("vm: field name is not Text: {:?}", other)),
5216 };
5217 let v = self.reg(value).as_runtime().clone();
5218 match self.reg_mut(obj).as_runtime_mut() {
5219 RuntimeValue::Struct(s) => {
5220 s.fields.insert(field_name, v);
5221 }
5222 _ => return Err("Cannot set field on non-struct value".to_string()),
5223 }
5224 pc += 1;
5225 }
5226 Op::GetField { dst, obj, field } => {
5227 use crate::interpreter::RuntimeValue;
5228 let field_name = match &self.program.constants[field as usize] {
5229 Constant::Text(s) => s.as_str(),
5230 other => return Err(format!("vm: field name is not Text: {:?}", other)),
5231 };
5232 let v = match &*self.reg(obj).as_runtime() {
5233 RuntimeValue::Struct(s) => s
5234 .fields
5235 .get(field_name)
5236 .cloned()
5237 .ok_or_else(|| format!("Field '{}' not found", field_name))?,
5238 other => {
5239 return Err(format!("Cannot access field on {}", other.type_name()));
5240 }
5241 };
5242 self.set(dst, Value::from_runtime(v));
5243 pc += 1;
5244 }
5245 Op::NewInductive {
5246 dst,
5247 type_name,
5248 ctor,
5249 args_start,
5250 count,
5251 } => {
5252 use crate::interpreter::{InductiveValue, RuntimeValue};
5253 let inductive_type = match &self.program.constants[type_name as usize] {
5254 Constant::Text(s) => s.clone(),
5255 other => return Err(format!("vm: enum name is not Text: {:?}", other)),
5256 };
5257 let constructor = match &self.program.constants[ctor as usize] {
5258 Constant::Text(s) => s.clone(),
5259 other => return Err(format!("vm: variant name is not Text: {:?}", other)),
5260 };
5261 let mut args = Vec::with_capacity(count as usize);
5262 for k in 0..count {
5263 args.push(self.reg(args_start + k).as_runtime().clone());
5264 }
5265 self.set(
5266 dst,
5267 Value::from_runtime(RuntimeValue::Inductive(std::rc::Rc::new(
5268 InductiveValue {
5269 inductive_type,
5270 constructor,
5271 args,
5272 },
5273 ))),
5274 );
5275 pc += 1;
5276 }
5277 Op::TestArm {
5278 dst,
5279 target,
5280 variant,
5281 } => {
5282 use crate::interpreter::RuntimeValue;
5283 let variant_name = match &self.program.constants[variant as usize] {
5284 Constant::Text(s) => s.as_str(),
5285 other => return Err(format!("vm: variant name is not Text: {:?}", other)),
5286 };
5287 let matched = match &*self.reg(target).as_runtime() {
5288 // A struct matches its own variant name — and ALSO a `Some` arm, because
5289 // the Option encoding is transparent: `some(a new Response …)` IS the
5290 // Response. Without the second half, `Option of <any record>` could not be
5291 // inspected at all while `Option of Int` worked, since a scalar falls to
5292 // the catch-all below. The plan's own middleware signature is
5293 // `-> Option of Response`, so the gap was load-bearing.
5294 // ★ A STRUCT MATCHES ITS OWN VARIANT NAME, and only that.
5295 //
5296 // This used to read `|| variant_name == "Some"`, because an Option was
5297 // TRANSPARENT: `some (a new Response …)` WAS the Response, so a `Some` arm
5298 // had to match a bare struct or `Option of <record>` could not be inspected
5299 // at all. An Option now carries its own tag and arrives as an
5300 // `Inductive("Option", "Some")`, matched by the arm below — so this clause
5301 // no longer covers a real case, and keeping it would make a plain record
5302 // match a `Some` arm it has nothing to do with.
5303 RuntimeValue::Struct(s) => s.type_name == variant_name,
5304 RuntimeValue::Inductive(ind) => ind.constructor == variant_name,
5305 // The transparent Option encoding: `some x` IS x and
5306 // `none` IS Nothing, so Some/None arms match presence/
5307 // absence for non-enum values (the boxed `a new Some …`
5308 // form matches through the arms above).
5309 // A BARE `Nothing` still answers a `None` arm. It is not an Option — it
5310 // is what `Try to receive` and an over-`Pop` produce — but absence is one
5311 // thing however it arrived, which is the same rule R2 gives equality.
5312 RuntimeValue::Nothing => variant_name == "None",
5313 // ★ AND THE TRANSPARENT CATCH-ALL IS GONE. It read `_ => variant_name ==
5314 // "Some"`: any value that was not the sentinel answered a `Some` arm. That
5315 // was the encoding's whole presence rule, and it is now actively wrong —
5316 // a bare `7` is an Int, not a present Option, and saying otherwise is how
5317 // `some 0` and `none` became indistinguishable in the first place.
5318 _ => false,
5319 };
5320 self.set(dst, Value::bool(matched));
5321 pc += 1;
5322 }
5323 Op::BindArm {
5324 dst,
5325 target,
5326 field,
5327 index,
5328 } => {
5329 use crate::interpreter::RuntimeValue;
5330 let v = match &*self.reg(target).as_runtime() {
5331 RuntimeValue::Struct(st) => {
5332 let field_name = match &self.program.constants[field as usize] {
5333 Constant::Text(s) => s.as_str(),
5334 other => {
5335 return Err(format!("vm: field name is not Text: {:?}", other));
5336 }
5337 };
5338 // A real struct arm binds a FIELD. A `Some` arm over a struct binds
5339 // the WHOLE value, and the compiler says which by emitting a reserved
5340 // marker no identifier can spell instead of a field name.
5341 //
5342 // "any field miss binds the whole value" was the first version of this
5343 // and it was WRONG: `When Circle (r)` — a real struct arm naming a
5344 // field that does not exist — errors on the tree-walker and would have
5345 // silently bound the whole Circle here, a tier divergence introduced
5346 // by the fix for a different one.
5347 if field_name == crate::vm::SOME_BINDING_MARKER {
5348 Some(self.reg(target).as_runtime().as_ref().clone())
5349 } else {
5350 match st.fields.get(field_name) {
5351 Some(v) => Some(v.clone()),
5352 // A record arm naming a field the record does not have. The
5353 // tree-walker leaves the name unbound and fails at its first
5354 // USE ("Undefined variable: r"); this tier had no unbound
5355 // register, so it read whatever the slot held and printed it —
5356 // a silent wrong answer where the reference tier errors. In
5357 // the source form `When Circle (r)` the binding name IS the
5358 // field name, so the same words are available here.
5359 None => {
5360 return Err(format!("Undefined variable: {field_name}"));
5361 }
5362 }
5363 }
5364 }
5365 RuntimeValue::Inductive(ind) => ind.args.get(index as usize).cloned(),
5366 // Transparent `some x`: the matched Some arm's single
5367 // binding receives the value itself (BindArm only runs
5368 // after this arm's TestArm accepted the target).
5369 RuntimeValue::Nothing => None,
5370 other => (index == 0).then(|| other.clone()),
5371 };
5372 if let Some(v) = v {
5373 self.set(dst, Value::from_runtime(v));
5374 }
5375 pc += 1;
5376 }
5377 Op::CrdtBump {
5378 obj,
5379 field,
5380 amount,
5381 negate,
5382 } => {
5383 use crate::interpreter::RuntimeValue;
5384 let amount_int = match &*self.reg(amount).as_runtime() {
5385 RuntimeValue::Int(n) => *n,
5386 _ => {
5387 return Err(if negate {
5388 "CRDT decrement amount must be an integer".to_string()
5389 } else {
5390 "CRDT increment amount must be an integer".to_string()
5391 });
5392 }
5393 };
5394 let amount_int = if negate {
5395 amount_int.wrapping_neg()
5396 } else {
5397 amount_int
5398 };
5399 let field_name = match &self.program.constants[field as usize] {
5400 Constant::Text(s) => s.clone(),
5401 other => return Err(format!("vm: field name is not Text: {:?}", other)),
5402 };
5403 match self.reg_mut(obj).as_runtime_mut() {
5404 RuntimeValue::Struct(s) => {
5405 let current = s
5406 .fields
5407 .get(&field_name)
5408 .cloned()
5409 .unwrap_or(RuntimeValue::Int(0));
5410 let new_val = crate::semantics::arith::crdt_counter_bump(
5411 current,
5412 amount_int,
5413 &field_name,
5414 )?;
5415 s.fields.insert(field_name, new_val);
5416 }
5417 _ => {
5418 return Err(if negate {
5419 "Cannot decrease field on non-struct value".to_string()
5420 } else {
5421 "Cannot increase field on non-struct value".to_string()
5422 });
5423 }
5424 }
5425 pc += 1;
5426 }
5427 Op::CrdtMerge { target, source } => {
5428 use crate::interpreter::RuntimeValue;
5429 let source_fields = match &*self.reg(source).as_runtime() {
5430 RuntimeValue::Struct(s) => s.fields.clone(),
5431 _ => return Err("Merge source must be a struct".to_string()),
5432 };
5433 match self.reg_mut(target).as_runtime_mut() {
5434 RuntimeValue::Struct(s) => {
5435 for (field_name, incoming) in source_fields {
5436 let current = s
5437 .fields
5438 .get(&field_name)
5439 .cloned()
5440 .unwrap_or(RuntimeValue::Int(0));
5441 let merged =
5442 crate::semantics::arith::crdt_merge_field(¤t, incoming);
5443 s.fields.insert(field_name, merged);
5444 }
5445 }
5446 _ => return Err("Merge target must be a struct".to_string()),
5447 }
5448 pc += 1;
5449 }
5450 Op::CrdtJoin { target, source } => {
5451 // The state-based G-Counter LATTICE JOIN: per-replica MAX (idempotent), the
5452 // fixed-lane join the `crdt_merge` hardware block computes. Unlike CrdtMerge's
5453 // polymorphic field-wise merge (ADD for bare-int counters), this is unconditional
5454 // per-field MAX — so a redelivered/duplicated counter state never double-counts.
5455 use crate::interpreter::RuntimeValue;
5456 let source_fields = match &*self.reg(source).as_runtime() {
5457 RuntimeValue::Struct(s) => s.fields.clone(),
5458 _ => return Err("Join source must be a struct".to_string()),
5459 };
5460 match self.reg_mut(target).as_runtime_mut() {
5461 RuntimeValue::Struct(s) => {
5462 for (field_name, incoming) in source_fields {
5463 let current = s
5464 .fields
5465 .get(&field_name)
5466 .cloned()
5467 .unwrap_or(RuntimeValue::Int(0));
5468 let joined =
5469 crate::semantics::arith::crdt_join_field(¤t, incoming);
5470 s.fields.insert(field_name, joined);
5471 }
5472 }
5473 _ => return Err("Join target must be a struct".to_string()),
5474 }
5475 pc += 1;
5476 }
5477 Op::BigIntWide { kind, dst, a, b } => {
5478 // The 256-bit BigInt lane. On the soft-core the operands live in an 8×256-bit wide
5479 // register bank routed to bigint_alu/div/mul; in the VM they live in the register
5480 // file as BigInt (arbitrary precision), so the same arithmetic reuses Value's ops.
5481 use crate::interpreter::RuntimeValue;
5482 match kind {
5483 0 => {
5484 let v = self.reg(a).clone();
5485 *self.reg_mut(dst) = v;
5486 } // FromInt: R[dst] = R[a]
5487 1 => self.binop(dst, a, b, Value::add)?, // Add
5488 2 => self.binop(dst, a, b, Value::sub)?, // Sub
5489 3 => self.binop(dst, a, b, Value::lt)?, // Cmp: R[dst] = R[a] < R[b]
5490 4 => {
5491 // Low: R[dst] = R[a] mod 2^32
5492 let lo = match &*self.reg(a).as_runtime() {
5493 RuntimeValue::Int(n) => (*n as u32) as i64,
5494 _ => 0,
5495 };
5496 *self.reg_mut(dst) = Value::int(lo);
5497 }
5498 5 => self.binop(dst, a, b, Value::div)?, // Div
5499 6 => self.binop(dst, a, b, Value::mul)?, // Mul
5500 _ => {}
5501 }
5502 pc += 1;
5503 }
5504 Op::NewCrdt { dst, kind } => {
5505 use crate::interpreter::RuntimeValue;
5506 let cv = crate::semantics::crdt::CrdtKind::from_new_crdt_code(kind)
5507 .ok_or_else(|| format!("vm: unknown CRDT kind {kind}"))?
5508 .fresh();
5509 let v = Value::from_runtime(RuntimeValue::Crdt(std::rc::Rc::new(
5510 std::cell::RefCell::new(cv),
5511 )));
5512 // The replica id was drawn from a global counter — captured nondeterminism (the
5513 // same treatment as a clock read): reverse restores dst, leaving the counter drawn.
5514 if RECORDING {
5515 self.record_nondet(dst, &v);
5516 }
5517 self.set(dst, v);
5518 pc += 1;
5519 }
5520 Op::CrdtAppend { seq, value } => {
5521 use crate::interpreter::RuntimeValue;
5522 let v = self.reg(value).as_runtime().clone();
5523 let seq_rt = self.reg(seq).as_runtime();
5524 match &*seq_rt {
5525 RuntimeValue::Crdt(rc) => rc.borrow_mut().append(&v)?,
5526 RuntimeValue::List(_) => {
5527 crate::semantics::collections::list_push(&seq_rt, v)?
5528 }
5529 other => return Err(format!("Cannot append to {}", other.type_name())),
5530 }
5531 pc += 1;
5532 }
5533 Op::CrdtResolve { obj, field, value } => {
5534 use crate::interpreter::RuntimeValue;
5535 let v = self.reg(value).as_runtime().clone();
5536 let field_name = match &self.program.constants[field as usize] {
5537 Constant::Text(s) => s.clone(),
5538 other => return Err(format!("vm: field name is not Text: {:?}", other)),
5539 };
5540 match self.reg_mut(obj).as_runtime_mut() {
5541 RuntimeValue::Struct(s) => {
5542 // A real divergent register resolves in place via its shared
5543 // `Rc`; a plain field is overwritten — same fallback as the
5544 // tree-walker's `Resolve`.
5545 let is_register =
5546 matches!(s.fields.get(&field_name), Some(RuntimeValue::Crdt(_)));
5547 if is_register {
5548 if let Some(RuntimeValue::Crdt(rc)) = s.fields.get(&field_name) {
5549 rc.borrow_mut().resolve(&v)?;
5550 }
5551 } else {
5552 s.fields.insert(field_name, v);
5553 }
5554 }
5555 other => {
5556 return Err(format!("Cannot resolve a field on {}", other.type_name()))
5557 }
5558 }
5559 pc += 1;
5560 }
5561 Op::IterPrepare { iterable } => {
5562 let items = crate::semantics::collections::iteration_snapshot(
5563 &self.reg(iterable).as_runtime(),
5564 )?;
5565 self.iter_stack
5566 .push((items.into_iter().map(Value::from_runtime).collect(), 0));
5567 pc += 1;
5568 }
5569 Op::IterNext { dst, exit } => {
5570 let (items, idx) = self
5571 .iter_stack
5572 .last_mut()
5573 .ok_or("vm: IterNext with no live iterator")?;
5574 if *idx < items.len() {
5575 let v = items[*idx].clone();
5576 *idx += 1;
5577 // (the iter_stack borrow ends above via NLL — recording is dead-stripped when
5578 // `RECORDING = false`, so the hot loop is byte-for-byte unchanged.)
5579 if RECORDING {
5580 let dst_slot = self.base + dst as usize;
5581 let dst_old = self.registers[dst_slot].clone();
5582 if let Some(j) = self.journal.as_mut() {
5583 j.push(super::journal::JournalEntry::IterNextUndo {
5584 advanced: true,
5585 dst_slot,
5586 dst_old,
5587 });
5588 }
5589 }
5590 self.set(dst, v);
5591 pc += 1;
5592 } else {
5593 if RECORDING {
5594 if let Some(j) = self.journal.as_mut() {
5595 j.push(super::journal::JournalEntry::IterNextUndo {
5596 advanced: false,
5597 dst_slot: 0,
5598 dst_old: Value::nothing(),
5599 });
5600 }
5601 }
5602 pc = exit;
5603 }
5604 }
5605 Op::IterPop => {
5606 if RECORDING {
5607 if let Some((items, idx)) = self.iter_stack.last().cloned() {
5608 if let Some(j) = self.journal.as_mut() {
5609 j.push(super::journal::JournalEntry::IterPopUndo { items, idx });
5610 }
5611 }
5612 }
5613 self.iter_stack
5614 .pop()
5615 .ok_or("vm: IterPop with no live iterator")?;
5616 pc += 1;
5617 }
5618 Op::ListPop { list, dst } => {
5619 self.ensure_reg_owned(list, pc, call_stack.last().map(|f| f.func));
5620 let v = crate::semantics::collections::list_pop(&self.reg(list).as_runtime())?;
5621 self.set(dst, Value::from_runtime(v));
5622 pc += 1;
5623 }
5624 Op::Sleep { duration } => {
5625 // A VM `Sleep` only ever runs inside a task (a non-concurrent program
5626 // with `Sleep` routes to the async tree-walker, never the VM). Route it
5627 // through the scheduler's virtual timer — the same logical-tick scale as
5628 // a `Select` `After` arm — by yielding `VmBlock::Sleep`. Blocking on a
5629 // real host timer here would stall the cooperative scheduler (and errors
5630 // outright on wasm).
5631 let ticks = self.as_ticks(duration)?;
5632 if ticks > 0 {
5633 return Ok(self.block(pc + 1, call_stack, VmBlock::Sleep(ticks), None));
5634 }
5635 pc += 1;
5636 }
5637 Op::DestructureTuple { src, start, count } => {
5638 use crate::interpreter::RuntimeValue;
5639 match &*self.reg(src).as_runtime() {
5640 RuntimeValue::Tuple(items) => {
5641 // Arity is LOUD — a silent truncation binds ghosts.
5642 if items.len() != count as usize {
5643 return Err(format!(
5644 "Cannot bind a {}-tuple to {} names",
5645 items.len(),
5646 count
5647 ));
5648 }
5649 let items: Vec<Value> = items
5650 .iter()
5651 .take(count as usize)
5652 .cloned()
5653 .map(Value::from_runtime)
5654 .collect();
5655 for (i, v) in items.into_iter().enumerate() {
5656 self.set(start + i as Reg, v);
5657 }
5658 }
5659 other => {
5660 return Err(format!(
5661 "Expected tuple for pattern, got {}",
5662 other.type_name()
5663 ));
5664 }
5665 }
5666 pc += 1;
5667 }
5668 Op::Show { src } => {
5669 self.lines.push(self.reg(src).to_display_string());
5670 pc += 1;
5671 }
5672 Op::Obs {
5673 site,
5674 args_start,
5675 args_count,
5676 } => {
5677 // Wave 13 — emit the observation event the OBSERVED-profile
5678 // compiler recorded. No-op when no sink is capturing, so the
5679 // op costs a single branch off the hot path.
5680 if crate::observe::capturing() {
5681 let desc = &self.program.observation_sites[site as usize];
5682 match &desc.kind {
5683 ObsSiteKind::SpanEnter => {
5684 crate::observe::enter_span(desc.message.clone())
5685 }
5686 ObsSiteKind::SpanExit => {
5687 crate::observe::exit_span(desc.message.clone())
5688 }
5689 ObsSiteKind::Message(cat) => {
5690 let mut vals = Vec::with_capacity(args_count as usize);
5691 for i in 0..args_count {
5692 let v = self.reg(args_start + i).to_display_string();
5693 vals.push((desc.payload_names[i as usize].clone(), v));
5694 }
5695 crate::observe::emit(
5696 *cat,
5697 desc.message.clone(),
5698 vals,
5699 desc.sample,
5700 site as u64,
5701 );
5702 }
5703 }
5704 }
5705 pc += 1;
5706 }
5707 Op::Args { dst } => {
5708 use crate::interpreter::RuntimeValue;
5709 let items: Vec<RuntimeValue> = self
5710 .program_args
5711 .iter()
5712 .map(|s| RuntimeValue::Text(std::rc::Rc::new(s.clone())))
5713 .collect();
5714 let list = RuntimeValue::List(std::rc::Rc::new(std::cell::RefCell::new(
5715 crate::interpreter::ListRepr::from_values(items),
5716 )));
5717 self.set(dst, Value::from_runtime(list));
5718 pc += 1;
5719 }
5720 // Go-like concurrency (T11). Each op materialises its operands,
5721 // then suspends the slice — `self.block` saves the resume point
5722 // and the request; the scheduler driver services it and re-enters.
5723 Op::ChanNew { dst, cap, .. } => {
5724 let capacity = if cap < 0 { None } else { Some(cap as usize) };
5725 return Ok(self.block(
5726 pc + 1,
5727 call_stack,
5728 VmBlock::NewChan(capacity),
5729 Some(dst),
5730 ));
5731 }
5732 Op::ChanSend { chan, val } => {
5733 let ch = self.as_chan(chan)?;
5734 let payload = self.materialize_reg(val)?;
5735 return Ok(self.block(pc + 1, call_stack, VmBlock::Send(ch, payload), None));
5736 }
5737 Op::ChanRecv { dst, chan } => {
5738 let ch = self.as_chan(chan)?;
5739 return Ok(self.block(pc + 1, call_stack, VmBlock::Recv(ch), Some(dst)));
5740 }
5741 Op::ChanTrySend { dst, chan, val } => {
5742 let ch = self.as_chan(chan)?;
5743 let payload = self.materialize_reg(val)?;
5744 return Ok(self.block(
5745 pc + 1,
5746 call_stack,
5747 VmBlock::TrySend(ch, payload),
5748 Some(dst),
5749 ));
5750 }
5751 Op::ChanTryRecv { dst, chan } => {
5752 let ch = self.as_chan(chan)?;
5753 return Ok(self.block(pc + 1, call_stack, VmBlock::TryRecv(ch), Some(dst)));
5754 }
5755 Op::ChanClose { chan } => {
5756 let ch = self.as_chan(chan)?;
5757 return Ok(self.block(pc + 1, call_stack, VmBlock::Close(ch), None));
5758 }
5759 Op::TaskAwait { dst, handle } => {
5760 let tid = self.as_task(handle)?;
5761 return Ok(self.block(pc + 1, call_stack, VmBlock::Await(tid), Some(dst)));
5762 }
5763 Op::TaskAbort { handle } => {
5764 let tid = self.as_task(handle)?;
5765 return Ok(self.block(pc + 1, call_stack, VmBlock::Abort(tid), None));
5766 }
5767 Op::Spawn {
5768 func,
5769 args_start,
5770 arg_count,
5771 } => {
5772 let args = self.materialize_args(args_start, arg_count)?;
5773 let req = VmBlock::SpawnDesc {
5774 func,
5775 args,
5776 want_handle: false,
5777 };
5778 return Ok(self.block(pc + 1, call_stack, req, None));
5779 }
5780 Op::SpawnHandle {
5781 dst,
5782 func,
5783 args_start,
5784 arg_count,
5785 } => {
5786 let args = self.materialize_args(args_start, arg_count)?;
5787 let req = VmBlock::SpawnDesc {
5788 func,
5789 args,
5790 want_handle: true,
5791 };
5792 return Ok(self.block(pc + 1, call_stack, req, Some(dst)));
5793 }
5794 Op::SelectArmRecv { chan, var } => {
5795 let ch = self.as_chan(chan)?;
5796 self.select_pending.push((SelectArm::Recv(ch), Some(var)));
5797 pc += 1;
5798 }
5799 Op::SelectArmTimeout { ticks } => {
5800 let t = self.as_ticks(ticks)?;
5801 self.select_pending.push((SelectArm::Timeout(t), None));
5802 pc += 1;
5803 }
5804 Op::SelectWait { dst_arm } => {
5805 let arms: Vec<SelectArm> =
5806 self.select_pending.iter().map(|(a, _)| a.clone()).collect();
5807 return Ok(self.block(
5808 pc + 1,
5809 call_stack,
5810 VmBlock::Select(arms),
5811 Some(dst_arm),
5812 ));
5813 }
5814 // Peer networking: materialise the operands and suspend; the async VM driver
5815 // services the request through the shared `NetInbox` (the same inbox the
5816 // tree-walker uses) and resumes — `NetAwait` resumes with the received value.
5817 Op::NetConnect { url } => {
5818 let u = self.materialize_reg(url)?;
5819 return Ok(self.block(pc + 1, call_stack, VmBlock::NetConnect(u), None));
5820 }
5821 Op::NetListen { topic } => {
5822 let t = self.materialize_reg(topic)?;
5823 return Ok(self.block(pc + 1, call_stack, VmBlock::NetListen(t), None));
5824 }
5825 Op::NetSend { to, msg } => {
5826 let t = self.materialize_reg(to)?;
5827 let m = self.materialize_reg(msg)?;
5828 return Ok(self.block(pc + 1, call_stack, VmBlock::NetSend(t, m), None));
5829 }
5830 Op::NetStream { to, values } => {
5831 let t = self.materialize_reg(to)?;
5832 let v = self.materialize_reg(values)?;
5833 return Ok(self.block(pc + 1, call_stack, VmBlock::NetStream(t, v), None));
5834 }
5835 Op::NetAwait { dst, from, stream } => {
5836 let f = self.materialize_reg(from)?;
5837 return Ok(self.block(
5838 pc + 1,
5839 call_stack,
5840 VmBlock::NetAwait(f, stream),
5841 Some(dst),
5842 ));
5843 }
5844 Op::NetMakePeer { dst, addr } => {
5845 let a = self.materialize_reg(addr)?;
5846 return Ok(self.block(pc + 1, call_stack, VmBlock::NetMakePeer(a), Some(dst)));
5847 }
5848 Op::NetSync { dst, topic } => {
5849 let current = self.materialize_reg(dst)?;
5850 let t = self.materialize_reg(topic)?;
5851 return Ok(self.block(
5852 pc + 1,
5853 call_stack,
5854 VmBlock::NetSync(t, current),
5855 Some(dst),
5856 ));
5857 }
5858 // tcp.lg natives: materialise the operands and suspend; the async io
5859 // driver services the request through the SAME `TcpRegistry::exec_values`
5860 // the tree-walker calls, so the tiers cannot drift.
5861 Op::Tcp {
5862 dst,
5863 kind,
5864 args_start,
5865 arg_count,
5866 } => {
5867 let args = self.materialize_args(args_start, arg_count)?;
5868 return Ok(self.block(pc + 1, call_stack, VmBlock::Tcp(kind, args), Some(dst)));
5869 }
5870 // `Serve` on the async io driver: read the port and suspend. The
5871 // driver owns the accept loop and re-enters `handler` per
5872 // connection as a fresh child VM; the loop never returns, so no
5873 // resume slot is reserved.
5874 Op::Serve { port, handler } => {
5875 let port = match &*self.reg(port).as_runtime() {
5876 crate::interpreter::RuntimeValue::Int(n) if (0..=65535).contains(n) => {
5877 *n as u16
5878 }
5879 crate::interpreter::RuntimeValue::Int(n) => {
5880 return Err(format!("Serve: port {n} is out of range (0-65535)"))
5881 }
5882 other => {
5883 return Err(format!(
5884 "Serve: port must be an Int, got {}",
5885 other.type_name()
5886 ))
5887 }
5888 };
5889 return Ok(self.block(pc + 1, call_stack, VmBlock::Serve(port, handler), None));
5890 }
5891 Op::FailWith { msg } => {
5892 return Err(match &self.program.constants[msg as usize] {
5893 Constant::Text(s) => s.clone(),
5894 other => format!("vm: FailWith constant is not Text: {:?}", other),
5895 });
5896 }
5897 Op::Halt => break,
5898 }
5899 }
5900 Ok(VmStep::Done(crate::interpreter::RuntimeValue::Nothing))
5901 }
5902
5903 /// Enter function `func` with its arguments in registers `args_start..args_start +
5904 /// arg_count` of the current frame, answering the pc to continue at.
5905 ///
5906 /// A call that completes without a bytecode frame — the pbkdf2 accelerator, the native tier,
5907 /// the WASM-JIT tier — has already written its result into `dst` and answers `return_pc`.
5908 /// A precise deopt answers the pc the materialized frames resume at. Otherwise the callee's
5909 /// frame is pushed (warm body first, then baseline) and its entry pc is answered. The one call
5910 /// path behind `Op::Call` and [`Vm::invoke_function`].
5911 #[inline(always)]
5912 fn enter_call<const RECORDING: bool>(
5913 &mut self,
5914 dst: Reg,
5915 func: FuncIdx,
5916 args_start: Reg,
5917 arg_count: u16,
5918 return_pc: usize,
5919 call_stack: &mut Vec<CallFrame>,
5920 ) -> Result<usize, String> {
5921 // Native-accelerate crypto.lg's pbkdf2Sha256 — byte-identical to the pure body
5922 // (crypto_accel_lock.rs), but ~16k interpreted SHA-256 compressions is untenable as
5923 // bytecode for a live SCRAM handshake. Skipped under reverse recording so the pure path
5924 // stays reversible.
5925 if !RECORDING && Some(func) == self.accel_pbkdf2 && arg_count == 3 {
5926 let a0 = self.reg(args_start).as_runtime().clone();
5927 let a1 = self.reg(args_start + 1).as_runtime().clone();
5928 let a2 = self.reg(args_start + 2).as_runtime().clone();
5929 let (pw, salt, iters) = crate::semantics::builtins::pbkdf2_arguments(&a0, &a1, &a2)?;
5930 let dk = crate::crypto_accel::pbkdf2_sha256(&pw, &salt, iters);
5931 self.set(
5932 dst,
5933 Value::from_runtime(crate::semantics::builtins::bytes_to_seq(&dk)),
5934 );
5935 self.clear_args(args_start, arg_count, Some(func));
5936 return Ok(return_pc);
5937 }
5938 if call_stack.len() >= crate::semantics::MAX_CALL_DEPTH {
5939 return Err(crate::semantics::CALL_DEPTH_ERR.to_string());
5940 }
5941 // Reverse recording covers the interpreter frame teardown only; a native/deopt call has
5942 // effects the frame journal doesn't capture, so decline rather than mis-reverse. (A fresh
5943 // recording VM has `tier: None`, so this never fires there.)
5944 if RECORDING && self.tier.is_some() {
5945 return Err("vm: reverse recording does not support the native tier".to_string());
5946 }
5947 match self.try_native(func, args_start, arg_count, call_stack.len()) {
5948 NativeDisposition::Done(v) => {
5949 self.set(dst, v);
5950 self.clear_args(args_start, arg_count, Some(func));
5951 return Ok(return_pc);
5952 }
5953 NativeDisposition::Interpret => {}
5954 // Precise deopt: every native frame becomes a real CallFrame (registers re-boxed per
5955 // the adapter's kind capture), then the interpreter resumes AT the faulting op —
5956 // effects stay, the kernel raises the exact error from the exact state.
5957 NativeDisposition::Materialize {
5958 resume_pc,
5959 frames,
5960 list_args,
5961 } => {
5962 self.materialize_native_frames(
5963 &frames, &list_args, args_start, dst, func, return_pc, call_stack,
5964 )?;
5965 return Ok(resume_pc);
5966 }
5967 }
5968 // WS6 (Phase 13): the WASM-JIT tier — the browser JIT path, consulted here (behind the
5969 // native forge tier above, which is absent on wasm32). A hot pure-integer function runs
5970 // its emitted WebAssembly module instead of the bytecode; non-Int args or an ineligible
5971 // body fall through.
5972 #[cfg(feature = "wasm-jit")]
5973 {
5974 let prog = self.program;
5975 let abase = self.base + args_start as usize;
5976 let mut ints: Vec<i64> = Vec::with_capacity(arg_count as usize);
5977 let mut all_int = true;
5978 for k in 0..arg_count as usize {
5979 match &*self.registers[abase + k].as_runtime() {
5980 crate::interpreter::RuntimeValue::Int(n) => ints.push(*n),
5981 _ => {
5982 all_int = false;
5983 break;
5984 }
5985 }
5986 }
5987 if all_int {
5988 if let Some(r) = self.wasm_tier.on_call(prog, func, &ints) {
5989 self.set(dst, Value::int(r));
5990 return Ok(return_pc);
5991 }
5992 }
5993 }
5994 // Dispatch order (HOTSWAP §7): FnTable native (above) → warm_bytecode → baseline. A warm
5995 // body runs from the unified pc space past `program.code`.
5996 let (entry_pc, reg_count) = match self.warm_entry.get(func as usize).and_then(|w| *w) {
5997 Some(w) => (w.entry_pc, w.register_count),
5998 None => {
5999 let f = self
6000 .program
6001 .functions
6002 .get(func as usize)
6003 .ok_or("vm: call to undefined function index")?;
6004 (f.entry_pc, f.register_count)
6005 }
6006 };
6007 let callee_base = self.base + args_start as usize;
6008 let restore_len = self.registers.len();
6009 let needed = callee_base + reg_count;
6010 if needed > MAX_REGISTER_FILE {
6011 return Err("vm: register file limit exceeded".to_string());
6012 }
6013 if self.registers.len() < needed {
6014 self.registers.resize(needed, Value::nothing());
6015 }
6016 if RECORDING {
6017 if let Some(j) = self.journal.as_mut() {
6018 j.push(super::journal::JournalEntry::CallUndo { restore_len });
6019 }
6020 }
6021 call_stack.push(CallFrame {
6022 return_pc,
6023 return_reg: dst,
6024 caller_base: self.base,
6025 restore_len,
6026 iter_depth: self.iter_stack.len(),
6027 func,
6028 arg_lo: callee_base,
6029 arg_count,
6030 });
6031 self.base = callee_base;
6032 Ok(entry_pc)
6033 }
6034
6035 /// Enter `closure` with its arguments in registers `args_start..args_start + arg_count` of
6036 /// the current frame: push its frame, bind its captures, and answer its entry pc. The one
6037 /// closure-call path behind `Op::CallValue` and [`Vm::call_closure`].
6038 #[inline(always)]
6039 fn enter_closure<const RECORDING: bool>(
6040 &mut self,
6041 dst: Reg,
6042 closure: &crate::interpreter::ClosureValue,
6043 args_start: Reg,
6044 arg_count: u16,
6045 return_pc: usize,
6046 call_stack: &mut Vec<CallFrame>,
6047 ) -> Result<usize, String> {
6048 if call_stack.len() >= crate::semantics::MAX_CALL_DEPTH {
6049 return Err(crate::semantics::CALL_DEPTH_ERR.to_string());
6050 }
6051 let f = self
6052 .program
6053 .functions
6054 .get(closure.body_index)
6055 .ok_or("vm: CallValue on undefined function index")?;
6056 if arg_count as usize != f.param_count as usize {
6057 return Err(format!(
6058 "Closure expects {} arguments, got {}",
6059 f.param_count, arg_count
6060 ));
6061 }
6062 let entry_pc = f.entry_pc;
6063 let reg_count = f.register_count;
6064 let captures = f.captures.clone();
6065 let param_count = f.param_count;
6066
6067 let callee_base = self.base + args_start as usize;
6068 let restore_len = self.registers.len();
6069 let needed = callee_base + reg_count;
6070 if needed > MAX_REGISTER_FILE {
6071 return Err("vm: register file limit exceeded".to_string());
6072 }
6073 if self.registers.len() < needed {
6074 self.registers.resize(needed, Value::nothing());
6075 }
6076 call_stack.push(CallFrame {
6077 return_pc,
6078 return_reg: dst,
6079 caller_base: self.base,
6080 restore_len,
6081 iter_depth: self.iter_stack.len(),
6082 func: closure.body_index as u16,
6083 arg_lo: callee_base,
6084 arg_count,
6085 });
6086 self.base = callee_base;
6087 // Bind captures: value slots then present flags — both deep-cloned PER CALL (the
6088 // tree-walker re-clones each invocation).
6089 let cap_count = captures.len() as Reg;
6090 if RECORDING {
6091 let mut caps = Vec::with_capacity(captures.len() * 2);
6092 for k in 0..cap_count {
6093 let vslot = self.base + (param_count + k) as usize;
6094 let pslot = self.base + (param_count + cap_count + k) as usize;
6095 caps.push((vslot, self.registers[vslot].clone()));
6096 caps.push((pslot, self.registers[pslot].clone()));
6097 }
6098 if let Some(j) = self.journal.as_mut() {
6099 j.push(super::journal::JournalEntry::CallValueUndo {
6100 restore_len,
6101 captures: caps,
6102 });
6103 }
6104 }
6105 for (k, (sym, _)) in captures.iter().enumerate() {
6106 let (v, present) = match closure.captured_env.get(sym) {
6107 Some(v) => (Value::from_runtime(v.deep_clone()), true),
6108 None => (Value::nothing(), false),
6109 };
6110 self.set(param_count + k as Reg, v);
6111 self.set(param_count + cap_count + k as Reg, Value::bool(present));
6112 }
6113 Ok(entry_pc)
6114 }
6115
6116 #[inline]
6117 fn reg(&self, r: Reg) -> &Value {
6118 &self.registers[self.base + r as usize]
6119 }
6120
6121 #[inline]
6122 fn set(&mut self, r: Reg, v: Value) {
6123 let slot = self.base + r as usize;
6124 self.registers[slot] = v;
6125 }
6126
6127 #[inline]
6128 fn reg_mut(&mut self, r: Reg) -> &mut Value {
6129 let slot = self.base + r as usize;
6130 &mut self.registers[slot]
6131 }
6132
6133 // ─── Scheduler-driver hooks (T11) ───────────────────────────────────────
6134
6135 /// Save the suspended `pc` + call stack and the request; the slice returns
6136 /// [`VmStep::Blocked`]. `slot` is the register the resume value lands in.
6137 fn block(
6138 &mut self,
6139 resume_pc: usize,
6140 call_stack: Vec<CallFrame>,
6141 req: VmBlock,
6142 slot: Option<Reg>,
6143 ) -> VmStep {
6144 self.sched_pc = resume_pc;
6145 self.sched_call_stack = call_stack;
6146 self.sched_active = true;
6147 self.resume_wraps_option = matches!(req, VmBlock::TryRecv(_));
6148 self.pending = Some(req);
6149 self.resume_slot = slot;
6150 VmStep::Blocked
6151 }
6152
6153 // ─── Debug-drawer hooks (single-task, bytecode tier) ─────────────────────
6154
6155 /// Build a [`DebugView`] of the paused VM: the call frames with their register
6156 /// values, the globals, the output, and the program counter (the op about to
6157 /// execute). Reconstructs each frame's register window from the saved call
6158 /// stack — Main has base 0; frame `k`'s base is the next frame's `caller_base`
6159 /// (the innermost is the live `self.base`).
6160 pub(crate) fn debug_view(&self) -> DebugView {
6161 let prog = self.program;
6162 let frames = self
6163 .active_frames()
6164 .into_iter()
6165 .map(|(func, base, count)| self.frame_view(func, base, count))
6166 .collect();
6167 let globals = prog
6168 .globals
6169 .iter()
6170 .enumerate()
6171 .filter_map(|(i, name)| {
6172 self.globals
6173 .get(i)
6174 .and_then(|o| o.as_ref())
6175 .map(|v| (name.clone(), v.to_display_string()))
6176 })
6177 .collect();
6178 DebugView {
6179 pc: self.sched_pc,
6180 frames,
6181 globals,
6182 output: self.lines.clone(),
6183 }
6184 }
6185
6186 /// The live call frames, Main first: each one's function (`None` for Main), the base
6187 /// of its registers in the register file, and how many it has.
6188 fn active_frames(&self) -> Vec<(Option<u16>, usize, usize)> {
6189 let prog = self.program;
6190 let cs = &self.sched_call_stack;
6191 let mut frames = Vec::with_capacity(cs.len() + 1);
6192 frames.push((None, 0, prog.register_count));
6193 for (k, fr) in cs.iter().enumerate() {
6194 let base = cs.get(k + 1).map(|n| n.caller_base).unwrap_or(self.base);
6195 let count = prog
6196 .functions
6197 .get(fr.func as usize)
6198 .map(|f| f.register_count)
6199 .unwrap_or(0);
6200 frames.push((Some(fr.func), base, count));
6201 }
6202 frames
6203 }
6204
6205 fn frame_view(&self, func: Option<u16>, base: usize, count: usize) -> DebugFrameView {
6206 let registers = (0..count)
6207 .filter_map(|i| {
6208 self.registers.get(base + i).map(|v| {
6209 // `as_runtime` (not `as_runtime_ref`) so inline scalars report their
6210 // type too — under the narrow-value repr `as_runtime_ref` is `None` for
6211 // an inline Int/Float/Bool, but the type is still well-defined.
6212 let kind = v.as_runtime().type_name().to_string();
6213 (i as u16, kind, v.to_display_string())
6214 })
6215 })
6216 .collect();
6217 DebugFrameView {
6218 func,
6219 base,
6220 registers,
6221 }
6222 }
6223
6224 /// Walk the roots (the current frame's registers + the globals) and collect the
6225 /// distinct heap objects they reach, recording each object's reference count and
6226 /// every root that points at it — so a shared list shows up once with two
6227 /// referrers (the `let b be a` aliasing that trips up every beginner).
6228 pub(crate) fn debug_heap(&self) -> Vec<HeapObjView> {
6229 let prog = self.program;
6230 let (count, is_main) = match self.sched_call_stack.last() {
6231 Some(fr) => (
6232 prog.functions
6233 .get(fr.func as usize)
6234 .map(|f| f.register_count)
6235 .unwrap_or(0),
6236 false,
6237 ),
6238 None => (prog.register_count, true),
6239 };
6240 let name_of = |i: usize| -> String {
6241 if is_main {
6242 prog.reg_names
6243 .iter()
6244 .find(|(r, _)| *r as usize == i)
6245 .map(|(_, n)| n.clone())
6246 .unwrap_or_else(|| format!("R{i}"))
6247 } else {
6248 format!("R{i}")
6249 }
6250 };
6251 // The program's own handles: every live frame's registers, the globals, and the
6252 // values loops are iterating — not the copies the debugger keeps for rewinding.
6253 let frames = self.active_frames();
6254 let handles = count_handles(
6255 frames
6256 .iter()
6257 .flat_map(|&(_, base, count)| self.registers.iter().skip(base).take(count))
6258 .chain(self.globals.iter().flatten())
6259 .chain(self.iter_stack.iter().flat_map(|(items, _)| items.iter()))
6260 .filter_map(|v| v.as_runtime_ref()),
6261 );
6262 let mut objs: Vec<HeapObjView> = Vec::new();
6263 let add = |v: &Value, root: String, objs: &mut Vec<HeapObjView>| {
6264 if let Some((id, kind, storage)) = heap_identity(v) {
6265 let rc = handles.get(&id).copied().unwrap_or(1);
6266 match objs.iter_mut().find(|o| o.id == id) {
6267 Some(o) => {
6268 if !o.referenced_by.contains(&root) {
6269 o.referenced_by.push(root);
6270 }
6271 }
6272 None => objs.push(HeapObjView {
6273 id,
6274 kind,
6275 summary: v.to_display_string(),
6276 storage,
6277 rc,
6278 referenced_by: vec![root],
6279 }),
6280 }
6281 }
6282 };
6283 for i in 0..count {
6284 if let Some(v) = self.registers.get(self.base + i) {
6285 add(v, name_of(i), &mut objs);
6286 }
6287 }
6288 for (i, name) in prog.globals.iter().enumerate() {
6289 if let Some(Some(v)) = self.globals.get(i) {
6290 add(v, name.clone(), &mut objs);
6291 }
6292 }
6293 objs
6294 }
6295
6296 /// Clone the resumable execution state so the debugger can carry it between
6297 /// steps (it rebuilds the VM each step — see [`DebugVmState`]).
6298 pub(crate) fn save_debug_state(&self) -> DebugVmState {
6299 DebugVmState {
6300 registers: self.registers.clone(),
6301 base: self.base,
6302 globals: self.globals.clone(),
6303 lines: self.lines.clone(),
6304 iter_stack: self.iter_stack.clone(),
6305 sched_active: self.sched_active,
6306 sched_pc: self.sched_pc,
6307 sched_call_stack: self.sched_call_stack.clone(),
6308 }
6309 }
6310
6311 /// Restore a snapshot taken by [`Vm::save_debug_state`].
6312 pub(crate) fn restore_debug_state(&mut self, st: DebugVmState) {
6313 self.registers = st.registers;
6314 self.base = st.base;
6315 self.globals = st.globals;
6316 self.lines = st.lines;
6317 self.iter_stack = st.iter_stack;
6318 self.sched_active = st.sched_active;
6319 self.sched_pc = st.sched_pc;
6320 self.sched_call_stack = st.sched_call_stack;
6321 }
6322
6323 /// Take the pending concurrency request (the driver services it).
6324 pub(crate) fn take_pending(&mut self) -> Option<VmBlock> {
6325 self.pending.take()
6326 }
6327
6328 /// Deliver a resume value into the slot the last block reserved (if any).
6329 pub(crate) fn deliver_resume(&mut self, value: Value) {
6330 if let Some(slot) = self.resume_slot.take() {
6331 let value = self.wrap_resume_if_optional(value);
6332 self.set(slot, value);
6333 }
6334 }
6335
6336 /// Wrap a try-receive's resume value as a real `Option` — see [`Self::resume_wraps_option`].
6337 fn wrap_resume_if_optional(&mut self, value: Value) -> Value {
6338 if !std::mem::take(&mut self.resume_wraps_option) {
6339 return value;
6340 }
6341 match &*value.as_runtime() {
6342 crate::interpreter::RuntimeValue::Nothing => {
6343 Value::from_runtime(crate::interpreter::option_none())
6344 }
6345 other => Value::from_runtime(crate::interpreter::option_some(other.clone())),
6346 }
6347 }
6348
6349 /// Deliver a resume value into the slot the last block reserved, RETURNING the `(absolute slot,
6350 /// prior value)` it overwrote — so the reversible scheduler can undo the write (the delivery
6351 /// happens outside the recording loop, so it is not on the task's tape). `None` if the block
6352 /// reserved no slot (e.g. a `Send`).
6353 pub(crate) fn deliver_resume_recorded(&mut self, value: Value) -> Option<(usize, Value)> {
6354 let reg = self.resume_slot.take()?;
6355 let value = self.wrap_resume_if_optional(value);
6356 let slot = self.base + reg as usize;
6357 let old = self.registers[slot].clone();
6358 self.set(reg, value);
6359 Some((slot, old))
6360 }
6361
6362 /// Deliver a resolved `Select`: the received value (when a recv arm won) into
6363 /// that arm's var register, and the winning arm index into the `SelectWait`'s
6364 /// destination register.
6365 pub(crate) fn deliver_select(&mut self, arm: usize, value: Value) {
6366 let var = self.select_pending.get(arm).and_then(|(_, v)| *v);
6367 if let Some(reg) = var {
6368 self.set(reg, value);
6369 }
6370 if let Some(slot) = self.resume_slot.take() {
6371 self.set(
6372 slot,
6373 Value::from_runtime(crate::interpreter::RuntimeValue::Int(arm as i64)),
6374 );
6375 }
6376 self.select_pending.clear();
6377 }
6378
6379 /// Like [`deliver_select`], but RECORDS the prior value of each register it overwrites — the
6380 /// received value into the winning Recv arm's var register (when `value` is `Some`) and the
6381 /// winning arm index into the `SelectWait` destination — so the reversible scheduler can restore
6382 /// both. Returns `(var write, arm-index write)` as `(abs slot, prior value)` pairs.
6383 pub(crate) fn deliver_select_recorded(
6384 &mut self,
6385 arm: usize,
6386 value: Option<Value>,
6387 ) -> (Option<(usize, Value)>, Option<(usize, Value)>) {
6388 let var_write = value.and_then(|v| {
6389 let reg = self.select_pending.get(arm).and_then(|(_, r)| *r)?;
6390 let slot = self.base + reg as usize;
6391 let old = self.registers[slot].clone();
6392 self.set(reg, v);
6393 Some((slot, old))
6394 });
6395 let arm_write = self.resume_slot.take().map(|reg| {
6396 let slot = self.base + reg as usize;
6397 let old = self.registers[slot].clone();
6398 self.set(
6399 reg,
6400 Value::from_runtime(crate::interpreter::RuntimeValue::Int(arm as i64)),
6401 );
6402 (slot, old)
6403 });
6404 self.select_pending.clear();
6405 (var_write, arm_write)
6406 }
6407
6408 /// Read a select-timeout register as a non-negative logical tick count.
6409 fn as_ticks(&self, r: Reg) -> Result<u64, String> {
6410 use crate::interpreter::RuntimeValue;
6411 Ok(match &*self.reg(r).as_runtime() {
6412 RuntimeValue::Int(n) => (*n).max(0) as u64,
6413 RuntimeValue::Duration(d) => (*d).max(0) as u64,
6414 RuntimeValue::Span { months, days } => {
6415 (((*months as i64) * 30 + *days as i64) * 86_400).max(0) as u64
6416 }
6417 other => {
6418 return Err(format!(
6419 "select timeout must be a number or duration, found {}",
6420 other.type_name()
6421 ))
6422 }
6423 })
6424 }
6425
6426 /// Read a channel handle from register `r`.
6427 fn as_chan(&self, r: Reg) -> Result<ChanId, String> {
6428 match &*self.reg(r).as_runtime() {
6429 crate::interpreter::RuntimeValue::Chan(id) => Ok(*id),
6430 other => Err(format!("expected a channel, found {}", other.type_name())),
6431 }
6432 }
6433
6434 /// Read a task handle from register `r`.
6435 fn as_task(&self, r: Reg) -> Result<TaskId, String> {
6436 match &*self.reg(r).as_runtime() {
6437 crate::interpreter::RuntimeValue::TaskHandle(id) => Ok(*id),
6438 other => Err(format!(
6439 "expected a task handle, found {}",
6440 other.type_name()
6441 )),
6442 }
6443 }
6444
6445 /// Materialise register `r`'s value into a Send-able payload for a channel.
6446 fn materialize_reg(&self, r: Reg) -> Result<RtPayload, String> {
6447 let rt = self.reg(r).as_runtime();
6448 crate::concurrency::marshal::materialize(&rt)
6449 .map_err(|e| format!("cannot send value through a channel: {:?}", e))
6450 }
6451
6452 /// Materialise a contiguous register window `[args_start, args_start+count)`
6453 /// into `Send`-able payloads — the spawn arguments that cross to the child
6454 /// task (and, under work-stealing, to its worker thread).
6455 fn materialize_args(&self, args_start: Reg, arg_count: u16) -> Result<Vec<RtPayload>, String> {
6456 (0..arg_count as Reg)
6457 .map(|i| self.materialize_reg(args_start + i))
6458 .collect()
6459 }
6460
6461 /// Install the spawn entry-state for `functions[func](args)` into THIS VM:
6462 /// rebuild the payload args into a base-0 register window, push a sentinel
6463 /// frame so the body's `Return` terminates the task cleanly (result in
6464 /// register 0), and arm the scheduler `pc` at the function's `entry_pc`.
6465 ///
6466 /// Shared by both drivers: the cooperative one calls it on a freshly-cloned
6467 /// child (see [`Vm::spawn_task_vm`]); a work-stealing worker calls it on a VM
6468 /// built locally over its own borrow of the program.
6469 pub(crate) fn setup_task(&mut self, func: FuncIdx, args: &[RtPayload]) {
6470 let (entry_pc, reg_count) = {
6471 let f = &self.program.functions[func as usize];
6472 (f.entry_pc, f.register_count)
6473 };
6474 if self.registers.len() < reg_count {
6475 self.registers.resize(reg_count, Value::nothing());
6476 }
6477 for (i, a) in args.iter().enumerate() {
6478 self.registers[i] =
6479 Value::from_runtime(crate::concurrency::marshal::rebuild(a.clone()));
6480 }
6481 let restore_len = self.registers.len();
6482 self.sched_call_stack = vec![CallFrame {
6483 return_pc: self.program.code.len(),
6484 return_reg: 0,
6485 caller_base: 0,
6486 restore_len,
6487 iter_depth: 0,
6488 func,
6489 arg_lo: 0,
6490 arg_count: 0,
6491 }];
6492 self.sched_active = true;
6493 self.sched_pc = entry_pc;
6494 }
6495
6496 /// Build a fresh child VM that runs `functions[func](args)` — a spawned task —
6497 /// sharing this VM's `&'p program` and run context (tier, policy, program
6498 /// args). Used by the cooperative driver, which builds children inline.
6499 pub(crate) fn spawn_task_vm(&self, func: FuncIdx, args: &[RtPayload]) -> Vm<'p> {
6500 let mut child = Vm::new(self.program);
6501 child.policy_ctx = self.policy_ctx;
6502 child.tier = self.tier;
6503 child.accel_pbkdf2 = self.accel_pbkdf2;
6504 child.program_args = self.program_args.clone();
6505 child.setup_task(func, args);
6506 child
6507 }
6508
6509 /// Re-enter a program function `func` AS BYTECODE with a single materialised
6510 /// argument value, running it to completion on a fresh child VM that shares
6511 /// this VM's program + run context. Returns the handler's `Return` value
6512 /// (register 0) and any `Show` output it produced, in order. This is the
6513 /// `Serve` accept loop's per-connection dispatch — the exact analogue of the
6514 /// tree-walker's `call_function_with_values`, keeping the handler on the VM
6515 /// tier. A handler that suspends on nested IO (its own tcp/net) is refused
6516 /// with a clear error (→ a 500 for that request), never silently mis-run.
6517 pub(crate) fn call_handler_bytecode(
6518 &self,
6519 func: FuncIdx,
6520 arg: crate::interpreter::RuntimeValue,
6521 ) -> (
6522 Result<crate::interpreter::RuntimeValue, String>,
6523 Vec<String>,
6524 ) {
6525 let payload = match crate::concurrency::marshal::materialize(&arg) {
6526 Ok(p) => p,
6527 Err(e) => {
6528 return (
6529 Err(format!("Serve: cannot marshal Request: {e:?}")),
6530 Vec::new(),
6531 )
6532 }
6533 };
6534 let mut child = self.spawn_task_vm(func, &[payload]);
6535 match child.run_until_block() {
6536 // The sentinel frame `setup_task` installed carries `return_reg: 0`,
6537 // so the handler's `Return` leaves its `Response` in register 0 with
6538 // `base` restored to 0; the top-level `Done` payload is `Nothing`, so
6539 // read the return slot directly.
6540 Ok(VmStep::Done(_)) => {
6541 let value = (*child.registers[0].as_runtime()).clone();
6542 (Ok(value), child.drain_lines())
6543 }
6544 Ok(VmStep::Blocked) => (
6545 Err(
6546 "Serve: the handler suspended on nested IO; the VM tier serves \
6547 straight-line handlers (no tcp/net inside a request handler yet)"
6548 .to_string(),
6549 ),
6550 child.drain_lines(),
6551 ),
6552 Ok(VmStep::Paused) => (
6553 Err("Serve: the handler exhausted its step budget".to_string()),
6554 child.drain_lines(),
6555 ),
6556 Err(e) => (Err(e), child.drain_lines()),
6557 }
6558 }
6559
6560 fn binop(
6561 &mut self,
6562 dst: Reg,
6563 lhs: Reg,
6564 rhs: Reg,
6565 f: impl Fn(&Value, &Value) -> Result<Value, String>,
6566 ) -> Result<(), String> {
6567 let v = f(self.reg(lhs), self.reg(rhs))?;
6568 self.set(dst, v);
6569 Ok(())
6570 }
6571
6572 /// `R[dst] = R[dst] + R[src]`, extending in place when `R[dst]` is a
6573 /// Text this register exclusively owns (`Rc` count 1 — no alias, capture
6574 /// snapshot, or iterator can observe the mutation). The two in-place arms
6575 /// transcribe the kernel's `(Text, Text)` / `(Text, other)` add rules;
6576 /// every other shape — shared Rc included — takes the kernel itself.
6577 fn add_assign(&mut self, dst: Reg, src: Reg) -> Result<(), String> {
6578 use crate::interpreter::RuntimeValue;
6579 use std::rc::Rc;
6580 let di = self.base + dst as usize;
6581 let si = self.base + src as usize;
6582 if di != si {
6583 let (a, b) = if di < si {
6584 let (lo, hi) = self.registers.split_at_mut(si);
6585 (&mut lo[di], &hi[0])
6586 } else {
6587 let (lo, hi) = self.registers.split_at_mut(di);
6588 (&mut hi[0], &lo[si])
6589 };
6590 // Only the heap Text arm takes the in-place fast path; peek without
6591 // promoting (`as_runtime_mut` would box an inline scalar) so the
6592 // common non-Text case stays inline and falls to the kernel below.
6593 if matches!(a.as_runtime_ref(), Some(RuntimeValue::Text(_))) {
6594 if let RuntimeValue::Text(rc) = a.as_runtime_mut() {
6595 if let Some(s) = Rc::get_mut(rc) {
6596 match &*b.as_runtime() {
6597 RuntimeValue::Text(t) => s.push_str(t),
6598 other => s.push_str(&other.to_display_string()),
6599 }
6600 return Ok(());
6601 }
6602 }
6603 }
6604 }
6605 let v = self.reg(dst).add(self.reg(src))?;
6606 self.set(dst, v);
6607 Ok(())
6608 }
6609}
6610
6611fn const_to_value(c: &Constant) -> Value {
6612 use crate::interpreter::RuntimeValue;
6613 match c {
6614 Constant::Int(n) => Value::int(*n),
6615 Constant::Float(f) => Value::float(*f),
6616 Constant::Bool(b) => Value::bool(*b),
6617 Constant::Text(s) => Value::text(s.clone()),
6618 Constant::Char(c) => Value::from_runtime(RuntimeValue::Char(*c)),
6619 Constant::Nothing => Value::nothing(),
6620 Constant::Duration(n) => Value::from_runtime(RuntimeValue::Duration(*n)),
6621 Constant::Date(d) => Value::from_runtime(RuntimeValue::Date(*d)),
6622 Constant::Moment(n) => Value::from_runtime(RuntimeValue::Moment(*n)),
6623 Constant::Span { months, days } => Value::from_runtime(RuntimeValue::Span {
6624 months: *months,
6625 days: *days,
6626 }),
6627 Constant::Time(n) => Value::from_runtime(RuntimeValue::Time(*n)),
6628 }
6629}
6630
6631/// The shared-state after-effect a scheduler slice's terminating block had, so reverse can undo it.
6632enum ChanEffect {
6633 None,
6634 /// Created channel index (reverse pops it off the channel list — LIFO with creation order).
6635 Create,
6636 /// Enqueued to channel `idx` (reverse pops the back).
6637 Send(usize),
6638 /// Dequeued the front of channel `idx` (reverse pushes the payload back to the front).
6639 Recv(usize, RtPayload),
6640 /// Spawned a child task (reversed on its own tape; nothing to undo here).
6641 Spawn,
6642 /// Closed channel `idx` (reverse clears its closed flag).
6643 Close(usize),
6644}
6645
6646/// One recorded scheduler slice: task `task` ran `steps` ops, then hit a block the driver serviced.
6647struct Slice {
6648 task: usize,
6649 steps: usize,
6650 /// The resume value the block delivered into a register (a channel handle / received payload),
6651 /// captured as `(target task, abs slot, prior value)` so reverse restores it — the delivery
6652 /// happens OUTSIDE the recording loop, so it is not on the task's own tape. The target task is
6653 /// usually `task` itself, but for a blocking-receive HANDOFF the SENDER's slice delivers the
6654 /// payload directly into the parked RECEIVER's register, so the target differs from `task`.
6655 resume: Option<(usize, usize, Value)>,
6656 /// A SECOND block-delivered write, for the one block that writes two registers: a resolved
6657 /// `Select` delivers the received value into the arm's var register (`resume`) AND the winning
6658 /// arm index into the `SelectWait` destination (`resume2`). `None` for every other block.
6659 resume2: Option<(usize, usize, Value)>,
6660 chan: ChanEffect,
6661}
6662
6663/// A REVERSIBLE COOPERATIVE SCHEDULER — drives a main VM plus its spawned tasks deterministically
6664/// with per-task reversibility recording, capturing the interleaved execution SCHEDULE + channel
6665/// state; then reverses the entire concurrent execution schedule-backward across all task VMs. Each
6666/// task's slices pop off its own tape in exact reverse order, channel deltas are undone at the block
6667/// that caused them, and block-delivered resume values are restored — so `forward ; reverse` restores
6668/// every task's state AND the channel topology.
6669///
6670/// Scope: fire-and-forget `Spawn`, `Sleep`, and channels (`ChanNew`/`Send`/`Recv`) — including a
6671/// BLOCKING receive, where a task parks on an empty channel until a later send hands the payload
6672/// straight into its register and wakes it (the `do_recv`/`do_send` model). Also `SpawnHandle` +
6673/// `TaskAwait`: an awaiter parks until the child finishes, whose `Done` slice hands its result off
6674/// and wakes it (the same cross-task pattern). And `Select` (first-ready-recv-else-timeout): the
6675/// winning arm's value + index deliveries are both recorded and reversed.
6676pub(crate) struct RevCoop<'p> {
6677 tasks: Vec<Vm<'p>>,
6678 channels: Vec<std::collections::VecDeque<RtPayload>>,
6679 closed: Vec<bool>,
6680 schedule: Vec<Slice>,
6681}
6682
6683impl<'p> RevCoop<'p> {
6684 /// Drive `main` forward to quiescence with per-task recording, capturing the schedule + channel
6685 /// state. Declines a program using any op outside the reversible subset, or a block beyond the
6686 /// current scope, rather than mis-reversing.
6687 pub(crate) fn record(main: Vm<'p>) -> Result<Self, String> {
6688 Self::record_mode(main, super::reverse::ReverseMode::Observable)
6689 }
6690
6691 /// Like [`RevCoop::record`] but in an explicit [`super::reverse::ReverseMode`] — `Adiabatic`
6692 /// RECOMPUTES each task's reverse-live scratch on reverse (per-task register frames are independent,
6693 /// so per-task recompute is sound), driving the concurrent tape toward the Landauer floor.
6694 pub(crate) fn record_mode(
6695 mut main: Vm<'p>,
6696 mode: super::reverse::ReverseMode,
6697 ) -> Result<Self, String> {
6698 if let Some(op) = main
6699 .program
6700 .code
6701 .iter()
6702 .find(|op| !super::reverse::is_reversible_supported(op))
6703 {
6704 return Err(match super::reverse::external_effect_barrier(op) {
6705 // A truly-external effect: name the irreversibility barrier (internal state up to it
6706 // reverses; the effect itself cannot be un-done) — never a silent lie.
6707 Some(barrier) => format!(
6708 "vm: `{}` is an irreversible {barrier} effect — not yet reversible past the honest Landauer wall (an external effect cannot be un-done)",
6709 op.name()
6710 ),
6711 None => format!("vm: op `{}` is not yet reversible", op.name()),
6712 });
6713 }
6714 logicaffeine_base::money::clear_ambient_rates();
6715 // Concurrency elision/recompute: each task VM records under `mode` (tasks have independent
6716 // register frames, so per-task elision AND recompute are sound). Empty `named_regs` ⇒ no elision.
6717 main.install_reverse_recording(mode);
6718 let mut tasks = vec![main];
6719 let mut ready = vec![true];
6720 let mut channels: Vec<std::collections::VecDeque<RtPayload>> = Vec::new();
6721 let mut closed: Vec<bool> = Vec::new();
6722 // Per-channel FIFO of task ids parked on an empty receive (the do_recv/do_send handoff model).
6723 // Forward-routing bookkeeping only — reverse replays the recorded handoffs, never re-routes.
6724 let mut blocked_receivers: Vec<std::collections::VecDeque<usize>> = Vec::new();
6725 // Each task's captured `Done` result (for `Await`), and — per parked awaiter — the child task
6726 // it is blocked awaiting. Grow in lockstep with `tasks`/`ready`. Forward bookkeeping only.
6727 let mut results: Vec<Option<Value>> = vec![None];
6728 let mut awaiting: Vec<Option<usize>> = vec![None];
6729 let mut schedule: Vec<Slice> = Vec::new();
6730 loop {
6731 // Deterministic cooperative pick: the lowest-id ready task.
6732 let tid = match (0..tasks.len()).find(|&i| ready[i]) {
6733 Some(t) => t,
6734 None => break,
6735 };
6736 let before = tasks[tid].journal.as_ref().map_or(0, |j| j.step_count());
6737 let step = tasks[tid].run_until_block_impl::<false, true>(u64::MAX)?;
6738 let steps = tasks[tid].journal.as_ref().map_or(0, |j| j.step_count()) - before;
6739 // A second delivered write, set only by a resolved `Select` (value + arm-index).
6740 let mut resume2: Option<(usize, usize, Value)> = None;
6741 let (resume, chan) = match step {
6742 VmStep::Done(rv) => {
6743 ready[tid] = false;
6744 results[tid] = Some(Value::from_runtime(rv));
6745 // A parent parked in `Await` on this task takes its result now — a cross-task
6746 // handoff into the awaiter's register — and wakes (do_await / deliver-on-complete).
6747 if let Some(pid) = (0..tasks.len()).find(|&p| awaiting[p] == Some(tid)) {
6748 let v = results[tid].clone().unwrap();
6749 awaiting[pid] = None;
6750 ready[pid] = true;
6751 let r = tasks[pid]
6752 .deliver_resume_recorded(v)
6753 .map(|(s, o)| (pid, s, o));
6754 (r, ChanEffect::None)
6755 } else {
6756 (None, ChanEffect::None)
6757 }
6758 }
6759 VmStep::Blocked => {
6760 let block = tasks[tid]
6761 .take_pending()
6762 .ok_or("vm: blocked with no request")?;
6763 match block {
6764 VmBlock::Sleep(_) => (None, ChanEffect::None),
6765 VmBlock::NewChan(_) => {
6766 let idx = channels.len();
6767 channels.push(std::collections::VecDeque::new());
6768 closed.push(false);
6769 blocked_receivers.push(std::collections::VecDeque::new());
6770 let handle = Value::from_runtime(crate::interpreter::RuntimeValue::Chan(
6771 logicaffeine_runtime::ChanId(idx as u64),
6772 ));
6773 let r = tasks[tid].deliver_resume_recorded(handle).map(|(s, o)| (tid, s, o));
6774 (r, ChanEffect::Create)
6775 }
6776 VmBlock::Send(ch, payload) => {
6777 let idx = ch.0 as usize;
6778 // Direct handoff (do_send): a parked receiver takes the payload straight
6779 // into its register and wakes; nothing enqueues. The delivery is CROSS-TASK
6780 // — it lands in the receiver's slot, recorded on the sender's slice.
6781 if let Some(rid) = blocked_receivers[idx].pop_front() {
6782 let v = Value::from_runtime(
6783 crate::concurrency::marshal::rebuild(payload),
6784 );
6785 let r = tasks[rid].deliver_resume_recorded(v).map(|(s, o)| (rid, s, o));
6786 ready[rid] = true;
6787 (r, ChanEffect::None)
6788 } else {
6789 channels[idx].push_back(payload);
6790 (None, ChanEffect::Send(idx))
6791 }
6792 }
6793 VmBlock::Recv(ch) => {
6794 let idx = ch.0 as usize;
6795 match channels[idx].pop_front() {
6796 Some(payload) => {
6797 let v = Value::from_runtime(
6798 crate::concurrency::marshal::rebuild(payload.clone()),
6799 );
6800 let r = tasks[tid]
6801 .deliver_resume_recorded(v)
6802 .map(|(s, o)| (tid, s, o));
6803 (r, ChanEffect::Recv(idx, payload))
6804 }
6805 // Empty channel: PARK the receiver (do_recv). Its resume_slot + saved pc
6806 // persist on the task VM until a later send hands off directly to it.
6807 None => {
6808 blocked_receivers[idx].push_back(tid);
6809 ready[tid] = false;
6810 (None, ChanEffect::None)
6811 }
6812 }
6813 }
6814 VmBlock::SpawnDesc { func, args, want_handle } => {
6815 let child_idx = tasks.len();
6816 let mut child = tasks[tid].spawn_task_vm(func, &args);
6817 child.install_reverse_recording(mode);
6818 tasks.push(child);
6819 ready.push(true);
6820 results.push(None);
6821 awaiting.push(None);
6822 // `SpawnHandle` delivers a TaskHandle into the parent's dst; fire-and-forget
6823 // `Spawn` writes nothing. The child reverses on its own tape either way.
6824 let resume = if want_handle {
6825 let handle =
6826 Value::from_runtime(crate::interpreter::RuntimeValue::TaskHandle(
6827 logicaffeine_runtime::TaskId(child_idx as u64),
6828 ));
6829 tasks[tid].deliver_resume_recorded(handle).map(|(s, o)| (tid, s, o))
6830 } else {
6831 None
6832 };
6833 (resume, ChanEffect::Spawn)
6834 }
6835 VmBlock::Await(awaited) => {
6836 let a = awaited.0 as usize;
6837 match results.get(a).and_then(|r| r.clone()) {
6838 // Child already finished — take its result now (same slice).
6839 Some(v) => {
6840 let r = tasks[tid]
6841 .deliver_resume_recorded(v)
6842 .map(|(s, o)| (tid, s, o));
6843 (r, ChanEffect::None)
6844 }
6845 // Child still running — park the awaiter; the child's Done slice hands
6846 // its result off and wakes it.
6847 None => {
6848 awaiting[tid] = Some(a);
6849 ready[tid] = false;
6850 (None, ChanEffect::None)
6851 }
6852 }
6853 }
6854 VmBlock::TrySend(ch, payload) => {
6855 // Non-blocking send: always succeeds on an unbounded channel (Bool(true)
6856 // into dst). Hands off to a parked receiver (resume2, cross-task) or
6857 // enqueues, exactly like `Send`.
6858 let idx = ch.0 as usize;
6859 let chan = if let Some(rid) = blocked_receivers[idx].pop_front() {
6860 let v = Value::from_runtime(
6861 crate::concurrency::marshal::rebuild(payload),
6862 );
6863 resume2 =
6864 tasks[rid].deliver_resume_recorded(v).map(|(s, o)| (rid, s, o));
6865 ready[rid] = true;
6866 ChanEffect::None
6867 } else {
6868 channels[idx].push_back(payload);
6869 ChanEffect::Send(idx)
6870 };
6871 let ok = Value::from_runtime(crate::interpreter::RuntimeValue::Bool(true));
6872 let r = tasks[tid].deliver_resume_recorded(ok).map(|(s, o)| (tid, s, o));
6873 (r, chan)
6874 }
6875 VmBlock::TryRecv(ch) => {
6876 // Non-blocking receive: the queued value, else `Nothing` — never parks.
6877 let idx = ch.0 as usize;
6878 match channels[idx].pop_front() {
6879 Some(payload) => {
6880 // ★ A REAL OPTION, matching the tree-walker's
6881 // `Stmt::TryReceivePipe`. A try-receive answers "a value, or
6882 // nothing", which IS an Option — handing back the bare value
6883 // meant `Inspect x: When Some (v):` had no arm to take.
6884 // R1 keeps `Show x` printing the value; R2 keeps the empty
6885 // case equal to `nothing`.
6886 let v = Value::from_runtime(crate::interpreter::option_some(
6887 crate::concurrency::marshal::rebuild(payload.clone()),
6888 ));
6889 let r = tasks[tid]
6890 .deliver_resume_recorded(v)
6891 .map(|(s, o)| (tid, s, o));
6892 (r, ChanEffect::Recv(idx, payload))
6893 }
6894 None => {
6895 let nothing =
6896 Value::from_runtime(crate::interpreter::option_none());
6897 let r = tasks[tid]
6898 .deliver_resume_recorded(nothing)
6899 .map(|(s, o)| (tid, s, o));
6900 (r, ChanEffect::None)
6901 }
6902 }
6903 }
6904 VmBlock::Close(ch) => {
6905 let idx = ch.0 as usize;
6906 closed[idx] = true;
6907 (None, ChanEffect::Close(idx))
6908 }
6909 VmBlock::Select(arms) => {
6910 use logicaffeine_runtime::SelectArm;
6911 // First-ready-recv-else-timeout (the deterministic select semantics): the
6912 // lowest-index Recv arm whose channel has a payload wins; otherwise a
6913 // Timeout arm fires. Either delivers the winning arm index; a Recv win also
6914 // delivers the received value into that arm's var register.
6915 let recv_win = arms.iter().enumerate().find_map(|(i, a)| match a {
6916 SelectArm::Recv(ch) => {
6917 let idx = ch.0 as usize;
6918 (!channels[idx].is_empty()).then_some((i, idx))
6919 }
6920 SelectArm::Timeout(_) => None,
6921 });
6922 if let Some((arm_i, idx)) = recv_win {
6923 let payload = channels[idx].pop_front().unwrap();
6924 let v = Value::from_runtime(
6925 crate::concurrency::marshal::rebuild(payload.clone()),
6926 );
6927 let (var_w, arm_w) =
6928 tasks[tid].deliver_select_recorded(arm_i, Some(v));
6929 resume2 = arm_w.map(|(s, o)| (tid, s, o));
6930 (var_w.map(|(s, o)| (tid, s, o)), ChanEffect::Recv(idx, payload))
6931 } else if let Some(arm_i) =
6932 arms.iter().position(|a| matches!(a, SelectArm::Timeout(_)))
6933 {
6934 let (_, arm_w) = tasks[tid].deliver_select_recorded(arm_i, None);
6935 resume2 = arm_w.map(|(s, o)| (tid, s, o));
6936 (None, ChanEffect::None)
6937 } else {
6938 return Err("vm: reversible driver: a select with no ready arm and no timeout is not yet supported".to_string());
6939 }
6940 }
6941 _ => {
6942 return Err("vm: reversible driver supports spawn / await / select / sleep / channel ops only".to_string())
6943 }
6944 }
6945 }
6946 VmStep::Paused => unreachable!("recording run is not stepped"),
6947 };
6948 schedule.push(Slice {
6949 task: tid,
6950 steps,
6951 resume,
6952 resume2,
6953 chan,
6954 });
6955 }
6956 Ok(RevCoop {
6957 tasks,
6958 channels,
6959 closed,
6960 schedule,
6961 })
6962 }
6963
6964 /// Reverse the entire interleaved execution: walk the schedule BACKWARD; for each slice undo its
6965 /// channel delta and resume-value write, then reverse the task's ops from its own tape.
6966 pub(crate) fn reverse(&mut self) -> Result<(), String> {
6967 for i in (0..self.schedule.len()).rev() {
6968 let (task, steps, resume, resume2) = {
6969 let s = &self.schedule[i];
6970 (s.task, s.steps, s.resume.clone(), s.resume2.clone())
6971 };
6972 // Undo the shared-state effect of this slice's terminating block.
6973 match &self.schedule[i].chan {
6974 ChanEffect::Create => {
6975 self.channels.pop();
6976 }
6977 ChanEffect::Send(idx) => {
6978 self.channels[*idx].pop_back();
6979 }
6980 ChanEffect::Recv(idx, payload) => {
6981 let (idx, payload) = (*idx, payload.clone());
6982 self.channels[idx].push_front(payload);
6983 }
6984 ChanEffect::Close(idx) => {
6985 self.closed[*idx] = false;
6986 }
6987 ChanEffect::None | ChanEffect::Spawn => {}
6988 }
6989 // Undo the block-delivered resume-value write (into its TARGET task — for a blocking-recv
6990 // handoff the sender's slice wrote into the parked receiver, so the target differs).
6991 if let Some((target, slot, old)) = resume {
6992 self.tasks[target].registers[slot] = old;
6993 }
6994 // A resolved `Select` delivered a SECOND write (the winning arm index) — undo it too.
6995 if let Some((target, slot, old)) = resume2 {
6996 self.tasks[target].registers[slot] = old;
6997 }
6998 // Reverse the task's ops for this slice from its own tape.
6999 let mut tape = self.tasks[task]
7000 .journal
7001 .take()
7002 .ok_or("vm: task tape missing")?;
7003 self.tasks[task].reverse_slice(&mut tape, steps)?;
7004 self.tasks[task].journal = Some(tape);
7005 }
7006 // Adiabatic: once every task's slices are reversed, reset each task's elided scratch to its
7007 // default — the concurrency analogue of `Vm::run_reverse`'s tail reset (a no-op otherwise).
7008 for task in &mut self.tasks {
7009 task.adiabatic_reset();
7010 }
7011 Ok(())
7012 }
7013
7014 /// The main task's observable state (for the `forward ; reverse ≡ initial` check).
7015 pub(crate) fn main_state(&self) -> DebugVmState {
7016 self.tasks[0].save_debug_state()
7017 }
7018
7019 /// The main task's `Show` output after the forward run — the reference the soft-core differential
7020 /// compares against for the scheduler-only ops (`TaskAwait`/`ChanClose`) that no source emits, so a
7021 /// hand-built bytecode program driven through this scheduler is the only VM oracle for them.
7022 pub(crate) fn main_output(&self) -> String {
7023 self.tasks[0].output()
7024 }
7025
7026 /// The main task's recorded erased-tape byte count (before reverse) — for asserting the concurrency
7027 /// pebbling actually shrinks the tape under `Adiabatic` vs `Observable`.
7028 pub(crate) fn main_erased_bytes(&self) -> usize {
7029 self.tasks[0]
7030 .journal
7031 .as_ref()
7032 .map_or(0, |t| t.erased_bytes())
7033 }
7034
7035 /// The number of live channels (for asserting the channel topology reversed to empty).
7036 pub(crate) fn channel_count(&self) -> usize {
7037 self.channels.len()
7038 }
7039}
7040
7041#[cfg(test)]
7042#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/vm/machine/reverse_execution.rs"]
7043mod reverse_execution;
7044
7045#[cfg(test)]
7046#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/vm/machine/string_build_fastpath.rs"]
7047mod string_build_fastpath;
7048
7049#[cfg(test)]
7050#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/vm/machine/debug_stepping.rs"]
7051mod debug_stepping;
7052
7053#[cfg(test)]
7054#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/vm/machine/host_calls.rs"]
7055mod host_calls;
7056
7057#[cfg(test)]
7058#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/vm/machine/record_copy_work.rs"]
7059mod record_copy_work;
7060
7061#[cfg(test)]
7062#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/vm/machine/handle_count_tests.rs"]
7063mod handle_count_tests;