logicaffeine_compile/vm/instruction.rs
1//! Bytecode instruction set and the compiled-program container.
2//!
3//! Registers are per-frame `u16` indices (the compiler assigns locals to
4//! registers at compile time; frames are capped at `MAX_REGISTERS_PER_FRAME`).
5//! Jump targets are absolute instruction indices.
6
7use std::collections::HashMap;
8
9use serde::{Deserialize, Serialize};
10
11use crate::intern::Symbol;
12
13/// Serialize an interned [`Symbol`] as its `u32` index (HOTSWAP §P12). Sound for the
14/// tier cache because the cache key pins the exact source — re-parsing it reproduces
15/// the same interning order, so the index round-trips to the same symbol.
16pub(crate) mod symbol_serde {
17 use crate::intern::Symbol;
18 use serde::{Deserialize, Deserializer, Serializer};
19 pub fn serialize<S: Serializer>(s: &Symbol, ser: S) -> Result<S::Ok, S::Error> {
20 ser.serialize_u32(s.index() as u32)
21 }
22 pub fn deserialize<'de, D: Deserializer<'de>>(de: D) -> Result<Symbol, D::Error> {
23 Ok(Symbol::from_index(u32::deserialize(de)? as usize))
24 }
25}
26
27/// Serialize an `f64` by its raw bits so the cache round-trips bit-exactly (a text
28/// format would otherwise mangle NaN / ±∞ and risk precision drift).
29pub(crate) mod f64_bits {
30 use serde::{Deserialize, Deserializer, Serializer};
31 pub fn serialize<S: Serializer>(v: &f64, ser: S) -> Result<S::Ok, S::Error> {
32 ser.serialize_u64(v.to_bits())
33 }
34 pub fn deserialize<'de, D: Deserializer<'de>>(de: D) -> Result<f64, D::Error> {
35 Ok(f64::from_bits(u64::deserialize(de)?))
36 }
37}
38
39pub type Reg = u16;
40pub type ConstIdx = u32;
41pub type FuncIdx = u16;
42
43/// A constant-pool entry.
44#[derive(Clone, Debug, Serialize, Deserialize)]
45pub enum Constant {
46 Int(i64),
47 Float(#[serde(with = "f64_bits")] f64),
48 Bool(bool),
49 Text(String),
50 Char(char),
51 Nothing,
52 Duration(i64),
53 Date(i32),
54 Moment(i64),
55 Span { months: i32, days: i32 },
56 Time(i64),
57}
58
59/// A bytecode instruction. Every field is a small `Copy` scalar (registers,
60/// constant-pool indices, interned symbols), so the dispatch loop reads each
61/// op by value instead of `clone()`-ing through the `Clone` machinery.
62/// The declared element type of a `Pipe of T`, carried on [`Op::ChanNew`] so a consumer that
63/// models a channel as a typed FIFO queue (the direct-WASM AOT) can type a `Receive`/`select`
64/// arm's bound variable even when the pipe is never sent to (an empty `Pipe of Text` in a
65/// timeout-only `select`). A `Copy` tag — the scalar element types cover every pipe the corpus
66/// declares; a struct/enum element resolves to [`ChanElem::Unknown`] (falls back to the untyped
67/// queue, exactly as before).
68#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
69pub enum ChanElem {
70 Unknown,
71 Int,
72 Float,
73 Bool,
74 Text,
75}
76
77impl ChanElem {
78 /// Resolve a pipe's declared element type name (`Pipe of <name>`) to its tag.
79 pub fn from_type_name(name: &str) -> ChanElem {
80 match name {
81 "Int" | "Nat" => ChanElem::Int,
82 "Real" | "Float" => ChanElem::Float,
83 "Bool" => ChanElem::Bool,
84 "Text" => ChanElem::Text,
85 _ => ChanElem::Unknown,
86 }
87 }
88}
89
90#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
91pub enum Op {
92 /// `R[dst] = constants[idx]`
93 LoadConst {
94 dst: Reg,
95 idx: ConstIdx,
96 },
97 /// `R[dst] = R[src]` (shallow clone)
98 Move {
99 dst: Reg,
100 src: Reg,
101 },
102 /// Exchange `R[a]` and `R[b]` in place — the canonical ZERO-GARBAGE reversible primitive (its
103 /// own inverse: swapping twice is the identity). Reverse execution re-applies it with no history
104 /// tape entry, so it reverses with zero erased bits (the adiabatic charge-recovery case).
105 RevSwap {
106 a: Reg,
107 b: Reg,
108 },
109 /// In-place XOR: `R[place] ^= R[delta]` over the ℤ/2ⁿ ring — SELF-INVERSE (`(x ⊕ e) ⊕ e = x`), so
110 /// reverse re-applies it with no history-tape entry (zero garbage). Requires `place != delta`
111 /// (else `x ⊕ x = 0` erases `x`) — a well-formedness invariant the emitter guarantees, like a
112 /// valid jump target. `R[delta]` is read-only, and the reverse-order invariant restores it to its
113 /// forward value before this op is re-applied, so the inverse is exact.
114 RevXor {
115 place: Reg,
116 delta: Reg,
117 },
118 /// In-place modular negation: `R[place] = -R[place]` (wrapping two's-complement) — SELF-INVERSE
119 /// (`-(-x) = x` for every `i64`, `i64::MIN` included), so reverse re-applies it with no tape entry.
120 /// The additive inverse of the (ℤ/2ⁿ, +) group.
121 RevNeg {
122 place: Reg,
123 },
124 /// In-place modular add: `R[place] = R[place] + R[delta]` (wrapping, non-promoting — the reversible
125 /// additive translation, DISTINCT from the BigInt-promoting [`Op::Add`]). Its inverse is
126 /// [`Op::RevSub`] with the same operands; reverse applies that, no tape entry. Requires
127 /// `place != delta` (else `x + x = 2x` is not invertible by subtraction). `R[delta]` is read-only.
128 RevAdd {
129 place: Reg,
130 delta: Reg,
131 },
132 /// In-place modular subtract: `R[place] = R[place] - R[delta]` (wrapping). Mutual inverse of
133 /// [`Op::RevAdd`]; reverse applies `RevAdd`, no tape entry. Requires `place != delta`.
134 RevSub {
135 place: Reg,
136 delta: Reg,
137 },
138 /// Copy-on-write barrier: if `R[reg]`'s collection is shared (`Rc` strong > 1),
139 /// deep-clone it in place so `R[reg]` becomes the sole owner. Emitted before an
140 /// argument is passed to a function whose corresponding parameter is an inferred
141 /// MUTABLE BORROW (mutated in place and returned): the callee's element writes
142 /// then land on a buffer no OTHER live handle can observe, so an aliasing caller
143 /// (`Let y be arr; Set arr to f(arr)`) still sees value semantics. A no-op when
144 /// already uniquely owned (the common `Set x to f(x)` consume-reassign), so the
145 /// hot path pays only a strong-count check. Mirrors the AOT's call-site `.cow()`.
146 EnsureOwned {
147 reg: Reg,
148 },
149
150 Add {
151 dst: Reg,
152 lhs: Reg,
153 rhs: Reg,
154 },
155 /// `R[dst] = R[dst] + R[src]` — the `Set x to x + …` shape. Semantically
156 /// identical to `Add { dst, lhs: dst, rhs: src }`; the dedicated form lets
157 /// the VM append in place when `R[dst]` is a sole-owner Text (turning the
158 /// O(n²) build-a-string-by-concatenation loop into amortized O(n)).
159 AddAssign {
160 dst: Reg,
161 src: Reg,
162 },
163 Sub {
164 dst: Reg,
165 lhs: Reg,
166 rhs: Reg,
167 },
168 Mul {
169 dst: Reg,
170 lhs: Reg,
171 rhs: Reg,
172 },
173 Div {
174 dst: Reg,
175 lhs: Reg,
176 rhs: Reg,
177 },
178 /// EXACT division (`7 / 2 → 7/2`, a Rational), the type-directed sibling of
179 /// [`Op::Div`] — emitted for `BinaryOpKind::ExactDivide`.
180 ExactDiv {
181 dst: Reg,
182 lhs: Reg,
183 rhs: Reg,
184 },
185 /// FLOOR division (`-7 // 2 → -4`, toward negative infinity) — emitted for
186 /// `BinaryOpKind::FloorDivide`, distinct from the truncating [`Op::Div`].
187 FloorDiv {
188 dst: Reg,
189 lhs: Reg,
190 rhs: Reg,
191 },
192 Mod {
193 dst: Reg,
194 lhs: Reg,
195 rhs: Reg,
196 },
197 /// `dst = lhs / 2^k` (signed, round toward zero) — emitted only when the
198 /// divisor is a literal power of two AND the Oracle proved `lhs` is `Int`.
199 /// A single op (the JIT lowers it to the side-exit-free `divpow2` shift
200 /// stencil) so it fires for loop-invariant divisors the in-region JIT
201 /// detector misses, without the scratch-register pressure of an expansion.
202 DivPow2 {
203 dst: Reg,
204 lhs: Reg,
205 k: u8,
206 },
207 /// `dst = lhs / c` (`mul_back == 0`) or `dst = lhs % c` (`mul_back == c`),
208 /// where `c` is a compile-time-constant divisor that is NOT a power of two
209 /// (W5/`DivPow2` handles powers of two), computed by the Granlund–Montgomery
210 /// / libdivide UNSIGNED magic-reciprocal sequence (a `mul`-high + shift,
211 /// ~3 cycles) instead of `idiv` (~25 cycles). `magic`/`more` are the
212 /// precomputed constants (the exact [`logicaffeine_data::LogosDivU64`]
213 /// encoding — low 6 bits of `more` are the shift, `0x40` is the 65-bit
214 /// add-marker path). Emitted ONLY when the Oracle proves `lhs` is `Int` and
215 /// NON-NEGATIVE: the unsigned magic equals the signed truncating `/`/`%`
216 /// only for a non-negative dividend (for `x < 0` the signs disagree, exactly
217 /// as for the `% 2^k → &` rewrite). The remainder is derived as
218 /// `lhs - q*c` (wrapping), bit-exact with the kernel's `wrapping_rem` for
219 /// non-negative `lhs`. `divisor` carries the original constant `c` so the VM handler can fall
220 /// back to an exact `Div`/`Mod` when `lhs` is a `BigInt` the u64 magic reciprocal cannot hold
221 /// (the optimistic non-negative gate does not prove the dividend fits i64).
222 /// `wrap`: the Oracle also proved `lhs < 2 * divisor` (`Opt::ModWrap`), so the remainder is `lhs`,
223 /// less `divisor` once when `lhs >= divisor` — a compare and a subtract a backend may compute in
224 /// place of the magic sequence. A backend that reads the magic constants stays exact.
225 MagicDivU {
226 dst: Reg,
227 lhs: Reg,
228 magic: u64,
229 more: u8,
230 mul_back: i64,
231 divisor: i64,
232 wrap: bool,
233 },
234
235 Lt {
236 dst: Reg,
237 lhs: Reg,
238 rhs: Reg,
239 },
240 Gt {
241 dst: Reg,
242 lhs: Reg,
243 rhs: Reg,
244 },
245 LtEq {
246 dst: Reg,
247 lhs: Reg,
248 rhs: Reg,
249 },
250 GtEq {
251 dst: Reg,
252 lhs: Reg,
253 rhs: Reg,
254 },
255 Eq {
256 dst: Reg,
257 lhs: Reg,
258 rhs: Reg,
259 },
260 /// Tolerant float comparison (`a is approximately b`) — the shared
261 /// isclose semantics (`logicaffeine_data::ops::logos_approx_eq`);
262 /// `==`/`Eq` stays IEEE bit-exact.
263 ApproxEq {
264 dst: Reg,
265 lhs: Reg,
266 rhs: Reg,
267 },
268 NotEq {
269 dst: Reg,
270 lhs: Reg,
271 rhs: Reg,
272 },
273
274 Not {
275 dst: Reg,
276 src: Reg,
277 },
278
279 Concat {
280 dst: Reg,
281 lhs: Reg,
282 rhs: Reg,
283 },
284 /// `a followed by b` — merge two sequences into one.
285 SeqConcat {
286 dst: Reg,
287 lhs: Reg,
288 rhs: Reg,
289 },
290 /// `a ** b` — exponentiation. Integer power is exact (promotes to BigInt on
291 /// overflow); a Float operand uses `powf`; a negative Int exponent errors.
292 Pow {
293 dst: Reg,
294 lhs: Reg,
295 rhs: Reg,
296 },
297 BitXor {
298 dst: Reg,
299 lhs: Reg,
300 rhs: Reg,
301 },
302 /// `a & b` — bitwise AND on Int, logical on Bool, intersection on Sets.
303 BitAnd {
304 dst: Reg,
305 lhs: Reg,
306 rhs: Reg,
307 },
308 /// `a | b` (see `BitAnd`) — union on Sets.
309 BitOr {
310 dst: Reg,
311 lhs: Reg,
312 rhs: Reg,
313 },
314 Shl {
315 dst: Reg,
316 lhs: Reg,
317 rhs: Reg,
318 },
319 Shr {
320 dst: Reg,
321 lhs: Reg,
322 rhs: Reg,
323 },
324
325 /// Unconditional jump to absolute instruction index.
326 Jump {
327 target: usize,
328 },
329 /// Jump if `R[cond]` is falsey.
330 JumpIfFalse {
331 cond: Reg,
332 target: usize,
333 },
334 /// Jump if `R[cond]` is truthy.
335 JumpIfTrue {
336 cond: Reg,
337 target: usize,
338 },
339
340 /// Call a user function. The caller has placed `arg_count` arguments in
341 /// consecutive registers starting at `args_start` (relative to the caller's
342 /// frame base). The result is written to `R[dst]`. Uses register windowing.
343 Call {
344 dst: Reg,
345 func: FuncIdx,
346 args_start: Reg,
347 arg_count: u16,
348 },
349 /// Call a kernel builtin with already-evaluated arguments (arity was
350 /// validated at compile time, mirroring the tree-walker's
351 /// arity-before-evaluation rule).
352 CallBuiltin {
353 dst: Reg,
354 builtin: crate::semantics::builtins::BuiltinId,
355 args_start: Reg,
356 arg_count: u16,
357 },
358 /// Call the closure value in `R[callee]`. `name_for_err` is the function
359 /// name when this came from a by-name call (`Unknown function: f` when the
360 /// value is not callable) or `u32::MAX` for a call-by-expression
361 /// (`Cannot call value of type T`).
362 CallValue {
363 dst: Reg,
364 callee: Reg,
365 args_start: Reg,
366 arg_count: u16,
367 name_for_err: ConstIdx,
368 },
369 /// Build a closure over `program.functions[func]`: its `captures` list is
370 /// snapshotted — local captures deep-cloned from the register window at
371 /// `locals_start`, global captures from the globals table (skipped when
372 /// still undefined; the body then falls through to the live global).
373 MakeClosure {
374 dst: Reg,
375 func: FuncIdx,
376 locals_start: Reg,
377 },
378
379 /// `Check subject can/is predicate (of object)` — kernel policy check.
380 /// `object == Reg::MAX` means no object.
381 CheckPolicy {
382 subject: Reg,
383 #[serde(with = "symbol_serde")]
384 predicate: Symbol,
385 is_capability: bool,
386 object: Reg,
387 source_text: ConstIdx,
388 },
389
390 /// `Push value to obj's field` — kernel push into a struct's List field.
391 /// `field` is a Text constant (the resolved field name).
392 ListPushField {
393 obj: Reg,
394 field: ConstIdx,
395 src: Reg,
396 },
397
398 // ---- Globals (Main top-level bindings visible inside functions) ----
399 /// `R[dst] = globals[idx]`, error "Undefined variable: {name}" when unset.
400 GlobalGet {
401 dst: Reg,
402 idx: u16,
403 },
404 /// `globals[idx] = R[src]` (defines or overwrites).
405 GlobalSet {
406 idx: u16,
407 src: Reg,
408 },
409 /// Return `R[src]` from the current function.
410 Return {
411 src: Reg,
412 },
413 /// Return `nothing` from the current function.
414 ReturnNothing,
415
416 // ---- Collections ----
417 /// `R[dst] = [R[start], …, R[start+count-1]]` (a new list).
418 NewList {
419 dst: Reg,
420 start: Reg,
421 count: u16,
422 },
423 NewEmptyList {
424 dst: Reg,
425 },
426 /// `R[dst] = a new empty list reserving max(R[capacity], 0) elements`.
427 /// Unlike `NewEmptyListFixed`, this carries a source/runtime capacity hint
428 /// and therefore reads a register rather than a compile-time proof.
429 NewEmptyListWithCapacity {
430 dst: Reg,
431 capacity: Reg,
432 },
433 /// `R[dst] = a new empty list whose exact maximum length is capacity`.
434 /// The shared fixed-sequence proof emits this only for a non-escaping local.
435 /// It is observably identical to `NewEmptyList`; storage-aware backends may
436 /// reserve once or use frame-local backing instead of a growable heap list.
437 NewEmptyListFixed {
438 dst: Reg,
439 capacity: u16,
440 },
441 /// `R[dst] = a new half-width (`Vec<i32>`) Int sequence` — emitted (behind
442 /// `LOGOS_NARROW_VM`) for a `new Seq of Int` declaration the narrowing
443 /// proof certified fits `i32`. Observably identical to `NewEmptyList`; only
444 /// the storage width differs (see [`crate::interpreter::ListRepr::IntsI32`]).
445 NewEmptyListI32 {
446 dst: Reg,
447 },
448 NewEmptySet {
449 dst: Reg,
450 },
451 NewEmptyMap {
452 dst: Reg,
453 },
454 /// `R[dst] = a new empty map reserving max(R[capacity], 0) entries`.
455 NewEmptyMapWithCapacity {
456 dst: Reg,
457 capacity: Reg,
458 },
459 /// `R[dst] = [R[start]..=R[end]]` (inclusive integer range as a list).
460 NewRange {
461 dst: Reg,
462 start: Reg,
463 end: Reg,
464 },
465 /// Append `R[value]` to the list in `R[list]` (mutates in place).
466 ListPush {
467 list: Reg,
468 value: Reg,
469 },
470 /// Add `R[value]` to the set in `R[set]` (no-op if already present).
471 SetAdd {
472 set: Reg,
473 value: Reg,
474 },
475 /// Remove `R[value]` from the set/map in `R[collection]`.
476 RemoveFrom {
477 collection: Reg,
478 value: Reg,
479 },
480 /// `R[collection][R[index]] = R[value]` (1-based list set, or map insert).
481 SetIndex {
482 collection: Reg,
483 index: Reg,
484 value: Reg,
485 },
486 /// Like `SetIndex` but the Oracle PROVED the index in `[1, length]`
487 /// (range analysis, M9) — bounds-check elimination for the STORE. The
488 /// interpreter still checks (free defense-in-depth); the JIT lowers it to
489 /// an UNCHECKED array store (no bounds branch). Only listy collections
490 /// with a stable length earn this, via `index_provably_in_bounds`.
491 SetIndexUnchecked {
492 collection: Reg,
493 index: Reg,
494 value: Reg,
495 },
496 /// `R[dst] = R[collection][R[index]]` (1-based for ordered collections).
497 Index {
498 dst: Reg,
499 collection: Reg,
500 index: Reg,
501 },
502 /// Like `Index` but the Oracle (range analysis, M9) PROVED the index
503 /// in `[1, length]` at this point — bounds-check elimination, the V8/LLVM
504 /// way. The bytecode interpreter still checks (a sound proof makes the
505 /// check never fire; keeping it is free defense-in-depth), but the JIT
506 /// lowers it to an UNCHECKED array load (no bounds branch, no deopt).
507 /// Only listy collections with a stable length earn this; the compiler
508 /// emits it solely behind `index_provably_in_bounds`.
509 IndexUnchecked {
510 dst: Reg,
511 collection: Reg,
512 index: Reg,
513 },
514 /// REGION-ENTRY bounds-check hoist (V8 TurboFan loop bound-check
515 /// elimination). For a loop `while iv </<= bound` reading/writing
516 /// `R[array]` at affine indices, this asserts ONCE — at native region
517 /// entry — that the array is long enough for the whole loop:
518 /// `length(R[array]) >= R[bound] + add_max` and `R[iv] + add_min >= 1`.
519 /// If it holds, the region runs every covered access UNCHECKED; if not,
520 /// the VM declines the region and replays on bytecode (where the accesses
521 /// are checked). A pure no-op in the interpreter and the function tier —
522 /// speculation is region-only, made safe solely by this entry guard.
523 RegionBoundsGuard {
524 array: Reg,
525 bound: Reg,
526 iv: Reg,
527 add_max: i32,
528 add_min: i32,
529 },
530 /// `R[dst] = length of R[collection]`.
531 Length {
532 dst: Reg,
533 collection: Reg,
534 },
535 /// `R[dst] = R[collection] contains R[value]`.
536 Contains {
537 dst: Reg,
538 collection: Reg,
539 value: Reg,
540 },
541
542 // ---- Strings / slices / tuples / sets / temporal ----
543 /// `R[dst] = Text(debug_prefix? + format(R[src], spec?))` — one
544 /// interpolated-string segment. `u32::MAX` = no spec / no prefix.
545 FormatValue {
546 dst: Reg,
547 src: Reg,
548 spec: ConstIdx,
549 debug_prefix: ConstIdx,
550 },
551 /// `R[dst] = R[collection][R[start]..=R[end]]` (1-indexed inclusive).
552 SliceOp {
553 dst: Reg,
554 collection: Reg,
555 start: Reg,
556 end: Reg,
557 },
558 /// `R[dst] = deep clone of R[src]`.
559 DeepClone {
560 dst: Reg,
561 src: Reg,
562 },
563 /// `R[dst] = (R[start], …, R[start+count-1])` (immutable tuple).
564 NewTuple {
565 dst: Reg,
566 start: Reg,
567 count: u16,
568 },
569 UnionOp {
570 dst: Reg,
571 lhs: Reg,
572 rhs: Reg,
573 },
574 IntersectOp {
575 dst: Reg,
576 lhs: Reg,
577 rhs: Reg,
578 },
579 /// `R[dst] = today` (Date; honors the test fixed-clock).
580 LoadToday {
581 dst: Reg,
582 },
583 /// `R[dst] = now` (Moment; honors the test fixed-clock).
584 LoadNow {
585 dst: Reg,
586 },
587
588 // ---- Structs / enums / Inspect / CRDT ----
589 /// `R[dst] = Struct { type_name: constants[type_name], fields: {} }`.
590 NewStruct {
591 dst: Reg,
592 type_name: ConstIdx,
593 },
594 /// Insert `R[value]` under field `constants[field]` into the struct in
595 /// `R[obj]` (construction and SetField — structs have VALUE semantics, so
596 /// in-place mutation of the register equals the tree-walker's
597 /// clone-mutate-reassign).
598 StructInsert {
599 obj: Reg,
600 field: ConstIdx,
601 value: Reg,
602 },
603 /// `R[dst] = R[obj].field` — "Field '{f}' not found" / "Cannot access
604 /// field on {type}".
605 GetField {
606 dst: Reg,
607 obj: Reg,
608 field: ConstIdx,
609 },
610 /// `R[dst] = Inductive { type, constructor, args: R[args_start..+count] }`.
611 NewInductive {
612 dst: Reg,
613 type_name: ConstIdx,
614 ctor: ConstIdx,
615 args_start: Reg,
616 count: u16,
617 },
618 /// `R[dst] = Bool(struct type-name or inductive constructor == constants[variant])`;
619 /// false for any other value.
620 TestArm {
621 dst: Reg,
622 target: Reg,
623 variant: ConstIdx,
624 },
625 /// Inspect-arm binding: a Struct target binds `fields[constants[field]]`,
626 /// an Inductive target binds `args[index]`. A missing field/index leaves
627 /// `R[dst]` unwritten (the tree-walker skips the bind — unreachable for
628 /// parsed programs, whose fields always exist after default-fill).
629 BindArm {
630 dst: Reg,
631 target: Reg,
632 field: ConstIdx,
633 index: u16,
634 },
635 /// GCounter/PNCounter bump of `R[obj].field` by `R[amount]` (negated for
636 /// Decrease — also selects the tree-walker's increment/decrement wording).
637 CrdtBump {
638 obj: Reg,
639 field: ConstIdx,
640 amount: Reg,
641 negate: bool,
642 },
643 /// GCounter merge: fold every field of `R[source]` into `R[target]`.
644 CrdtMerge {
645 target: Reg,
646 source: Reg,
647 },
648 /// GCounter LATTICE JOIN: per-replica MAX of two 4-lane G-Counters (`R[target]` ⊔= `R[source]`),
649 /// the state-based, idempotent join. Unlike `CrdtMerge`'s polymorphic field-wise merge (which is
650 /// field-wise ADD for bare-int counters), this is the fixed 4-lane per-replica MAX that maps 1:1
651 /// to the `crdt_merge` hardware block — the coprocessor the real soft-core issues on its port.
652 CrdtJoin {
653 target: Reg,
654 source: Reg,
655 },
656 /// 256-BIT BIGINT LANE — one opcode for the whole wide-arithmetic family, routed on the soft-core
657 /// to the proven `bigint_alu`/`bigint_div`/`bigint_mul` blocks over an 8×256-bit wide register bank.
658 /// `kind` selects the operation: 0 = FromInt (`W[dst] = zext(R[a])`), 1 = Add (`W[dst]=W[a]+W[b]`),
659 /// 2 = Sub, 3 = Cmp (`R[dst] = W[a] < W[b]`), 4 = Low (`R[dst] = W[a][31:0]`), 5 = Div, 6 = Mul.
660 /// On the chip word the kind rides the high nibble of the dst byte; the VM carries it as a field.
661 BigIntWide {
662 kind: u8,
663 dst: Reg,
664 a: Reg,
665 b: Reg,
666 },
667 /// `R[dst]` = a fresh, empty rich CRDT — `kind` 0 = SharedSet (OR-Set),
668 /// 1 = SharedSequence (RGA), 2 = Divergent (MV-register). Used to default-fill a
669 /// `Shared` struct's CRDT fields, mirroring the tree-walker's `new`-struct init.
670 NewCrdt {
671 dst: Reg,
672 kind: u8,
673 },
674 /// RGA append: push `R[value]` onto the replicated sequence in `R[seq]` (mutates the
675 /// shared CRDT in place, so a field access propagates).
676 CrdtAppend {
677 seq: Reg,
678 value: Reg,
679 },
680 /// Resolve `R[obj].field` to `R[value]`: a real MV-register resolves in place, a plain
681 /// field is overwritten — the same fallback the tree-walker's `Resolve` takes.
682 CrdtResolve {
683 obj: Reg,
684 field: ConstIdx,
685 value: Reg,
686 },
687
688 // ---- Repeat (snapshot iteration) ----
689 /// Snapshot `R[iterable]` (List/Set items, Text chars, Map (k,v) tuples)
690 /// and push it onto the iterator stack.
691 IterPrepare {
692 iterable: Reg,
693 },
694 /// Load the next snapshot element into `R[dst]` and advance; jump to
695 /// `exit` when exhausted (the iterator stays pushed — `IterPop` at the
696 /// exit point drops it).
697 IterNext {
698 dst: Reg,
699 exit: usize,
700 },
701 /// Drop the top iterator.
702 IterPop,
703 /// `R[dst] = R[list].pop()` — Nothing when empty (not an error).
704 ListPop {
705 list: Reg,
706 dst: Reg,
707 },
708 /// Sleep for `R[nanos]` (Duration nanos, or Int milliseconds).
709 Sleep {
710 duration: Reg,
711 },
712 /// Tuple-pattern binding: `R[start..start+count] = tuple elements` with
713 /// zip semantics (stops at the shorter side, like the tree-walker).
714 /// Errors when `R[src]` is not a Tuple.
715 DestructureTuple {
716 src: Reg,
717 start: Reg,
718 count: u16,
719 },
720
721 /// Emit `R[src].to_display_string()` to the output stream.
722 Show {
723 src: Reg,
724 },
725 /// Emit an observation event (Wave 13 — the OBSERVED profile only). `site`
726 /// indexes [`CompiledProgram::observation_sites`] for the category / message
727 /// / payload names / span kind (all resolved at compile time); a `Message`
728 /// site reads its payload VALUES from the register range
729 /// `R[args_start .. args_start+args_count]`. Never emitted in the elided
730 /// (compiled/release) profile — observation is erased before those tiers — so
731 /// this op is `Unreachable` for AOT/WASM (see `wasm_aot_lock`).
732 Obs {
733 site: u32,
734 args_start: Reg,
735 args_count: u16,
736 },
737 /// `R[dst] = the program argument vector` as a `Seq of Text` (the
738 /// interpreter's `args()` system native, mirroring the compiled binary's
739 /// `env::args()`: index 0 is the program name). Outside the JIT integer
740 /// subset, so the adapters bail on it and it always runs in the VM.
741 Args {
742 dst: Reg,
743 },
744 // ─── Go-like concurrency (Phase 54 / T10) ───────────────────────────────
745 // Args travel through register ranges (`Op` is `Copy`). Channel/task handles
746 // are ordinary `Value`s (`RuntimeValue::Chan` / `::TaskHandle`). Every op that
747 // can block suspends the resumable VM (`run_until_block`) and is serviced by
748 // the deterministic scheduler, exactly as the tree-walker's `yield_request`.
749 /// `R[dst] = a new channel`; `cap < 0` ⇒ the scheduler's default capacity. `elem` is the
750 /// declared `Pipe of T` element type (a hint for a typed-queue consumer; the scheduler ignores it).
751 ChanNew {
752 dst: Reg,
753 cap: i32,
754 elem: ChanElem,
755 },
756 /// Send `R[val]` into channel `R[chan]` (blocks if the channel is full).
757 ChanSend {
758 chan: Reg,
759 val: Reg,
760 },
761 /// `R[dst] = receive from channel R[chan]` (blocks if the channel is empty).
762 ChanRecv {
763 dst: Reg,
764 chan: Reg,
765 },
766 /// `R[dst] = bool` — non-blocking send of `R[val]` into `R[chan]`.
767 ChanTrySend {
768 dst: Reg,
769 chan: Reg,
770 val: Reg,
771 },
772 /// `R[dst] = received value, or Nothing` — non-blocking receive from `R[chan]`.
773 ChanTryRecv {
774 dst: Reg,
775 chan: Reg,
776 },
777 /// Close channel `R[chan]`.
778 ChanClose {
779 chan: Reg,
780 },
781 /// Spawn `functions[func]` with args in `R[args_start..+arg_count]` (fire-and-forget).
782 Spawn {
783 func: FuncIdx,
784 args_start: Reg,
785 arg_count: u16,
786 },
787 /// `R[dst] = task handle` of a spawned `functions[func]` (same arg convention).
788 SpawnHandle {
789 dst: Reg,
790 func: FuncIdx,
791 args_start: Reg,
792 arg_count: u16,
793 },
794 /// `R[dst] = result of awaiting task R[handle]` (Nothing if it was aborted).
795 TaskAwait {
796 dst: Reg,
797 handle: Reg,
798 },
799 /// Abort task `R[handle]`.
800 TaskAbort {
801 handle: Reg,
802 },
803 /// Register a `Receive var from chan` arm for the next `SelectWait`.
804 SelectArmRecv {
805 chan: Reg,
806 var: Reg,
807 },
808 /// Register an `After ticks` timeout arm for the next `SelectWait`.
809 SelectArmTimeout {
810 ticks: Reg,
811 },
812 /// Block on the registered select arms; `R[dst_arm] = the winning arm index`
813 /// (a recv arm's received value is already in its `var` register).
814 SelectWait {
815 dst_arm: Reg,
816 },
817
818 // ─── peer networking over the relay (async-tier). Each suspends the resumable VM via a
819 // `VmBlock::Net*` request the async VM driver services with the shared `NetInbox` — the same
820 // inbox the tree-walker uses, so a `Send`/`Await` runs byte-identically on both tiers. ───
821 /// Dial the relay at `R[url]` (async); resume when connected.
822 NetConnect {
823 url: Reg,
824 },
825 /// Subscribe this node's inbox to `R[topic]` (async); resume when subscribed.
826 NetListen {
827 topic: Reg,
828 },
829 /// Encode `R[msg]` and publish it to peer `R[to]`.
830 NetSend {
831 to: Reg,
832 msg: Reg,
833 },
834 /// Batch-stream the list `R[values]` to peer `R[to]`.
835 NetStream {
836 to: Reg,
837 values: Reg,
838 },
839 /// `R[dst] = await a message (or a batch stream, if `stream`) from peer `R\[from\]`` (blocks).
840 NetAwait {
841 dst: Reg,
842 from: Reg,
843 stream: bool,
844 },
845 /// `R[dst] = a PeerAgent handle for address `R\[addr\]`` (its canonical relay topic). Pure.
846 NetMakePeer {
847 dst: Reg,
848 addr: Reg,
849 },
850 /// CRDT sync point on topic `R[topic]`: publish `R[dst]`'s counter, merge what has arrived,
851 /// and write the merged value back to `R[dst]`.
852 NetSync {
853 dst: Reg,
854 topic: Reg,
855 },
856
857 /// A tcp.lg client native (async-tier): `kind` is the `TcpOp` code
858 /// (connect/send/recv/recvExact/close — the `BigIntWide` one-op-many-kinds
859 /// pattern), operands in `R[args_start..args_start+arg_count]`. Suspends via
860 /// `VmBlock::Tcp`; the async io driver services it through the SAME
861 /// `TcpRegistry::exec_values` the tree-walker calls, and resumes `R[dst]`
862 /// with the LOGOS `Result` value.
863 Tcp {
864 dst: Reg,
865 kind: u8,
866 args_start: Reg,
867 arg_count: u16,
868 },
869
870 /// Serve HTTP on `R[port]` with the handler function `handler` (a resolved
871 /// `FuncIdx`) — the `Serve` keystone on the bytecode tier. Suspends via
872 /// `VmBlock::Serve`; the async io driver owns the SAME concurrent accept
873 /// loop the tree-walker's `serve_http_concurrent` uses, and per connection
874 /// RE-ENTERS `handler` AS VM BYTECODE (a fresh child `Vm` at the handler's
875 /// entry) with the marshaled `Request` value, reading its `Response`
876 /// through the shared request/response marshaling — so both tiers serve
877 /// byte-identically. The accept loop never returns; this op never resumes.
878 Serve {
879 port: Reg,
880 handler: FuncIdx,
881 },
882
883 /// Fail with the Text constant at `msg` — used for constructs whose
884 /// tree-walker semantics are "error WHEN EXECUTED" (an unbound `Set`, an
885 /// unsupported statement). Never fails at compile time: dead branches must
886 /// stay free.
887 FailWith {
888 msg: ConstIdx,
889 },
890 /// Stop execution.
891 Halt,
892}
893
894impl Op {
895 /// A stable name for this op variant — EXHAUSTIVE (no wildcard), so a new VM instruction fails
896 /// to compile until it is named here. The single source of truth for op names shared by every
897 /// catalog lock (WASM-AOT support, reversibility, …) — see `tests/reverse_op_lock.rs`.
898 pub fn name(&self) -> &'static str {
899 match self {
900 Op::LoadConst { .. } => "LoadConst",
901 Op::Move { .. } => "Move",
902 Op::RevSwap { .. } => "RevSwap",
903 Op::RevXor { .. } => "RevXor",
904 Op::RevNeg { .. } => "RevNeg",
905 Op::RevAdd { .. } => "RevAdd",
906 Op::RevSub { .. } => "RevSub",
907 Op::EnsureOwned { .. } => "EnsureOwned",
908 Op::Add { .. } => "Add",
909 Op::AddAssign { .. } => "AddAssign",
910 Op::Sub { .. } => "Sub",
911 Op::Mul { .. } => "Mul",
912 Op::Div { .. } => "Div",
913 Op::ExactDiv { .. } => "ExactDiv",
914 Op::FloorDiv { .. } => "FloorDiv",
915 Op::Mod { .. } => "Mod",
916 Op::DivPow2 { .. } => "DivPow2",
917 Op::MagicDivU { .. } => "MagicDivU",
918 Op::Lt { .. } => "Lt",
919 Op::Gt { .. } => "Gt",
920 Op::LtEq { .. } => "LtEq",
921 Op::GtEq { .. } => "GtEq",
922 Op::Eq { .. } => "Eq",
923 Op::ApproxEq { .. } => "ApproxEq",
924 Op::NotEq { .. } => "NotEq",
925 Op::Not { .. } => "Not",
926 Op::Concat { .. } => "Concat",
927 Op::SeqConcat { .. } => "SeqConcat",
928 Op::Pow { .. } => "Pow",
929 Op::BitXor { .. } => "BitXor",
930 Op::BitAnd { .. } => "BitAnd",
931 Op::BitOr { .. } => "BitOr",
932 Op::Shl { .. } => "Shl",
933 Op::Shr { .. } => "Shr",
934 Op::Jump { .. } => "Jump",
935 Op::JumpIfFalse { .. } => "JumpIfFalse",
936 Op::JumpIfTrue { .. } => "JumpIfTrue",
937 Op::Call { .. } => "Call",
938 Op::CallBuiltin { .. } => "CallBuiltin",
939 Op::CallValue { .. } => "CallValue",
940 Op::MakeClosure { .. } => "MakeClosure",
941 Op::CheckPolicy { .. } => "CheckPolicy",
942 Op::ListPushField { .. } => "ListPushField",
943 Op::GlobalGet { .. } => "GlobalGet",
944 Op::GlobalSet { .. } => "GlobalSet",
945 Op::Return { .. } => "Return",
946 Op::ReturnNothing => "ReturnNothing",
947 Op::NewList { .. } => "NewList",
948 Op::NewEmptyList { .. } => "NewEmptyList",
949 Op::NewEmptyListWithCapacity { .. } => "NewEmptyListWithCapacity",
950 Op::NewEmptyListFixed { .. } => "NewEmptyListFixed",
951 Op::NewEmptyListI32 { .. } => "NewEmptyListI32",
952 Op::NewEmptySet { .. } => "NewEmptySet",
953 Op::NewEmptyMap { .. } => "NewEmptyMap",
954 Op::NewEmptyMapWithCapacity { .. } => "NewEmptyMapWithCapacity",
955 Op::NewRange { .. } => "NewRange",
956 Op::ListPush { .. } => "ListPush",
957 Op::SetAdd { .. } => "SetAdd",
958 Op::RemoveFrom { .. } => "RemoveFrom",
959 Op::SetIndex { .. } => "SetIndex",
960 Op::SetIndexUnchecked { .. } => "SetIndexUnchecked",
961 Op::Index { .. } => "Index",
962 Op::IndexUnchecked { .. } => "IndexUnchecked",
963 Op::RegionBoundsGuard { .. } => "RegionBoundsGuard",
964 Op::Length { .. } => "Length",
965 Op::Contains { .. } => "Contains",
966 Op::FormatValue { .. } => "FormatValue",
967 Op::SliceOp { .. } => "SliceOp",
968 Op::DeepClone { .. } => "DeepClone",
969 Op::NewTuple { .. } => "NewTuple",
970 Op::UnionOp { .. } => "UnionOp",
971 Op::IntersectOp { .. } => "IntersectOp",
972 Op::LoadToday { .. } => "LoadToday",
973 Op::LoadNow { .. } => "LoadNow",
974 Op::NewStruct { .. } => "NewStruct",
975 Op::StructInsert { .. } => "StructInsert",
976 Op::GetField { .. } => "GetField",
977 Op::NewInductive { .. } => "NewInductive",
978 Op::TestArm { .. } => "TestArm",
979 Op::BindArm { .. } => "BindArm",
980 Op::CrdtBump { .. } => "CrdtBump",
981 Op::CrdtMerge { .. } => "CrdtMerge",
982 Op::CrdtJoin { .. } => "CrdtJoin",
983 Op::BigIntWide { .. } => "BigIntWide",
984 Op::NewCrdt { .. } => "NewCrdt",
985 Op::CrdtAppend { .. } => "CrdtAppend",
986 Op::CrdtResolve { .. } => "CrdtResolve",
987 Op::IterPrepare { .. } => "IterPrepare",
988 Op::IterNext { .. } => "IterNext",
989 Op::IterPop => "IterPop",
990 Op::ListPop { .. } => "ListPop",
991 Op::Sleep { .. } => "Sleep",
992 Op::DestructureTuple { .. } => "DestructureTuple",
993 Op::Show { .. } => "Show",
994 Op::Args { .. } => "Args",
995 Op::ChanNew { .. } => "ChanNew",
996 Op::ChanSend { .. } => "ChanSend",
997 Op::ChanRecv { .. } => "ChanRecv",
998 Op::ChanTrySend { .. } => "ChanTrySend",
999 Op::ChanTryRecv { .. } => "ChanTryRecv",
1000 Op::ChanClose { .. } => "ChanClose",
1001 Op::Spawn { .. } => "Spawn",
1002 Op::SpawnHandle { .. } => "SpawnHandle",
1003 Op::TaskAwait { .. } => "TaskAwait",
1004 Op::TaskAbort { .. } => "TaskAbort",
1005 Op::SelectArmRecv { .. } => "SelectArmRecv",
1006 Op::SelectArmTimeout { .. } => "SelectArmTimeout",
1007 Op::SelectWait { .. } => "SelectWait",
1008 Op::NetConnect { .. } => "NetConnect",
1009 Op::NetListen { .. } => "NetListen",
1010 Op::NetSend { .. } => "NetSend",
1011 Op::NetStream { .. } => "NetStream",
1012 Op::NetAwait { .. } => "NetAwait",
1013 Op::NetMakePeer { .. } => "NetMakePeer",
1014 Op::NetSync { .. } => "NetSync",
1015 Op::Tcp { .. } => "Tcp",
1016 Op::Serve { .. } => "Serve",
1017 Op::FailWith { .. } => "FailWith",
1018 Op::Obs { .. } => "Obs",
1019 Op::Halt => "Halt",
1020 }
1021 }
1022
1023 /// Every register this op WRITES (rebinds). EXHAUSTIVE (no wildcard) and over-approximate — a
1024 /// conditional write (`IterNext`'s element) and a copy-on-write rebind (`EnsureOwned`) count. An
1025 /// analysis that types or classifies registers takes a written register's facts from the writing
1026 /// op alone, never from what it held before; a new op that writes a register cannot compile until
1027 /// it is listed here.
1028 pub fn for_each_written_reg(&self, mut f: impl FnMut(Reg)) {
1029 match self {
1030 Op::LoadConst { dst, .. }
1031 | Op::Move { dst, .. }
1032 | Op::Add { dst, .. }
1033 | Op::BigIntWide { dst, .. }
1034 | Op::AddAssign { dst, .. }
1035 | Op::Sub { dst, .. }
1036 | Op::Mul { dst, .. }
1037 | Op::Div { dst, .. }
1038 | Op::ExactDiv { dst, .. }
1039 | Op::FloorDiv { dst, .. }
1040 | Op::Mod { dst, .. }
1041 | Op::DivPow2 { dst, .. }
1042 | Op::MagicDivU { dst, .. }
1043 | Op::Lt { dst, .. }
1044 | Op::Gt { dst, .. }
1045 | Op::LtEq { dst, .. }
1046 | Op::GtEq { dst, .. }
1047 | Op::Eq { dst, .. }
1048 | Op::ApproxEq { dst, .. }
1049 | Op::NotEq { dst, .. }
1050 | Op::Not { dst, .. }
1051 | Op::Concat { dst, .. }
1052 | Op::SeqConcat { dst, .. }
1053 | Op::Pow { dst, .. }
1054 | Op::BitXor { dst, .. }
1055 | Op::BitAnd { dst, .. }
1056 | Op::BitOr { dst, .. }
1057 | Op::Shl { dst, .. }
1058 | Op::Shr { dst, .. }
1059 | Op::Call { dst, .. }
1060 | Op::CallBuiltin { dst, .. }
1061 | Op::CallValue { dst, .. }
1062 | Op::MakeClosure { dst, .. }
1063 | Op::GlobalGet { dst, .. }
1064 | Op::NewList { dst, .. }
1065 | Op::NewEmptyList { dst }
1066 | Op::NewEmptyListWithCapacity { dst, .. }
1067 | Op::NewEmptyListFixed { dst, .. }
1068 | Op::NewEmptyListI32 { dst }
1069 | Op::NewEmptySet { dst }
1070 | Op::NewEmptyMap { dst }
1071 | Op::NewEmptyMapWithCapacity { dst, .. }
1072 | Op::NewRange { dst, .. }
1073 | Op::Index { dst, .. }
1074 | Op::IndexUnchecked { dst, .. }
1075 | Op::Length { dst, .. }
1076 | Op::Contains { dst, .. }
1077 | Op::FormatValue { dst, .. }
1078 | Op::SliceOp { dst, .. }
1079 | Op::DeepClone { dst, .. }
1080 | Op::NewTuple { dst, .. }
1081 | Op::UnionOp { dst, .. }
1082 | Op::IntersectOp { dst, .. }
1083 | Op::LoadToday { dst }
1084 | Op::LoadNow { dst }
1085 | Op::NewStruct { dst, .. }
1086 | Op::GetField { dst, .. }
1087 | Op::NewInductive { dst, .. }
1088 | Op::TestArm { dst, .. }
1089 | Op::BindArm { dst, .. }
1090 | Op::NewCrdt { dst, .. }
1091 | Op::IterNext { dst, .. }
1092 | Op::ListPop { dst, .. }
1093 | Op::Args { dst }
1094 | Op::ChanNew { dst, .. }
1095 | Op::ChanRecv { dst, .. }
1096 | Op::ChanTrySend { dst, .. }
1097 | Op::ChanTryRecv { dst, .. }
1098 | Op::SpawnHandle { dst, .. }
1099 | Op::TaskAwait { dst, .. }
1100 | Op::NetAwait { dst, .. }
1101 | Op::NetMakePeer { dst, .. }
1102 | Op::NetSync { dst, .. }
1103 | Op::Tcp { dst, .. }
1104 | Op::SelectWait { dst_arm: dst } => f(*dst),
1105
1106 Op::RevSwap { a, b } => {
1107 f(*a);
1108 f(*b);
1109 }
1110 Op::RevXor { place, .. }
1111 | Op::RevNeg { place }
1112 | Op::RevAdd { place, .. }
1113 | Op::RevSub { place, .. } => f(*place),
1114 Op::EnsureOwned { reg } => f(*reg),
1115 Op::SelectArmRecv { var, .. } => f(*var),
1116 Op::DestructureTuple { start, count, .. } => {
1117 for i in 0..*count {
1118 f(start + i);
1119 }
1120 }
1121
1122 // No register writes: control, stores, effects.
1123 Op::Jump { .. }
1124 | Op::JumpIfFalse { .. }
1125 | Op::JumpIfTrue { .. }
1126 | Op::CheckPolicy { .. }
1127 | Op::ListPushField { .. }
1128 | Op::GlobalSet { .. }
1129 | Op::Return { .. }
1130 | Op::ReturnNothing
1131 | Op::ListPush { .. }
1132 | Op::SetAdd { .. }
1133 | Op::RemoveFrom { .. }
1134 | Op::SetIndex { .. }
1135 | Op::SetIndexUnchecked { .. }
1136 | Op::RegionBoundsGuard { .. }
1137 | Op::StructInsert { .. }
1138 | Op::CrdtBump { .. }
1139 | Op::CrdtMerge { .. }
1140 | Op::CrdtJoin { .. }
1141 | Op::CrdtAppend { .. }
1142 | Op::CrdtResolve { .. }
1143 | Op::IterPrepare { .. }
1144 | Op::IterPop
1145 | Op::Sleep { .. }
1146 | Op::Show { .. }
1147 | Op::Obs { .. }
1148 | Op::ChanSend { .. }
1149 | Op::ChanClose { .. }
1150 | Op::Spawn { .. }
1151 | Op::TaskAbort { .. }
1152 | Op::SelectArmTimeout { .. }
1153 | Op::NetConnect { .. }
1154 | Op::NetListen { .. }
1155 | Op::NetSend { .. }
1156 | Op::NetStream { .. }
1157 | Op::Serve { .. }
1158 | Op::FailWith { .. }
1159 | Op::Halt => {}
1160 }
1161 }
1162
1163 /// Every register this op READS — EXHAUSTIVE and over-approximate: every range operand is expanded, and
1164 /// a `Reg::MAX` "no object" sentinel is skipped. A `MakeClosure` snapshots `captures(func)` locals from
1165 /// `locals_start`; a caller without the program passes an upper bound, which only reads more.
1166 pub fn for_each_read_reg(&self, captures: impl Fn(FuncIdx) -> usize, mut f: impl FnMut(Reg)) {
1167 fn range(start: Reg, count: u16, f: &mut impl FnMut(Reg)) {
1168 for i in 0..count {
1169 f(start.wrapping_add(i));
1170 }
1171 }
1172 match self {
1173 // dst = f(lhs, rhs)
1174 Op::Add { lhs, rhs, .. }
1175 | Op::Sub { lhs, rhs, .. }
1176 | Op::Mul { lhs, rhs, .. }
1177 | Op::Div { lhs, rhs, .. }
1178 | Op::ExactDiv { lhs, rhs, .. }
1179 | Op::FloorDiv { lhs, rhs, .. }
1180 | Op::Mod { lhs, rhs, .. }
1181 | Op::Lt { lhs, rhs, .. }
1182 | Op::Gt { lhs, rhs, .. }
1183 | Op::LtEq { lhs, rhs, .. }
1184 | Op::GtEq { lhs, rhs, .. }
1185 | Op::Eq { lhs, rhs, .. }
1186 | Op::ApproxEq { lhs, rhs, .. }
1187 | Op::NotEq { lhs, rhs, .. }
1188 | Op::Concat { lhs, rhs, .. }
1189 | Op::SeqConcat { lhs, rhs, .. }
1190 | Op::Pow { lhs, rhs, .. }
1191 | Op::BitXor { lhs, rhs, .. }
1192 | Op::BitAnd { lhs, rhs, .. }
1193 | Op::BitOr { lhs, rhs, .. }
1194 | Op::Shl { lhs, rhs, .. }
1195 | Op::Shr { lhs, rhs, .. }
1196 | Op::UnionOp { lhs, rhs, .. }
1197 | Op::IntersectOp { lhs, rhs, .. } => {
1198 f(*lhs);
1199 f(*rhs);
1200 }
1201 Op::DivPow2 { lhs, .. } | Op::MagicDivU { lhs, .. } => f(*lhs),
1202 // dst = f(src)
1203 Op::Move { src, .. }
1204 | Op::Not { src, .. }
1205 | Op::DeepClone { src, .. }
1206 | Op::FormatValue { src, .. } => f(*src),
1207 // dst = R[dst] op R[src] (dst read + written)
1208 Op::AddAssign { dst, src } => {
1209 f(*dst);
1210 f(*src);
1211 }
1212 // in-place reversible core (place read + written; delta read)
1213 Op::RevAdd { place, delta }
1214 | Op::RevSub { place, delta }
1215 | Op::RevXor { place, delta } => {
1216 f(*place);
1217 f(*delta);
1218 }
1219 Op::RevNeg { place } => f(*place),
1220 Op::RevSwap { a, b } => {
1221 f(*a);
1222 f(*b);
1223 }
1224 Op::EnsureOwned { reg } => f(*reg),
1225 // pure reads → fresh dst
1226 Op::Index {
1227 collection, index, ..
1228 }
1229 | Op::IndexUnchecked {
1230 collection, index, ..
1231 } => {
1232 f(*collection);
1233 f(*index);
1234 }
1235 Op::Length { collection, .. } => f(*collection),
1236 Op::Contains {
1237 collection, value, ..
1238 } => {
1239 f(*collection);
1240 f(*value);
1241 }
1242 Op::SliceOp {
1243 collection,
1244 start,
1245 end,
1246 ..
1247 } => {
1248 f(*collection);
1249 f(*start);
1250 f(*end);
1251 }
1252 Op::GetField { obj, .. } => f(*obj),
1253 Op::TestArm { target, .. } | Op::BindArm { target, .. } => f(*target),
1254 Op::NewRange { start, end, .. } => {
1255 f(*start);
1256 f(*end);
1257 }
1258 // range constructors
1259 Op::NewList { start, count, .. } | Op::NewTuple { start, count, .. } => {
1260 range(*start, *count, &mut f)
1261 }
1262 Op::NewInductive {
1263 args_start, count, ..
1264 } => range(*args_start, *count, &mut f),
1265 // calls: consecutive arg window
1266 Op::Call {
1267 args_start,
1268 arg_count,
1269 ..
1270 }
1271 | Op::CallBuiltin {
1272 args_start,
1273 arg_count,
1274 ..
1275 } => range(*args_start, *arg_count, &mut f),
1276 Op::CallValue {
1277 callee,
1278 args_start,
1279 arg_count,
1280 ..
1281 } => {
1282 f(*callee);
1283 range(*args_start, *arg_count, &mut f);
1284 }
1285 // a closure snapshots its local captures from `locals_start` (over-approximate the
1286 // window with the whole capture count; global captures within it are read harmlessly)
1287 Op::MakeClosure {
1288 func, locals_start, ..
1289 } => {
1290 range(
1291 *locals_start,
1292 captures(*func).min(Reg::MAX as usize) as u16,
1293 &mut f,
1294 );
1295 }
1296 Op::Obs {
1297 args_start,
1298 args_count,
1299 ..
1300 } => range(*args_start, *args_count, &mut f),
1301 Op::Spawn {
1302 args_start,
1303 arg_count,
1304 ..
1305 }
1306 | Op::SpawnHandle {
1307 args_start,
1308 arg_count,
1309 ..
1310 } => range(*args_start, *arg_count, &mut f),
1311 Op::Tcp {
1312 args_start,
1313 arg_count,
1314 ..
1315 } => range(*args_start, *arg_count, &mut f),
1316 // in-place mutations: collection/struct read (and mutated) + value read
1317 Op::ListPush { list, value } => {
1318 f(*list);
1319 f(*value);
1320 }
1321 Op::ListPushField { obj, src, .. } => {
1322 f(*obj);
1323 f(*src);
1324 }
1325 Op::SetAdd { set, value } => {
1326 f(*set);
1327 f(*value);
1328 }
1329 Op::RemoveFrom { collection, value } => {
1330 f(*collection);
1331 f(*value);
1332 }
1333 Op::SetIndex {
1334 collection,
1335 index,
1336 value,
1337 }
1338 | Op::SetIndexUnchecked {
1339 collection,
1340 index,
1341 value,
1342 } => {
1343 f(*collection);
1344 f(*index);
1345 f(*value);
1346 }
1347 Op::StructInsert { obj, value, .. } => {
1348 f(*obj);
1349 f(*value);
1350 }
1351 Op::CrdtBump { obj, amount, .. } => {
1352 f(*obj);
1353 f(*amount);
1354 }
1355 Op::CrdtMerge { target, source } | Op::CrdtJoin { target, source } => {
1356 f(*target);
1357 f(*source);
1358 }
1359 Op::CrdtAppend { seq, value } => {
1360 f(*seq);
1361 f(*value);
1362 }
1363 Op::CrdtResolve { obj, value, .. } => {
1364 f(*obj);
1365 f(*value);
1366 }
1367 Op::ListPop { list, .. } => f(*list),
1368 Op::BigIntWide { a, b, .. } => {
1369 f(*a);
1370 f(*b);
1371 }
1372 Op::DestructureTuple { src, .. } => f(*src),
1373 // control / effects reading a scalar
1374 Op::JumpIfFalse { cond, .. } | Op::JumpIfTrue { cond, .. } => f(*cond),
1375 Op::GlobalSet { src, .. } => f(*src),
1376 Op::Return { src } => f(*src),
1377 Op::Show { src } => f(*src),
1378 Op::Sleep { duration } => f(*duration),
1379 Op::IterPrepare { iterable } => f(*iterable),
1380 Op::RegionBoundsGuard {
1381 array, bound, iv, ..
1382 } => {
1383 f(*array);
1384 f(*bound);
1385 f(*iv);
1386 }
1387 Op::CheckPolicy {
1388 subject, object, ..
1389 } => {
1390 f(*subject);
1391 if *object != Reg::MAX {
1392 f(*object);
1393 }
1394 }
1395 // concurrency / net handle + value reads
1396 Op::ChanSend { chan, val } => {
1397 f(*chan);
1398 f(*val);
1399 }
1400 Op::ChanRecv { chan, .. } | Op::ChanTryRecv { chan, .. } | Op::ChanClose { chan } => {
1401 f(*chan)
1402 }
1403 Op::ChanTrySend { chan, val, .. } => {
1404 f(*chan);
1405 f(*val);
1406 }
1407 Op::TaskAwait { handle, .. } | Op::TaskAbort { handle } => f(*handle),
1408 Op::SelectArmRecv { chan, .. } => f(*chan),
1409 Op::SelectArmTimeout { ticks } => f(*ticks),
1410 Op::NetConnect { url } => f(*url),
1411 Op::NetListen { topic } => f(*topic),
1412 Op::NetSend { to, msg } => {
1413 f(*to);
1414 f(*msg);
1415 }
1416 Op::NetStream { to, values } => {
1417 f(*to);
1418 f(*values);
1419 }
1420 Op::NetAwait { from, .. } => f(*from),
1421 Op::NetMakePeer { addr, .. } => f(*addr),
1422 Op::NetSync { dst, topic } => {
1423 f(*dst);
1424 f(*topic);
1425 }
1426 Op::Serve { port, .. } => f(*port),
1427 Op::NewEmptyListWithCapacity { capacity, .. }
1428 | Op::NewEmptyMapWithCapacity { capacity, .. } => f(*capacity),
1429 // read nothing
1430 Op::LoadConst { .. }
1431 | Op::LoadToday { .. }
1432 | Op::LoadNow { .. }
1433 | Op::Args { .. }
1434 | Op::NewEmptyList { .. }
1435 | Op::NewEmptyListFixed { .. }
1436 | Op::NewEmptyListI32 { .. }
1437 | Op::NewEmptySet { .. }
1438 | Op::NewEmptyMap { .. }
1439 | Op::NewStruct { .. }
1440 | Op::NewCrdt { .. }
1441 | Op::GlobalGet { .. }
1442 | Op::ChanNew { .. }
1443 | Op::SelectWait { .. }
1444 | Op::Jump { .. }
1445 | Op::IterNext { .. }
1446 | Op::IterPop
1447 | Op::ReturnNothing
1448 | Op::Halt
1449 | Op::FailWith { .. } => {}
1450 }
1451 }
1452
1453 /// One instance of EVERY VM bytecode op — the full instruction catalog of the language. Catalog
1454 /// locks iterate this to COUNT coverage/classification. (`name`, WASM-AOT `op_support`, and
1455 /// `reversibility` are exhaustive matches, so the compiler already forbids a new op from
1456 /// escaping classification; this enumeration is what lets a lock *count* the ISA.)
1457 pub fn all_variants() -> Vec<Op> {
1458 let s = Symbol::from_index(0);
1459 use crate::semantics::builtins::BuiltinId;
1460 vec![
1461 Op::LoadConst { dst: 0, idx: 0 },
1462 Op::Move { dst: 0, src: 0 },
1463 Op::RevSwap { a: 0, b: 0 },
1464 Op::RevXor { place: 0, delta: 1 },
1465 Op::RevNeg { place: 0 },
1466 Op::RevAdd { place: 0, delta: 1 },
1467 Op::RevSub { place: 0, delta: 1 },
1468 Op::EnsureOwned { reg: 0 },
1469 Op::Add {
1470 dst: 0,
1471 lhs: 0,
1472 rhs: 0,
1473 },
1474 Op::AddAssign { dst: 0, src: 0 },
1475 Op::Sub {
1476 dst: 0,
1477 lhs: 0,
1478 rhs: 0,
1479 },
1480 Op::Mul {
1481 dst: 0,
1482 lhs: 0,
1483 rhs: 0,
1484 },
1485 Op::Div {
1486 dst: 0,
1487 lhs: 0,
1488 rhs: 0,
1489 },
1490 Op::ExactDiv {
1491 dst: 0,
1492 lhs: 0,
1493 rhs: 0,
1494 },
1495 Op::FloorDiv {
1496 dst: 0,
1497 lhs: 0,
1498 rhs: 0,
1499 },
1500 Op::Mod {
1501 dst: 0,
1502 lhs: 0,
1503 rhs: 0,
1504 },
1505 Op::DivPow2 {
1506 dst: 0,
1507 lhs: 0,
1508 k: 0,
1509 },
1510 Op::MagicDivU {
1511 dst: 0,
1512 lhs: 0,
1513 magic: 0,
1514 more: 0,
1515 mul_back: 0,
1516 divisor: 1,
1517 wrap: false,
1518 },
1519 Op::Lt {
1520 dst: 0,
1521 lhs: 0,
1522 rhs: 0,
1523 },
1524 Op::Gt {
1525 dst: 0,
1526 lhs: 0,
1527 rhs: 0,
1528 },
1529 Op::LtEq {
1530 dst: 0,
1531 lhs: 0,
1532 rhs: 0,
1533 },
1534 Op::GtEq {
1535 dst: 0,
1536 lhs: 0,
1537 rhs: 0,
1538 },
1539 Op::Eq {
1540 dst: 0,
1541 lhs: 0,
1542 rhs: 0,
1543 },
1544 Op::ApproxEq {
1545 dst: 0,
1546 lhs: 0,
1547 rhs: 0,
1548 },
1549 Op::NotEq {
1550 dst: 0,
1551 lhs: 0,
1552 rhs: 0,
1553 },
1554 Op::Not { dst: 0, src: 0 },
1555 Op::Concat {
1556 dst: 0,
1557 lhs: 0,
1558 rhs: 0,
1559 },
1560 Op::SeqConcat {
1561 dst: 0,
1562 lhs: 0,
1563 rhs: 0,
1564 },
1565 Op::Pow {
1566 dst: 0,
1567 lhs: 0,
1568 rhs: 0,
1569 },
1570 Op::BitXor {
1571 dst: 0,
1572 lhs: 0,
1573 rhs: 0,
1574 },
1575 Op::BitAnd {
1576 dst: 0,
1577 lhs: 0,
1578 rhs: 0,
1579 },
1580 Op::BitOr {
1581 dst: 0,
1582 lhs: 0,
1583 rhs: 0,
1584 },
1585 Op::Shl {
1586 dst: 0,
1587 lhs: 0,
1588 rhs: 0,
1589 },
1590 Op::Shr {
1591 dst: 0,
1592 lhs: 0,
1593 rhs: 0,
1594 },
1595 Op::Jump { target: 0 },
1596 Op::JumpIfFalse { cond: 0, target: 0 },
1597 Op::JumpIfTrue { cond: 0, target: 0 },
1598 Op::Call {
1599 dst: 0,
1600 func: 0,
1601 args_start: 0,
1602 arg_count: 0,
1603 },
1604 Op::CallBuiltin {
1605 dst: 0,
1606 builtin: BuiltinId::Sqrt,
1607 args_start: 0,
1608 arg_count: 1,
1609 },
1610 Op::CallValue {
1611 dst: 0,
1612 callee: 0,
1613 args_start: 0,
1614 arg_count: 0,
1615 name_for_err: 0,
1616 },
1617 Op::MakeClosure {
1618 dst: 0,
1619 func: 0,
1620 locals_start: 0,
1621 },
1622 Op::CheckPolicy {
1623 subject: 0,
1624 predicate: s,
1625 is_capability: false,
1626 object: 0,
1627 source_text: 0,
1628 },
1629 Op::ListPushField {
1630 obj: 0,
1631 field: 0,
1632 src: 0,
1633 },
1634 Op::GlobalGet { dst: 0, idx: 0 },
1635 Op::GlobalSet { idx: 0, src: 0 },
1636 Op::Return { src: 0 },
1637 Op::ReturnNothing,
1638 Op::NewList {
1639 dst: 0,
1640 start: 0,
1641 count: 0,
1642 },
1643 Op::NewEmptyList { dst: 0 },
1644 Op::NewEmptyListWithCapacity {
1645 dst: 0,
1646 capacity: 1,
1647 },
1648 Op::NewEmptyListFixed {
1649 dst: 0,
1650 capacity: 8,
1651 },
1652 Op::NewEmptyListI32 { dst: 0 },
1653 Op::NewEmptySet { dst: 0 },
1654 Op::NewEmptyMap { dst: 0 },
1655 Op::NewEmptyMapWithCapacity {
1656 dst: 0,
1657 capacity: 1,
1658 },
1659 Op::NewRange {
1660 dst: 0,
1661 start: 0,
1662 end: 0,
1663 },
1664 Op::ListPush { list: 0, value: 0 },
1665 Op::SetAdd { set: 0, value: 0 },
1666 Op::RemoveFrom {
1667 collection: 0,
1668 value: 0,
1669 },
1670 Op::SetIndex {
1671 collection: 0,
1672 index: 0,
1673 value: 0,
1674 },
1675 Op::SetIndexUnchecked {
1676 collection: 0,
1677 index: 0,
1678 value: 0,
1679 },
1680 Op::Index {
1681 dst: 0,
1682 collection: 0,
1683 index: 0,
1684 },
1685 Op::IndexUnchecked {
1686 dst: 0,
1687 collection: 0,
1688 index: 0,
1689 },
1690 Op::RegionBoundsGuard {
1691 array: 0,
1692 bound: 0,
1693 iv: 0,
1694 add_max: 0,
1695 add_min: 0,
1696 },
1697 Op::Length {
1698 dst: 0,
1699 collection: 0,
1700 },
1701 Op::Contains {
1702 dst: 0,
1703 collection: 0,
1704 value: 0,
1705 },
1706 Op::FormatValue {
1707 dst: 0,
1708 src: 0,
1709 spec: 0,
1710 debug_prefix: 0,
1711 },
1712 Op::SliceOp {
1713 dst: 0,
1714 collection: 0,
1715 start: 0,
1716 end: 0,
1717 },
1718 Op::DeepClone { dst: 0, src: 0 },
1719 Op::NewTuple {
1720 dst: 0,
1721 start: 0,
1722 count: 0,
1723 },
1724 Op::UnionOp {
1725 dst: 0,
1726 lhs: 0,
1727 rhs: 0,
1728 },
1729 Op::IntersectOp {
1730 dst: 0,
1731 lhs: 0,
1732 rhs: 0,
1733 },
1734 Op::LoadToday { dst: 0 },
1735 Op::LoadNow { dst: 0 },
1736 Op::NewStruct {
1737 dst: 0,
1738 type_name: 0,
1739 },
1740 Op::StructInsert {
1741 obj: 0,
1742 field: 0,
1743 value: 0,
1744 },
1745 Op::GetField {
1746 dst: 0,
1747 obj: 0,
1748 field: 0,
1749 },
1750 Op::NewInductive {
1751 dst: 0,
1752 type_name: 0,
1753 ctor: 0,
1754 args_start: 0,
1755 count: 0,
1756 },
1757 Op::TestArm {
1758 dst: 0,
1759 target: 0,
1760 variant: 0,
1761 },
1762 Op::BindArm {
1763 dst: 0,
1764 target: 0,
1765 field: 0,
1766 index: 0,
1767 },
1768 Op::CrdtBump {
1769 obj: 0,
1770 field: 0,
1771 amount: 0,
1772 negate: false,
1773 },
1774 Op::CrdtMerge {
1775 target: 0,
1776 source: 0,
1777 },
1778 Op::CrdtJoin {
1779 target: 0,
1780 source: 0,
1781 },
1782 Op::BigIntWide {
1783 kind: 0,
1784 dst: 0,
1785 a: 0,
1786 b: 0,
1787 },
1788 Op::NewCrdt { dst: 0, kind: 0 },
1789 Op::CrdtAppend { seq: 0, value: 0 },
1790 Op::CrdtResolve {
1791 obj: 0,
1792 field: 0,
1793 value: 0,
1794 },
1795 Op::IterPrepare { iterable: 0 },
1796 Op::IterNext { dst: 0, exit: 0 },
1797 Op::IterPop,
1798 Op::ListPop { list: 0, dst: 0 },
1799 Op::Sleep { duration: 0 },
1800 Op::DestructureTuple {
1801 src: 0,
1802 start: 0,
1803 count: 0,
1804 },
1805 Op::Show { src: 0 },
1806 Op::Args { dst: 0 },
1807 Op::ChanNew {
1808 dst: 0,
1809 cap: 0,
1810 elem: ChanElem::Unknown,
1811 },
1812 Op::ChanSend { chan: 0, val: 0 },
1813 Op::ChanRecv { dst: 0, chan: 0 },
1814 Op::ChanTrySend {
1815 dst: 0,
1816 chan: 0,
1817 val: 0,
1818 },
1819 Op::ChanTryRecv { dst: 0, chan: 0 },
1820 Op::ChanClose { chan: 0 },
1821 Op::Spawn {
1822 func: 0,
1823 args_start: 0,
1824 arg_count: 0,
1825 },
1826 Op::SpawnHandle {
1827 dst: 0,
1828 func: 0,
1829 args_start: 0,
1830 arg_count: 0,
1831 },
1832 Op::TaskAwait { dst: 0, handle: 0 },
1833 Op::TaskAbort { handle: 0 },
1834 Op::SelectArmRecv { chan: 0, var: 0 },
1835 Op::SelectArmTimeout { ticks: 0 },
1836 Op::SelectWait { dst_arm: 0 },
1837 Op::NetConnect { url: 0 },
1838 Op::NetListen { topic: 0 },
1839 Op::NetSend { to: 0, msg: 0 },
1840 Op::NetStream { to: 0, values: 0 },
1841 Op::NetAwait {
1842 dst: 0,
1843 from: 0,
1844 stream: false,
1845 },
1846 Op::NetMakePeer { dst: 0, addr: 0 },
1847 Op::NetSync { dst: 0, topic: 0 },
1848 Op::Tcp {
1849 dst: 0,
1850 kind: 0,
1851 args_start: 0,
1852 arg_count: 0,
1853 },
1854 Op::Serve {
1855 port: 0,
1856 handler: 0,
1857 },
1858 Op::FailWith { msg: 0 },
1859 Op::Obs {
1860 site: 0,
1861 args_start: 0,
1862 args_count: 0,
1863 },
1864 Op::Halt,
1865 ]
1866 }
1867}
1868
1869/// A parameter's (or struct field's) declared type, RESOLVED at compile time into a self-contained
1870/// form a STATICALLY-typed consumer can use without the AST or the interner. The dynamically-typed
1871/// tree-walker/VM and the scalar-only native JIT never needed static types, so they were not put in
1872/// the bytecode before; they are now a first-class part of the compiled program (a struct is
1873/// referenced by name, its layout living in [`CompiledProgram::struct_types`]).
1874#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1875pub enum BoundaryType {
1876 Int,
1877 Float,
1878 Bool,
1879 Text,
1880 Date,
1881 Moment,
1882 /// A `Word32`/`Word64` wrapping-integer (ℤ/2ⁿ) — a native `i32`/`i64` scalar, so a `Seq of Word32`
1883 /// parameter (a crypto state array) resolves its element kind cross-region.
1884 Word32,
1885 Word64,
1886 /// `Seq of <elem>`.
1887 Seq(Box<BoundaryType>),
1888 /// A user struct, by name — its field layout is in [`CompiledProgram::struct_types`].
1889 Struct(String),
1890 /// A user enum (sum type), by name. Carried as one i32 handle whose word 0 is the constructor
1891 /// tag; `Inspect`/`TestArm` read the tag directly, so no separate layout is needed.
1892 Enum(String),
1893 /// `Result of <ok> and <err>` — an enum with no NAME, carrying its two payload types.
1894 ///
1895 /// ★ STRUCTURAL BECAUSE IT IS ANONYMOUS. Every other enum here is a name to look up in
1896 /// [`CompiledProgram::enum_types`], because a `## An X is one of:` declared it. A `Result`
1897 /// is written at its use site and never declared, and two instantiations in one program
1898 /// (`Result of Int and E` beside `Result of Text and F`) are different types that would
1899 /// collide under any single name — so the payload types are carried here rather than
1900 /// resolved through a table. Laid out exactly as [`BoundaryType::Enum`]: one i32 handle
1901 /// whose word 0 is the `Ok`/`Err` tag.
1902 Result(Box<BoundaryType>, Box<BoundaryType>),
1903 /// `Map of <key> to <value>` — one i32 handle. The key kind is recovered at each access from the
1904 /// key expression's own kind (no map metadata needed); the VALUE kind is carried here so a
1905 /// parameter map's `item k of m` resolves its result kind cross-region.
1906 Map(Box<BoundaryType>, Box<BoundaryType>),
1907 /// A HETEROGENEOUS tuple (`Pair`/`Triple` of mixed element types) — one i32 handle to a buffer of
1908 /// 8-byte slots, each holding its element at its own kind. The per-position element types are
1909 /// carried so a `item N of t` (constant `N`) resolves its result kind cross-region. (A homogeneous
1910 /// tuple resolves to [`BoundaryType::Seq`] instead — it shares the list buffer layout.)
1911 Tuple(Vec<BoundaryType>),
1912 /// A first-class BUILTIN value type by name (`Uuid`, `Duration`, `Time`, `Span`, `Money`,
1913 /// `Quantity`, `Rational`, `Complex`, `Decimal`, `Modular`) — a scalar/handle type whose wasm
1914 /// register kind is fixed by its name, not by a user-defined layout. Carried by name (like
1915 /// [`BoundaryType::Struct`]/[`BoundaryType::Enum`]) so a cross-region parameter/return of one of
1916 /// these types (`uuidV5(namespace: Uuid) -> Uuid`) seeds the correct handle kind; a name with no
1917 /// wasm kind resolves to `None` and is left soundly unmodeled.
1918 Builtin(String),
1919 /// `Set of <elem>` — one i32 handle to an insertion-ordered dedup'd buffer, exactly like the VM's
1920 /// hashset. The element type distinguishes the two self-describing set kinds: a `Set of Int` rides
1921 /// `Kind::Set` (i64 slots, dedup by value) and a `Set of Text` rides `Kind::SetText` (Text-handle
1922 /// slots, dedup by byte equality); other element types have no self-contained set kind and resolve
1923 /// to `None`. (Placed LAST so the pre-existing bincode variant indices stay stable.)
1924 Set(Box<BoundaryType>),
1925 /// `Option of <inner>` — an anonymous two-constructor enum (`Some` carrying one payload,
1926 /// `None` carrying nothing), carrying its payload type.
1927 ///
1928 /// ★ STRUCTURAL FOR THE SAME REASON AS `Result`, and absent for a long time because an Option
1929 /// used not to be a value at all: `some x` compiled to `x` and `none` to the `Nothing`
1930 /// sentinel, so there was no type to carry and `boundary_of_type_expr` fell to `_ => None`.
1931 /// Now that an Option is a real tagged inductive, the payload type has to reach the backends
1932 /// or they cannot emit a printer for a `When Some (v):` arm — which is a real refusal on wasm
1933 /// ("Show of an unknown-kind value") for an Option that happens to be absent, since that arm
1934 /// is still lowered even though it never runs.
1935 ///
1936 /// (Placed LAST so the pre-existing bincode variant indices stay stable — the same rule `Set`
1937 /// records above.)
1938 Option(Box<BoundaryType>),
1939}
1940
1941/// A struct type's resolved field layout (fields in declaration / slot order), carried in the
1942/// bytecode so any consumer can address a struct's fields without re-deriving them from the AST.
1943#[derive(Clone, Debug, Serialize, Deserialize)]
1944pub struct StructTypeDef {
1945 pub name: String,
1946 pub fields: Vec<(String, BoundaryType)>,
1947}
1948
1949/// One variant of an enum: its constructor name and the resolved types of its payload fields, in
1950/// position order (empty for a nullary variant). A `BindArm` extracts payload position `index`.
1951#[derive(Clone, Debug, Serialize, Deserialize)]
1952pub struct EnumVariantDef {
1953 pub name: String,
1954 pub field_types: Vec<BoundaryType>,
1955}
1956
1957/// An enum type's resolved per-variant payload layout, carried in the bytecode so a consumer can
1958/// type a `When V (binds)` payload extraction on a value whose construction isn't visible (an enum
1959/// PARAMETER) — the sum-type analog of [`StructTypeDef`].
1960#[derive(Clone, Debug, Serialize, Deserialize)]
1961pub struct EnumTypeDef {
1962 pub name: String,
1963 pub variants: Vec<EnumVariantDef>,
1964}
1965
1966/// A compiled user function (or closure body). All bodies share the program's
1967/// single `code` vector; `entry_pc` is where this one begins. A closure body's
1968/// frame layout is `[params… , capture values… , capture-present flags…]`.
1969#[derive(Clone, Debug)]
1970pub struct CompiledFunction {
1971 pub name: Symbol,
1972 pub entry_pc: usize,
1973 pub param_count: u16,
1974 pub register_count: usize,
1975 /// Capture list for a closure body (empty for plain functions), in frame
1976 /// order. Each entry: the captured name and, when that name is a promoted
1977 /// global, its global index (the live-fallback source).
1978 pub captures: Vec<(Symbol, Option<u16>)>,
1979 /// Which of THIS frame's registers carry a user-visible name (params,
1980 /// captures, Let targets, loop variables) — the region JIT's
1981 /// observability map for loops tiering up inside this function.
1982 pub named_regs: Vec<bool>,
1983 /// DECLARED parameter kinds: scalars (`x: Float`) ride i64 slots,
1984 /// `Seq of <scalar>` pins at the boundary; `None` for types native
1985 /// code cannot represent (Map, Text, nested Seq, …). Closures (no
1986 /// declarations) default to all-Int — exactly the old entry-guard
1987 /// contract.
1988 pub param_kinds: Vec<Option<super::native_tier::ParamKind>>,
1989 /// Declared return kind; `None` falls back to the adapter's Int/Bool
1990 /// return inference.
1991 pub ret_kind: Option<super::native_tier::SlotKind>,
1992 /// Each parameter's FULL declared type, resolved at compile time (`None` for a closure body —
1993 /// no declarations — or a type the resolver does not model). Unlike `param_kinds` (a scalar/list
1994 /// performance hint for the native tier), this carries struct/Text/etc. so a statically-typed
1995 /// consumer can type a `f(p: Point)` / `f(s: Text)` parameter from the bytecode alone.
1996 pub param_types: Vec<Option<BoundaryType>>,
1997 /// The function's FULL declared RETURN type, resolved at compile time (`None` if undeclared or
1998 /// unmodeled). Carries struct/map/enum/etc. so a caller can type the inline use of a returned
1999 /// composite (`item k of f()`, `Inspect f()`) the same way a parameter of that type is typed.
2000 pub return_type: Option<BoundaryType>,
2001 /// Argument registers retained on return so an in-out call can copy the
2002 /// final values back to the caller. Includes inferred mutable-borrow slots.
2003 pub mutable_param_regs: Vec<Reg>,
2004 /// Registers proven to be consumed-and-returned borrows. Only these may
2005 /// bypass copy-on-write; an explicit mutable parameter may make local copies.
2006 pub cow_exempt_regs: Vec<Reg>,
2007}
2008
2009/// What an [`Op::Obs`] emits, resolved at COMPILE time (Wave 13). A `Message`
2010/// carries the speech-act category, the that-clause text, and the payload NAMES
2011/// (values live in the op's register range); `SpanEnter`/`SpanExit` carry the
2012/// span label. Kept off the hot loop — the machine only reads it.
2013#[derive(Clone, Debug)]
2014pub enum ObsSiteKind {
2015 Message(crate::observe::ObsCat),
2016 SpanEnter,
2017 SpanExit,
2018}
2019
2020/// One compiled observation site (indexed by `Op::Obs { site }`).
2021#[derive(Clone, Debug)]
2022pub struct ObsSiteDesc {
2023 pub kind: ObsSiteKind,
2024 pub message: String,
2025 pub payload_names: Vec<String>,
2026 pub sample: Option<u64>,
2027}
2028
2029/// DEBUG-ONLY names for one compiled function, for the Studio debug drawer.
2030#[derive(Clone, Debug, Default, PartialEq)]
2031pub struct FnDebugInfo {
2032 /// The function's source name, for the call stack.
2033 pub name: String,
2034 /// Register index → source variable name (parameters and locals) in its frame.
2035 pub reg_names: Vec<(u16, String)>,
2036}
2037
2038/// A compiled program: the constant pool, the linear bytecode (Main first, then
2039/// every function body), the size of Main's register frame, and the function
2040/// table (indexed by `FuncIdx`, with a name → index map for call resolution).
2041#[derive(Clone, Debug, Default)]
2042pub struct CompiledProgram {
2043 pub constants: Vec<Constant>,
2044 pub code: Vec<Op>,
2045 pub register_count: usize,
2046 pub functions: Vec<CompiledFunction>,
2047 pub fn_index: HashMap<Symbol, FuncIdx>,
2048 /// Names of the promoted globals (Main top-level bindings referenced from
2049 /// function/closure bodies), for "Undefined variable" errors.
2050 pub globals: Vec<String>,
2051 /// Which Main-frame registers carry a user-visible NAME (Let targets,
2052 /// loop variables). Everything else is a statement-local scratch — dead
2053 /// at every statement boundary by the allocator's recycling discipline —
2054 /// so the region JIT neither writes it back nor preserves its pre-state.
2055 pub named_regs: Vec<bool>,
2056 /// `loop_locals[head]` = the registers bound INSIDE the loop whose region
2057 /// head (back-edge target) is the absolute pc `head` — names lexically dead
2058 /// the moment that loop exits. The region JIT subtracts these from the
2059 /// write-back set, so copy-prop/CSE/fusion can treat them as true scratch.
2060 /// Keyed by absolute pc (one code array); valued by the head's OWNING frame's
2061 /// register indices (Main or the enclosing function).
2062 pub loop_locals: HashMap<usize, Vec<bool>>,
2063 /// DEBUG-ONLY: Main-frame register index → source variable name, populated only
2064 /// by the debugger's compile path ([`crate::vm::Compiler::compile_for_debug`]).
2065 /// Empty on every production build, so the runtime pays nothing; it just lets the
2066 /// Studio debug drawer show `x` instead of `R0`.
2067 pub reg_names: Vec<(u16, String)>,
2068 /// DEBUG-ONLY: each function's source name and register → variable names, indexed like
2069 /// `functions`. Populated only by the debugger's compile path, like `reg_names`; empty on
2070 /// every production build.
2071 pub fn_debug: Vec<FnDebugInfo>,
2072 /// The program's struct type definitions (name → field layout), resolved at compile time. The
2073 /// bytecode's static type registry — the dynamically-typed tree-walker/VM never needed it, but a
2074 /// statically-typed consumer (the AOT backend) addresses a struct's fields through it.
2075 pub struct_types: Vec<StructTypeDef>,
2076 /// The program's enum type definitions (name → per-variant payload layout), resolved at compile
2077 /// time — the sum-type companion to `struct_types`. Lets the AOT backend type a `When V (binds)`
2078 /// payload extraction on an enum whose construction isn't in scope (an enum PARAMETER).
2079 pub enum_types: Vec<EnumTypeDef>,
2080 /// Each promoted GLOBAL's resolved composite type (by global index; `None` for scalar /
2081 /// self-describing / unmodeled). Lets the AOT type a closure that CAPTURES a composite global with
2082 /// the value's shape — the capture analog of a parameter's declared type.
2083 pub global_types: Vec<Option<BoundaryType>>,
2084 /// ★ WHAT THE PROGRAM DECLARES A VALUE TO BE, by the absolute pc of the op that defines it,
2085 /// sorted by pc. `a new Seq of Todo`, `a new Map of Text to Int` and `a new Set of Text` —
2086 /// wherever they are written, a constructor argument included — name their element types;
2087 /// `Let x: Seq of Text be …` and a `Let` of a call whose function declares `-> Seq of Todo` name
2088 /// the type of the value the binding's `Move` lands. A collection built EMPTY has no element
2089 /// to trace, so a statically-typed backend takes its kind from here, and infers only where
2090 /// nothing is declared.
2091 ///
2092 /// A side table rather than a field on the ops: the ops are matched exhaustively by every
2093 /// backend and catalog, and only the typed backends read this. Keyed by op position rather than
2094 /// register, because a backend renumbers registers before it reads it; every pass that moves
2095 /// ops (`peephole`'s `remove_ops`) remaps it the way it remaps jump targets, and a backend that
2096 /// lowers one region reads it through that region's own op mapping.
2097 pub declared_types: Vec<(u32, BoundaryType)>,
2098 /// Observation sites (Wave 13), indexed by `Op::Obs { site }`. EMPTY in the
2099 /// elided (compiled/release) profile — populated only when the VM compiles in
2100 /// the OBSERVED profile (`Compiler::compile_observed`), so ordinary programs
2101 /// pay nothing and `Op::Obs` never reaches the AOT/WASM backends.
2102 pub observation_sites: Vec<ObsSiteDesc>,
2103 /// `(pc, site_id)` pairs, sorted by `pc`, one entry per compiled function (Main included) at
2104 /// its `entry_pc` plus one per `Stmt::Site` marker the parser inserted — Wave 3: "runtime
2105 /// failures carry a location". A runtime error at pc `p` looks up the LAST entry with
2106 /// `pc <= p` (`partition_point`) for the site in force; every function opens with
2107 /// `NO_SITE` so a trap in the few ops before that function's own first author sentence
2108 /// (parameter binding, capture setup) does not inherit whatever site was active in the
2109 /// PREVIOUS function's own code, since `code` is one array (Main, then every function body).
2110 /// `site_id` indexes the parser's own `failure_sites()` table — this program does not carry
2111 /// that table itself (it lives beside the parsed AST, not the compiled one); a caller wanting
2112 /// a rendered location combines the two.
2113 pub site_at: Vec<(u32, u32)>,
2114}
2115
2116/// The `site_id` a pc range with no active `Stmt::Site` marker carries — append-only, like every
2117/// other wire-visible sentinel in this file.
2118pub const NO_SITE: u32 = u32::MAX;
2119
2120// ───────────────────────── register operands and control successors ─────────────────────────
2121//
2122// The ONE description of what each op does to registers and to control flow. The wasm backend's
2123// live-range splitter renames through it, the wasm place-mutation and heap analyses read op
2124// footprints through it, and the VM's copy-on-write asks it which registers are dead. A new `Op`
2125// variant fails to build until `visit_regs` classifies it.
2126
2127/// How an op touches a register operand.
2128#[derive(Clone, Copy, PartialEq, Eq, Debug)]
2129pub(crate) enum Role {
2130 /// Written (the prior value is dead).
2131 Def,
2132 /// Read.
2133 Use,
2134 /// Read AND written through the SAME single field (`x += …`) — must rename to one local.
2135 DefUse,
2136}
2137
2138/// A visitor over an op's register operands. `scalar` is a single register field; `range` is a
2139/// `count`-wide block of consecutive registers starting at `*start` (the members past `*start` are
2140/// implicit — not fields — so only `*start` is handed over, but the whole block is pinned).
2141pub(crate) trait RegVisitor {
2142 fn scalar(&mut self, r: &mut Reg, role: Role);
2143 fn range(&mut self, start: &mut Reg, count: u16, role: Role);
2144 /// A register block that must stay CONTIGUOUS only when it has ≥2 members — a range of ONE has
2145 /// no positional constraint, so its lone operand is a plain renamable scalar (the op reads it
2146 /// through `args_start`, which the rename updates). Visiting it as a scalar lets a single-arg
2147 /// call/builtin operand split off a register that a wider call reuses (spectral_norm's `Sqrt`
2148 /// arg sharing a slot with a 4-arg call's `Seq of Float` argument).
2149 fn members(&mut self, start: &mut Reg, count: u16, role: Role) {
2150 if count == 1 {
2151 self.scalar(start, role);
2152 } else {
2153 self.range(start, count, role);
2154 }
2155 }
2156}
2157
2158/// THE exhaustive enumeration of every op's register operands (compiler-enforced total match: a new
2159/// `Op` variant fails to build until classified here). `functions` resolves a `MakeClosure`'s
2160/// capture count, whose register range is not stored in the op. Takes `&mut Op` so the same routine
2161/// drives both read-only analysis and in-place renaming.
2162pub(crate) fn visit_regs(op: &mut Op, functions: &[CompiledFunction], v: &mut dyn RegVisitor) {
2163 use Role::{Def, DefUse, Use};
2164 match op {
2165 Op::LoadConst { dst, .. } => v.scalar(dst, Def),
2166 Op::Move { dst, src } => {
2167 v.scalar(src, Use);
2168 v.scalar(dst, Def);
2169 }
2170 // Register swap: both operands are read AND written in place.
2171 Op::RevSwap { a, b } => {
2172 v.scalar(a, DefUse);
2173 v.scalar(b, DefUse);
2174 }
2175 // In-place XOR: `place` is read+written, `delta` is read-only.
2176 Op::RevXor { place, delta } => {
2177 v.scalar(delta, Use);
2178 v.scalar(place, DefUse);
2179 }
2180 // In-place modular negation: single operand, read+written.
2181 Op::RevNeg { place } => v.scalar(place, DefUse),
2182 // In-place modular add/subtract: `place` read+written, `delta` read-only.
2183 Op::RevAdd { place, delta } | Op::RevSub { place, delta } => {
2184 v.scalar(delta, Use);
2185 v.scalar(place, DefUse);
2186 }
2187 Op::EnsureOwned { reg } => v.scalar(reg, Role::DefUse),
2188 Op::Add { dst, lhs, rhs }
2189 | Op::Sub { dst, lhs, rhs }
2190 | Op::Mul { dst, lhs, rhs }
2191 | Op::Pow { dst, lhs, rhs }
2192 | Op::Div { dst, lhs, rhs }
2193 | Op::ExactDiv { dst, lhs, rhs }
2194 | Op::FloorDiv { dst, lhs, rhs }
2195 | Op::Mod { dst, lhs, rhs }
2196 | Op::Lt { dst, lhs, rhs }
2197 | Op::Gt { dst, lhs, rhs }
2198 | Op::LtEq { dst, lhs, rhs }
2199 | Op::GtEq { dst, lhs, rhs }
2200 | Op::Eq { dst, lhs, rhs }
2201 | Op::NotEq { dst, lhs, rhs }
2202 | Op::ApproxEq { dst, lhs, rhs }
2203 | Op::Concat { dst, lhs, rhs }
2204 | Op::SeqConcat { dst, lhs, rhs }
2205 | Op::BitXor { dst, lhs, rhs }
2206 | Op::BitAnd { dst, lhs, rhs }
2207 | Op::BitOr { dst, lhs, rhs }
2208 | Op::Shl { dst, lhs, rhs }
2209 | Op::Shr { dst, lhs, rhs }
2210 | Op::UnionOp { dst, lhs, rhs }
2211 | Op::IntersectOp { dst, lhs, rhs } => {
2212 v.scalar(lhs, Use);
2213 v.scalar(rhs, Use);
2214 v.scalar(dst, Def);
2215 }
2216 Op::AddAssign { dst, src } => {
2217 v.scalar(src, Use);
2218 v.scalar(dst, DefUse);
2219 }
2220 Op::DivPow2 { dst, lhs, .. } | Op::MagicDivU { dst, lhs, .. } => {
2221 v.scalar(lhs, Use);
2222 v.scalar(dst, Def);
2223 }
2224 Op::Not { dst, src } | Op::DeepClone { dst, src } => {
2225 v.scalar(src, Use);
2226 v.scalar(dst, Def);
2227 }
2228 Op::Jump { .. } => {}
2229 Op::JumpIfFalse { cond, .. } | Op::JumpIfTrue { cond, .. } => v.scalar(cond, Use),
2230 Op::Call {
2231 dst,
2232 func,
2233 args_start,
2234 arg_count,
2235 } => {
2236 v.members(args_start, *arg_count, Use);
2237 // A `mutable` parameter's final value comes back in its argument register, which the caller copies
2238 // into the place it lent (`CompiledFunction::mutable_param_regs`): the call reads and writes it.
2239 if let Some(f) = functions.get(*func as usize) {
2240 for &p in f.mutable_param_regs.iter().filter(|p| **p < *arg_count) {
2241 let mut member = args_start.wrapping_add(p);
2242 v.scalar(&mut member, DefUse);
2243 }
2244 }
2245 v.scalar(dst, Def);
2246 }
2247 Op::CallBuiltin {
2248 dst,
2249 args_start,
2250 arg_count,
2251 ..
2252 } => {
2253 v.members(args_start, *arg_count, Use);
2254 v.scalar(dst, Def);
2255 }
2256 Op::CallValue {
2257 dst,
2258 callee,
2259 args_start,
2260 arg_count,
2261 ..
2262 } => {
2263 v.scalar(callee, Use);
2264 v.members(args_start, *arg_count, Use);
2265 v.scalar(dst, Def);
2266 }
2267 Op::MakeClosure {
2268 dst,
2269 func,
2270 locals_start,
2271 } => {
2272 let cap_n = functions
2273 .get(*func as usize)
2274 .map_or(0, |f| f.captures.len() as u16);
2275 v.members(locals_start, cap_n, Use);
2276 v.scalar(dst, Def);
2277 }
2278 Op::CheckPolicy {
2279 subject, object, ..
2280 } => {
2281 v.scalar(subject, Use);
2282 if *object != Reg::MAX {
2283 v.scalar(object, Use);
2284 }
2285 }
2286 Op::ListPushField { obj, src, .. } => {
2287 v.scalar(obj, Use);
2288 v.scalar(src, Use);
2289 }
2290 Op::GlobalGet { dst, .. } => v.scalar(dst, Def),
2291 Op::GlobalSet { src, .. } => v.scalar(src, Use),
2292 Op::Return { src } => v.scalar(src, Use),
2293 Op::ReturnNothing => {}
2294 Op::NewList { dst, start, count } | Op::NewTuple { dst, start, count } => {
2295 v.members(start, *count, Use);
2296 v.scalar(dst, Def);
2297 }
2298 Op::NewEmptyList { dst }
2299 | Op::NewEmptyListFixed { dst, .. }
2300 | Op::NewEmptyListI32 { dst }
2301 | Op::NewEmptySet { dst }
2302 | Op::NewEmptyMap { dst }
2303 | Op::LoadToday { dst }
2304 | Op::LoadNow { dst }
2305 | Op::NewStruct { dst, .. }
2306 | Op::NewCrdt { dst, .. }
2307 | Op::Args { dst }
2308 | Op::ChanNew { dst, .. }
2309 | Op::SelectWait { dst_arm: dst } => v.scalar(dst, Def),
2310 Op::NewEmptyListWithCapacity { dst, capacity }
2311 | Op::NewEmptyMapWithCapacity { dst, capacity } => {
2312 v.scalar(capacity, Use);
2313 v.scalar(dst, Def);
2314 }
2315 Op::NewRange { dst, start, end } => {
2316 v.scalar(start, Use);
2317 v.scalar(end, Use);
2318 v.scalar(dst, Def);
2319 }
2320 Op::ListPush { list, value } => {
2321 v.scalar(list, Use);
2322 v.scalar(value, Use);
2323 }
2324 Op::SetAdd { set, value } => {
2325 v.scalar(set, Use);
2326 v.scalar(value, Use);
2327 }
2328 Op::RemoveFrom { collection, value } => {
2329 v.scalar(collection, Use);
2330 v.scalar(value, Use);
2331 }
2332 Op::Contains {
2333 dst,
2334 collection,
2335 value,
2336 } => {
2337 v.scalar(collection, Use);
2338 v.scalar(value, Use);
2339 v.scalar(dst, Def);
2340 }
2341 Op::SetIndex {
2342 collection,
2343 index,
2344 value,
2345 }
2346 | Op::SetIndexUnchecked {
2347 collection,
2348 index,
2349 value,
2350 } => {
2351 v.scalar(collection, Use);
2352 v.scalar(index, Use);
2353 v.scalar(value, Use);
2354 }
2355 Op::Index {
2356 dst,
2357 collection,
2358 index,
2359 }
2360 | Op::IndexUnchecked {
2361 dst,
2362 collection,
2363 index,
2364 } => {
2365 v.scalar(collection, Use);
2366 v.scalar(index, Use);
2367 v.scalar(dst, Def);
2368 }
2369 Op::RegionBoundsGuard {
2370 array, bound, iv, ..
2371 } => {
2372 v.scalar(array, Use);
2373 v.scalar(bound, Use);
2374 v.scalar(iv, Use);
2375 }
2376 Op::Length { dst, collection } => {
2377 v.scalar(collection, Use);
2378 v.scalar(dst, Def);
2379 }
2380 Op::FormatValue { dst, src, .. } => {
2381 v.scalar(src, Use);
2382 v.scalar(dst, Def);
2383 }
2384 Op::SliceOp {
2385 dst,
2386 collection,
2387 start,
2388 end,
2389 } => {
2390 v.scalar(collection, Use);
2391 v.scalar(start, Use);
2392 v.scalar(end, Use);
2393 v.scalar(dst, Def);
2394 }
2395 Op::StructInsert { obj, value, .. } => {
2396 v.scalar(obj, Use);
2397 v.scalar(value, Use);
2398 }
2399 Op::GetField { dst, obj, .. } => {
2400 v.scalar(obj, Use);
2401 v.scalar(dst, Def);
2402 }
2403 Op::NewInductive {
2404 dst,
2405 args_start,
2406 count,
2407 ..
2408 } => {
2409 v.members(args_start, *count, Use);
2410 v.scalar(dst, Def);
2411 }
2412 Op::TestArm { dst, target, .. } | Op::BindArm { dst, target, .. } => {
2413 v.scalar(target, Use);
2414 v.scalar(dst, Def);
2415 }
2416 Op::CrdtBump { obj, amount, .. } => {
2417 v.scalar(obj, Use);
2418 v.scalar(amount, Use);
2419 }
2420 Op::CrdtMerge { target, source } | Op::CrdtJoin { target, source } => {
2421 v.scalar(target, Use);
2422 v.scalar(source, Use);
2423 }
2424 Op::BigIntWide { dst, a, b, .. } => {
2425 v.scalar(a, Use);
2426 v.scalar(b, Use);
2427 v.scalar(dst, Def);
2428 }
2429 Op::CrdtAppend { seq, value } => {
2430 v.scalar(seq, Use);
2431 v.scalar(value, Use);
2432 }
2433 Op::CrdtResolve { obj, value, .. } => {
2434 v.scalar(obj, Use);
2435 v.scalar(value, Use);
2436 }
2437 Op::IterPrepare { iterable } => v.scalar(iterable, Use),
2438 Op::IterNext { dst, .. } => v.scalar(dst, Def),
2439 Op::IterPop => {}
2440 Op::ListPop { list, dst } => {
2441 v.scalar(list, Use);
2442 v.scalar(dst, Def);
2443 }
2444 Op::Sleep { duration } => v.scalar(duration, Use),
2445 Op::DestructureTuple { src, start, count } => {
2446 v.scalar(src, Use);
2447 v.members(start, *count, Def);
2448 }
2449 Op::Show { src } => v.scalar(src, Use),
2450 Op::ChanSend { chan, val } => {
2451 v.scalar(chan, Use);
2452 v.scalar(val, Use);
2453 }
2454 Op::ChanRecv { dst, chan } | Op::ChanTryRecv { dst, chan } => {
2455 v.scalar(chan, Use);
2456 v.scalar(dst, Def);
2457 }
2458 Op::ChanTrySend { dst, chan, val } => {
2459 v.scalar(chan, Use);
2460 v.scalar(val, Use);
2461 v.scalar(dst, Def);
2462 }
2463 Op::ChanClose { chan } => v.scalar(chan, Use),
2464 Op::Spawn {
2465 args_start,
2466 arg_count,
2467 ..
2468 } => v.members(args_start, *arg_count, Use),
2469 Op::SpawnHandle {
2470 dst,
2471 args_start,
2472 arg_count,
2473 ..
2474 } => {
2475 v.members(args_start, *arg_count, Use);
2476 v.scalar(dst, Def);
2477 }
2478 Op::TaskAwait { dst, handle } => {
2479 v.scalar(handle, Use);
2480 v.scalar(dst, Def);
2481 }
2482 Op::TaskAbort { handle } => v.scalar(handle, Use),
2483 Op::SelectArmRecv { chan, var } => {
2484 v.scalar(chan, Use);
2485 v.scalar(var, Def);
2486 }
2487 Op::SelectArmTimeout { ticks } => v.scalar(ticks, Use),
2488 Op::NetConnect { url } => v.scalar(url, Use),
2489 Op::NetListen { topic } => v.scalar(topic, Use),
2490 Op::NetSend { to, msg } => {
2491 v.scalar(to, Use);
2492 v.scalar(msg, Use);
2493 }
2494 Op::NetStream { to, values } => {
2495 v.scalar(to, Use);
2496 v.scalar(values, Use);
2497 }
2498 Op::NetAwait { dst, from, .. } => {
2499 v.scalar(from, Use);
2500 v.scalar(dst, Def);
2501 }
2502 Op::NetMakePeer { dst, addr } => {
2503 v.scalar(addr, Use);
2504 v.scalar(dst, Def);
2505 }
2506 Op::NetSync { dst, topic } => {
2507 v.scalar(topic, Use);
2508 v.scalar(dst, DefUse);
2509 }
2510 Op::Tcp {
2511 dst,
2512 args_start,
2513 arg_count,
2514 ..
2515 } => {
2516 v.members(args_start, *arg_count, Use);
2517 v.scalar(dst, Def);
2518 }
2519 // `Serve` reads the port register; the handler rides a `FuncIdx`, not a register.
2520 Op::Serve { port, .. } => v.scalar(port, Use),
2521 // An observation reads its payload registers (the elided profile never emits one).
2522 Op::Obs {
2523 args_start,
2524 args_count,
2525 ..
2526 } => v.members(args_start, *args_count, Use),
2527 Op::FailWith { .. } | Op::Halt => {}
2528 }
2529}
2530
2531/// Every register an op DEFINES and every register it USES (register ranges expanded to members),
2532/// for any analysis that needs an op's full data-flow footprint and must not miss
2533/// an operand — it reuses the same exhaustive [`visit_regs`] enumeration, so a new op cannot slip
2534/// past. A `DefUse` operand appears in both lists.
2535pub(crate) fn op_def_uses(op: &Op, functions: &[CompiledFunction]) -> (Vec<Reg>, Vec<Reg>) {
2536 struct Collect {
2537 defs: Vec<Reg>,
2538 uses: Vec<Reg>,
2539 }
2540 impl RegVisitor for Collect {
2541 fn scalar(&mut self, r: &mut Reg, role: Role) {
2542 match role {
2543 Role::Def => self.defs.push(*r),
2544 Role::Use => self.uses.push(*r),
2545 Role::DefUse => {
2546 self.defs.push(*r);
2547 self.uses.push(*r);
2548 }
2549 }
2550 }
2551 fn range(&mut self, start: &mut Reg, count: u16, role: Role) {
2552 for i in 0..count {
2553 self.scalar(&mut start.wrapping_add(i), role);
2554 }
2555 }
2556 }
2557 let mut tmp = op.clone();
2558 let mut c = Collect {
2559 defs: Vec::new(),
2560 uses: Vec::new(),
2561 };
2562 visit_regs(&mut tmp, functions, &mut c);
2563 (c.defs, c.uses)
2564}
2565
2566/// The pcs control can reach from the op at `pc`, in the coordinate system of the op's own jump
2567/// targets (absolute over `program.code`, or region-relative after a backend rebases a region), with
2568/// fallthrough only to pcs below `end`. Every non-control-flow op falls through, so the explicit arms
2569/// are exactly the four ops that carry a target and the ops that never continue.
2570pub(crate) fn op_successors(op: &Op, pc: usize, end: usize) -> Vec<usize> {
2571 let fallthrough = |out: &mut Vec<usize>| {
2572 if pc + 1 < end {
2573 out.push(pc + 1);
2574 }
2575 };
2576 let mut out = Vec::new();
2577 match *op {
2578 Op::Jump { target } => out.push(target),
2579 Op::JumpIfFalse { target, .. } | Op::JumpIfTrue { target, .. } => {
2580 out.push(target);
2581 fallthrough(&mut out);
2582 }
2583 Op::IterNext { exit, .. } => {
2584 out.push(exit);
2585 fallthrough(&mut out);
2586 }
2587 Op::Return { .. } | Op::ReturnNothing | Op::Halt | Op::FailWith { .. } => {}
2588 // `Fail with …` / a broken contract's reason never returns.
2589 Op::CallBuiltin {
2590 builtin:
2591 crate::semantics::builtins::BuiltinId::Fail
2592 | crate::semantics::builtins::BuiltinId::FailReason,
2593 ..
2594 } => {}
2595 _ => fallthrough(&mut out),
2596 }
2597 out
2598}
2599
2600#[cfg(test)]
2601#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/vm/instruction/concurrency_op_tests.rs"]
2602mod concurrency_op_tests;