Skip to main content

logicaffeine_compile/vm/
compiler.rs

1//! AST → bytecode compiler.
2//!
3//! Layout: Main's bytecode is emitted first (entry pc 0) and ends with `Halt`;
4//! each function body is appended after it and reached via `Call` (an absolute
5//! jump to its `entry_pc`). Function names are registered in a first pass so
6//! forward references and (mutual) recursion resolve.
7//!
8//! Locals are assigned registers as they are first bound; expression temporaries
9//! get fresh registers above them, so a call's argument block never overlaps a
10//! live caller local.
11
12use std::collections::HashMap;
13
14use crate::ast::stmt::{BinaryOpKind, Expr, Literal, ObsCategory, Stmt};
15use crate::intern::{Interner, Symbol};
16
17use super::instruction::{
18    BoundaryType, CompiledFunction, CompiledProgram, ConstIdx, Constant, FnDebugInfo, FuncIdx,
19    ObsSiteDesc, ObsSiteKind, Op, Reg, StructTypeDef,
20};
21use super::{MAX_EXPR_DEPTH, MAX_REGISTERS_PER_FRAME};
22
23/// Why the bytecode compiler refused a program, and — when the refusal is about something the
24/// author wrote — where they wrote it.
25///
26/// `at` is a span in the parsed program's coordinates, attached where the refusal is DECIDED: the
27/// element, handler, route or page the message names. A limit of the compiler itself (the register
28/// or constant pools, nesting depth) was caused by no single construct and carries `None`. Every
29/// surface renders the location from here rather than recovering it from the message.
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct Refusal {
32    pub message: String,
33    pub at: Option<crate::token::Span>,
34}
35
36impl Refusal {
37    /// A refusal about the construct the author wrote at `span`.
38    pub fn at(span: crate::token::Span, message: impl Into<String>) -> Self {
39        Refusal {
40            message: message.into(),
41            at: Some(span),
42        }
43    }
44
45    /// The sentence alone, for a caller that reports text.
46    pub fn into_message(self) -> String {
47        self.message
48    }
49}
50
51impl From<String> for Refusal {
52    fn from(message: String) -> Self {
53        Refusal { message, at: None }
54    }
55}
56
57impl std::fmt::Display for Refusal {
58    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
59        f.write_str(&self.message)
60    }
61}
62
63/// A refusal as the diagnostic every source-pointing surface already renders: the message, at the
64/// construct's span. A span-less refusal reports at the start of the program, the one place a
65/// program-wide limit can be said to be.
66impl From<Refusal> for crate::error::ParseError {
67    fn from(r: Refusal) -> Self {
68        crate::error::ParseError {
69            kind: crate::error::ParseErrorKind::Custom(r.message),
70            span: r.at.unwrap_or_default(),
71        }
72    }
73}
74
75/// Map the AST speech-act category to the observation channel's category
76/// (Wave 13). The channel type is interner-free so sinks need no AST dependency.
77fn map_obs_cat(c: ObsCategory) -> crate::observe::ObsCat {
78    match c {
79        ObsCategory::Note => crate::observe::ObsCat::Note,
80        ObsCategory::Warn => crate::observe::ObsCat::Warn,
81        ObsCategory::Record => crate::observe::ObsCat::Record,
82    }
83}
84
85/// A loop-local fresh sequence which is transferred into a loop-carried
86/// sequence at the end of the iteration.  Lowering that transfer to a register
87/// exchange leaves the old outer buffer in `inner`; the next `NewEmptyList`
88/// can therefore clear and refill it instead of allocating again.
89#[derive(Clone, Copy)]
90struct LoopBufferSwap {
91    inner: Symbol,
92    outer: Symbol,
93    set_idx: usize,
94}
95
96fn unit_increment(stmt: &Stmt) -> bool {
97    let Stmt::Set { target, value } = stmt else {
98        return false;
99    };
100    matches!(
101        value,
102        Expr::BinaryOp {
103            op: BinaryOpKind::Add,
104            left,
105            right,
106        } if (matches!(left, Expr::Identifier(sym) if sym == target)
107            && matches!(right, Expr::Literal(Literal::Number(1))))
108            || (matches!(left, Expr::Literal(Literal::Number(1)))
109                && matches!(right, Expr::Identifier(sym) if sym == target))
110    )
111}
112
113/// Recognize the same conservative ping-pong shape as the Rust and C AST
114/// emitters.  This lives at bytecode lowering so VM, C-bytecode, and every JIT
115/// consuming the bytecode receive the optimization together.
116fn detect_loop_buffer_swap(body: &[Stmt], interner: &Interner) -> Option<LoopBufferSwap> {
117    if !crate::optimize::active_config().is_on(crate::optimization::Opt::Peephole) || body.len() < 2
118    {
119        return None;
120    }
121
122    let inner = body.iter().take(2).find_map(|stmt| {
123        let Stmt::Let {
124            var,
125            value:
126                Expr::New {
127                    type_name,
128                    init_fields,
129                    ..
130                },
131            mutable: true,
132            ..
133        } = stmt
134        else {
135            return None;
136        };
137        (matches!(interner.resolve(*type_name), "Seq" | "List" | "Vec") && init_fields.is_empty())
138            .then_some(*var)
139    })?;
140
141    let (outer, set_idx) = body.iter().enumerate().rev().find_map(|(idx, stmt)| {
142        let Stmt::Set {
143            target,
144            value: Expr::Identifier(source),
145        } = stmt
146        else {
147            return None;
148        };
149        (*source == inner && *target != inner).then_some((*target, idx))
150    })?;
151
152    if set_idx + 1 == body.len() {
153        // The ownership transfer is the final statement.
154    } else if set_idx + 2 == body.len() && unit_increment(&body[set_idx + 1]) {
155        // The only following statement advances the loop counter.
156    } else {
157        return None;
158    }
159
160    Some(LoopBufferSwap {
161        inner,
162        outer,
163        set_idx,
164    })
165}
166
167/// Whether the W24 constant-divisor magic-reciprocal lowering is enabled.
168/// Default ON (it is bit-identical to `Op::Div`/`Op::Mod` for the proven
169/// non-negative dividend it gates on, validated by the corpus differential).
170/// `LOGOS_MAGIC_DIV=0` is the kill-switch — also the A/B handle for measuring
171/// the lever's effect on a quiet box. Read once.
172pub fn magic_div_enabled() -> bool {
173    crate::optimize::active_config().is_on(crate::optimization::Opt::FastDiv)
174}
175
176/// Narrow a `new Seq of Int` whose elements provably fit `i32` into half-width
177/// (`Vec<i32>`) VM storage — the interpreter analogue of the AOT `Vec<i64>`→
178/// `Vec<i32>` narrowing, halving the array footprint and cache pressure. The JIT
179/// region path is i32-array aware (the hot region still tiers — 0 bails). PROMOTED
180/// 2026-06-21: default ON (kill-switch LOGOS_NARROW_VM=0) — graph_bfs -27.6% and
181/// array_fill -16.7% on the faithful interleaved A/B, all 33 benchmarks
182/// bit-identical, full suite 10341/10341 green, no regression.
183///
184/// Read fresh on each body-compile (not memoized) so a process can compile both
185/// regimes — the A/B differential harness and the in-process tests rely on this.
186/// The cost is one env lookup per function body, never per op.
187pub fn narrow_vm_enabled() -> bool {
188    crate::optimize::active_config().is_on(crate::optimization::Opt::NarrowVm)
189}
190
191/// Precompute the unsigned magic-reciprocal constants `(magic, more)` for a
192/// constant divisor `c` (`c != 0`), reusing the single canonical
193/// [`logicaffeine_data::LogosDivU64`] generator — the same algorithm the AOT
194/// `compile_to_rust` path emits, exhaustively proven against hardware `/`/`%`.
195/// The `more` byte encoding (low 6 bits = shift, `0x40` = the 65-bit add-marker
196/// path, `0x80` = the pure-shift power-of-two path) is exactly what
197/// [`magic_eval`] consumes.
198pub fn magic_u64_gen(c: u64) -> (u64, u8) {
199    logicaffeine_data::LogosDivU64::new(c).parts()
200}
201
202/// Evaluate the magic reciprocal: `x / c` when `mul_back == 0`, else `x % c`
203/// (`mul_back == c`). `x` is the dividend reinterpreted as `u64` — sound because
204/// the op is emitted ONLY for a proven non-negative `x`, where the i64 bit
205/// pattern equals the mathematical value and the unsigned quotient/remainder
206/// equal the signed truncating ones. The remainder is `x - q*c` computed in
207/// wrapping i64 (the low 64 bits agree with the u64 difference), bit-exact with
208/// the kernel's `wrapping_rem` for non-negative `x`.
209pub fn magic_eval(x: i64, magic: u64, more: u8, mul_back: i64) -> i64 {
210    const SHIFT_MASK: u8 = 0x3F;
211    const ADD_MARKER: u8 = 0x40;
212    const SHIFT_PATH: u8 = 0x80;
213    let n = x as u64;
214    let q = if more & SHIFT_PATH != 0 {
215        n >> (more & SHIFT_MASK)
216    } else {
217        let hi = (((magic as u128) * (n as u128)) >> 64) as u64;
218        if more & ADD_MARKER != 0 {
219            let t = (n.wrapping_sub(hi) >> 1).wrapping_add(hi);
220            t >> (more & SHIFT_MASK)
221        } else {
222            hi >> (more & SHIFT_MASK)
223        }
224    };
225    if mul_back == 0 {
226        q as i64
227    } else {
228        x.wrapping_sub((q as i64).wrapping_mul(mul_back))
229    }
230}
231
232/// Constant-pool dedup key. Floats are keyed by bit pattern so that distinct
233/// NaN payloads and -0.0/0.0 stay distinct pool entries.
234#[derive(Clone, PartialEq, Eq, Hash)]
235enum ConstKey {
236    Int(i64),
237    FloatBits(u64),
238    Bool(bool),
239    Text(String),
240    Char(char),
241    Nothing,
242    Duration(i64),
243    Date(i32),
244    Moment(i64),
245    Span { months: i32, days: i32 },
246    Time(i64),
247}
248
249fn const_key(c: &Constant) -> ConstKey {
250    match c {
251        Constant::Int(n) => ConstKey::Int(*n),
252        Constant::Float(f) => ConstKey::FloatBits(f.to_bits()),
253        Constant::Bool(b) => ConstKey::Bool(*b),
254        Constant::Text(s) => ConstKey::Text(s.clone()),
255        Constant::Char(c) => ConstKey::Char(*c),
256        Constant::Nothing => ConstKey::Nothing,
257        Constant::Duration(n) => ConstKey::Duration(*n),
258        Constant::Date(d) => ConstKey::Date(*d),
259        Constant::Moment(n) => ConstKey::Moment(*n),
260        Constant::Span { months, days } => ConstKey::Span {
261            months: *months,
262            days: *days,
263        },
264        Constant::Time(n) => ConstKey::Time(*n),
265    }
266}
267
268/// Which i64-slot kind a DECLARED scalar type compiles to, if any.
269fn slot_kind_of_type(
270    ty: &crate::ast::stmt::TypeExpr,
271    interner: &Interner,
272) -> Option<super::native_tier::SlotKind> {
273    use super::native_tier::SlotKind;
274    use crate::ast::stmt::TypeExpr;
275    match ty {
276        // Float reaches the AST as Named (the Primitive set is Int, Nat,
277        // Text, Bool) — accept the scalar names through either variant.
278        TypeExpr::Primitive(sym) | TypeExpr::Named(sym) => match interner.resolve(*sym) {
279            "Int" | "Nat" => Some(SlotKind::Int),
280            // DOM handles are nominal in the checker and i64 handles at runtime.
281            "Element" | "Event" | "View" => Some(SlotKind::Int),
282            "Float" => Some(SlotKind::Float),
283            "Bool" => Some(SlotKind::Bool),
284            // A `Word32` element type — a `Seq of Word32` param pins as a `Words32` buffer.
285            "Word32" => Some(SlotKind::Word32),
286            // A `Word64` rides as its bit pattern; a `Seq of Word64` has no packed list (see `param_kind_of_type`).
287            "Word64" => Some(SlotKind::Word64),
288            _ => None,
289        },
290        TypeExpr::Refinement { base, .. } => slot_kind_of_type(base, interner),
291        _ => None,
292    }
293}
294
295/// A DECLARED parameter's native representation: scalar slot or pinned
296/// `Seq of <scalar>`.
297fn param_kind_of_type(
298    ty: &crate::ast::stmt::TypeExpr,
299    interner: &Interner,
300) -> Option<super::native_tier::ParamKind> {
301    use super::native_tier::{ParamKind, PinElem, SlotKind};
302    use crate::ast::stmt::TypeExpr;
303    if let TypeExpr::Mutable { inner } = ty {
304        return param_kind_of_type(inner, interner);
305    }
306    if let Some(k) = slot_kind_of_type(ty, interner) {
307        return Some(ParamKind::Scalar(k));
308    }
309    if let TypeExpr::Generic { base, params } = ty {
310        if interner.resolve(*base) == "Seq" && params.len() == 1 {
311            return match slot_kind_of_type(&params[0], interner) {
312                Some(SlotKind::Int) => Some(ParamKind::List(PinElem::Int)),
313                Some(SlotKind::Float) => Some(ParamKind::List(PinElem::Float)),
314                Some(SlotKind::Bool) => Some(ParamKind::List(PinElem::Bool)),
315                // A `Seq of Word32` param pins as a `Words32` buffer (the sha256 `h`/`m`/`kk` schedule +
316                // constants) — reuses the IntList 8-byte pin, tags reads `Word32`. This lets a function
317                // taking Word32-list params (sha256Compress) tier instead of being marked `Failed`.
318                Some(SlotKind::Word32) => Some(ParamKind::List(PinElem::Word32)),
319                // `CharText` is a forge-only write-back carrier, never a declared element type.
320                Some(SlotKind::CharText) => None,
321                // A `Seq of Word64` has no packed list repr yet (no `Words64` `ListRepr`) — declines.
322                Some(SlotKind::Word64) => None,
323                None => None,
324            };
325        }
326    }
327    if let TypeExpr::Refinement { base, .. } = ty {
328        return param_kind_of_type(base, interner);
329    }
330    None
331}
332
333/// Resolve a type NAME to its full [`BoundaryType`] — a scalar/temporal primitive, or (if the name
334/// is a user type) a `Struct`/`Enum` reference (`user_types[name]` = true for struct, false for
335/// enum). `None` for an unmodeled type (Map, generic param…).
336fn boundary_of_name(
337    s: Symbol,
338    user_types: &std::collections::HashMap<Symbol, bool>,
339    interner: &Interner,
340) -> Option<BoundaryType> {
341    Some(match interner.resolve(s) {
342        "Int" | "Nat" | "Element" | "Event" | "View" => BoundaryType::Int,
343        "Float" | "Real" => BoundaryType::Float,
344        "Bool" => BoundaryType::Bool,
345        "Text" => BoundaryType::Text,
346        "Date" => BoundaryType::Date,
347        "Moment" => BoundaryType::Moment,
348        "Word32" => BoundaryType::Word32,
349        "Word64" => BoundaryType::Word64,
350        name @ ("Duration" | "Time" | "Span" | "Rational" | "Complex" | "Decimal" | "Modular"
351        | "Money" | "Quantity" | "Uuid" | "Algebraic" | "ExactReal" | "Hyperreal" | "Hypernatural"
352        | "Ordinal") => BoundaryType::Builtin(name.to_string()),
353        other => match user_types.get(&s) {
354            Some(true) => BoundaryType::Struct(other.to_string()),
355            Some(false) => BoundaryType::Enum(other.to_string()),
356            None => return None,
357        },
358    })
359}
360
361/// Resolve a parameter's AST [`TypeExpr`] to its [`BoundaryType`]. `None` for an unmodeled type.
362fn boundary_of_type_expr(
363    ty: &crate::ast::stmt::TypeExpr,
364    user_types: &std::collections::HashMap<Symbol, bool>,
365    interner: &Interner,
366) -> Option<BoundaryType> {
367    use crate::ast::stmt::TypeExpr;
368    match ty {
369        TypeExpr::Primitive(s) | TypeExpr::Named(s) => boundary_of_name(*s, user_types, interner),
370        TypeExpr::Generic { base, params }
371            if matches!(interner.resolve(*base), "Seq" | "List") && params.len() == 1 =>
372        {
373            boundary_of_type_expr(&params[0], user_types, interner)
374                .map(|e| BoundaryType::Seq(Box::new(e)))
375        }
376        // `Map of K to V` — resolve both the key and value element types (carried so a parameter
377        // map's `item k of m` resolves its result kind); rejected if either is unresolvable.
378        TypeExpr::Generic { base, params }
379            if matches!(interner.resolve(*base), "Map" | "HashMap") && params.len() == 2 =>
380        {
381            let k = boundary_of_type_expr(&params[0], user_types, interner)?;
382            let v = boundary_of_type_expr(&params[1], user_types, interner)?;
383            Some(BoundaryType::Map(Box::new(k), Box::new(v)))
384        }
385        // `Set of <elem>` — one i32 handle, resolved so a `Set of Int`/`Set of Text` PARAMETER seeds
386        // its self-describing kind (`Kind::Set`/`Kind::SetText`) and a `-> Set of …` RETURN threads it.
387        TypeExpr::Generic { base, params }
388            if matches!(interner.resolve(*base), "Set" | "HashSet") && params.len() == 1 =>
389        {
390            boundary_of_type_expr(&params[0], user_types, interner)
391                .map(|e| BoundaryType::Set(Box::new(e)))
392        }
393        // A HOMOGENEOUS tuple (`Pair of Int and Int`, `Triple of Int and Int and Int`) lays out
394        // identically to a `Seq` of the shared element kind, so it resolves through the same seq path
395        // (`item N of t` = seq index). A heterogeneous tuple has no single AOT element kind and stays
396        // rejected — exactly as a heterogeneous tuple LITERAL is rejected at lowering.
397        TypeExpr::Generic { base, params }
398            if matches!(interner.resolve(*base), "Pair" | "Triple") =>
399        {
400            let elems: Vec<BoundaryType> = params
401                .iter()
402                .filter_map(|p| boundary_of_type_expr(p, user_types, interner))
403                .collect();
404            if elems.len() != params.len() {
405                None
406            } else if elems.windows(2).all(|w| w[0] == w[1]) {
407                Some(BoundaryType::Seq(Box::new(elems[0].clone())))
408            } else {
409                Some(BoundaryType::Tuple(elems))
410            }
411        }
412        // An ANONYMOUS tuple type `(Int, Int)` / `(Int, Text)` — identical resolution to `Pair`/`Triple`:
413        // a homogeneous tuple lays out as a `Seq` of the shared element (so `item N of t` = seq index),
414        // a heterogeneous one is a `Tuple` of per-position kinds.
415        TypeExpr::Tuple(params) => {
416            let elems: Vec<BoundaryType> = params
417                .iter()
418                .filter_map(|p| boundary_of_type_expr(p, user_types, interner))
419                .collect();
420            if elems.len() != params.len() {
421                None
422            } else if elems.windows(2).all(|w| w[0] == w[1]) {
423                Some(BoundaryType::Seq(Box::new(elems[0].clone())))
424            } else {
425                Some(BoundaryType::Tuple(elems))
426            }
427        }
428        // `Result of <ok> and <err>` — an enum written at its use site, never declared, so its
429        // payload types are carried structurally rather than looked up by name. This is what lets
430        // a `When Err (e)` read a field of a RECORD payload: the arm resolves its layout from the
431        // declared type, exactly as a named enum's arm resolves it from `enum_types`.
432        // ★ AN `Option of <inner>` RESOLVES THE SAME WAY, and used to fall to `_ => None` below —
433        // so a declared `-> Option of Int` told the backends nothing, and a `When Some (v):` arm
434        // had no type for `v`. `Maybe` is the documented alias (`registry.rs` gives both arity 1).
435        TypeExpr::Generic { base, params }
436            if matches!(interner.resolve(*base), "Option" | "Maybe") && params.len() == 1 =>
437        {
438            let inner = boundary_of_type_expr(&params[0], user_types, interner)?;
439            Some(BoundaryType::Option(Box::new(inner)))
440        }
441        TypeExpr::Generic { base, params }
442            if interner.resolve(*base) == "Result" && params.len() == 2 =>
443        {
444            let ok = boundary_of_type_expr(&params[0], user_types, interner)?;
445            let err = boundary_of_type_expr(&params[1], user_types, interner)?;
446            Some(BoundaryType::Result(Box::new(ok), Box::new(err)))
447        }
448        TypeExpr::Refinement { base, .. } => boundary_of_type_expr(base, user_types, interner),
449        TypeExpr::Mutable { inner } => boundary_of_type_expr(inner, user_types, interner),
450        _ => None,
451    }
452}
453
454/// Resolve a struct FIELD's registry [`FieldType`] to its [`BoundaryType`] (the registry, unlike the
455/// lossy `struct_defs` map, preserves a `Seq of <elem>` element).
456fn boundary_of_field_type(
457    ft: &crate::analysis::registry::FieldType,
458    user_types: &std::collections::HashMap<Symbol, bool>,
459    interner: &Interner,
460) -> Option<BoundaryType> {
461    use crate::analysis::registry::FieldType;
462    match ft {
463        // A single-replica counter CRDT field (`ConvergentCount`/`GCounter`/`Tally`/`PNCounter`) lays out as
464        // its underlying Int (the net count), exactly as a `SharedMap` field resolves as its `Map`. This lets a
465        // `Shared` struct carrying a counter resolve its field layout (the CRDT machinery bumps/reads that int
466        // slot in place), so the struct is a valid heap-plane type — the whole-program fabric resolves the field.
467        FieldType::Named(s)
468            if matches!(
469                interner.resolve(*s),
470                "ConvergentCount" | "GCounter" | "Tally" | "PNCounter"
471            ) =>
472        {
473            Some(BoundaryType::Int)
474        }
475        // A single-replica set / sequence CRDT field (`SharedSet of T` / `SharedSequence of T` and their
476        // variants) lays out as its underlying `Seq of T` (the live converged collection), exactly as a
477        // counter field resolves as its Int and a `SharedMap` as its `Map`.
478        FieldType::Generic { base, params }
479            if matches!(
480                interner.resolve(*base),
481                "SharedSet"
482                    | "ORSet"
483                    | "SharedSet_AddWins"
484                    | "SharedSet_RemoveWins"
485                    | "SharedSequence"
486                    | "RGA"
487                    | "SharedSequence_YATA"
488                    | "CollaborativeSequence"
489            ) && params.len() == 1 =>
490        {
491            boundary_of_field_type(&params[0], user_types, interner)
492                .map(|e| BoundaryType::Seq(Box::new(e)))
493        }
494        // A multi-value register CRDT field (`Divergent T`) lays out as its underlying value type T: a
495        // single-replica LWW resolve keeps the last value written, so the field is that value's slot
496        // (exactly as a counter field resolves as its Int). This lets a `Shared` struct with a register
497        // field resolve its layout instead of being silently dropped.
498        FieldType::Generic { base, params }
499            if interner.resolve(*base) == "Divergent" && params.len() == 1 =>
500        {
501            boundary_of_field_type(&params[0], user_types, interner)
502        }
503        FieldType::Primitive(s) | FieldType::Named(s) => boundary_of_name(*s, user_types, interner),
504        FieldType::Generic { base, params }
505            if matches!(interner.resolve(*base), "Seq" | "List") && params.len() == 1 =>
506        {
507            boundary_of_field_type(&params[0], user_types, interner)
508                .map(|e| BoundaryType::Seq(Box::new(e)))
509        }
510        // A `Set of T` field — the same `Set` boundary a `Set of T` parameter resolves to, so a record
511        // carrying a set declares what its set holds for the record's whole life.
512        FieldType::Generic { base, params }
513            if matches!(interner.resolve(*base), "Set" | "HashSet") && params.len() == 1 =>
514        {
515            boundary_of_field_type(&params[0], user_types, interner)
516                .map(|e| BoundaryType::Set(Box::new(e)))
517        }
518        // A `Map of K to V` field — resolve both element types, so a struct carrying a map can be a
519        // parameter and `item k of s's m` resolves the value kind cross-region. A `SharedMap from K to V`
520        // (single-replica ORMap CRDT) lays out as its underlying Map, so it resolves the same way.
521        FieldType::Generic { base, params }
522            if matches!(interner.resolve(*base), "Map" | "HashMap" | "SharedMap")
523                && params.len() == 2 =>
524        {
525            let k = boundary_of_field_type(&params[0], user_types, interner)?;
526            let v = boundary_of_field_type(&params[1], user_types, interner)?;
527            Some(BoundaryType::Map(Box::new(k), Box::new(v)))
528        }
529        // A HOMOGENEOUS tuple field (`Pair of Int and Int`, `Triple of …`) lays out identically to a
530        // `Seq` of the shared element kind, so it resolves through the seq path (`item N of s's t` =
531        // seq index). A heterogeneous tuple field has no single AOT element kind and stays rejected.
532        FieldType::Generic { base, params }
533            if matches!(interner.resolve(*base), "Pair" | "Triple") =>
534        {
535            let elems: Vec<BoundaryType> = params
536                .iter()
537                .filter_map(|p| boundary_of_field_type(p, user_types, interner))
538                .collect();
539            if elems.len() != params.len() {
540                None
541            } else if elems.windows(2).all(|w| w[0] == w[1]) {
542                Some(BoundaryType::Seq(Box::new(elems[0].clone())))
543            } else {
544                Some(BoundaryType::Tuple(elems))
545            }
546        }
547        // A `Result of <ok> and <err>` FIELD — the third boundary position, resolved structurally
548        // like the parameter one (see `boundary_of_type_expr`), so a record carrying an answer can
549        // be a parameter and `Inspect s's answer` reads a record payload's field cross-region.
550        // An `Option of <inner>` FIELD — the same third boundary position a `Result` field holds.
551        FieldType::Generic { base, params }
552            if matches!(interner.resolve(*base), "Option" | "Maybe") && params.len() == 1 =>
553        {
554            let inner = boundary_of_field_type(&params[0], user_types, interner)?;
555            Some(BoundaryType::Option(Box::new(inner)))
556        }
557        FieldType::Generic { base, params }
558            if interner.resolve(*base) == "Result" && params.len() == 2 =>
559        {
560            let ok = boundary_of_field_type(&params[0], user_types, interner)?;
561            let err = boundary_of_field_type(&params[1], user_types, interner)?;
562            Some(BoundaryType::Result(Box::new(ok), Box::new(err)))
563        }
564        // A tuple FIELD rides the boundary exactly as a `Pair`/`Triple` field does: a homogeneous
565        // one as a `Seq` of its element, a heterogeneous one as a `Tuple`.
566        FieldType::Tuple(_) | FieldType::Record(_) => {
567            let items: Vec<&FieldType> = match ft {
568                FieldType::Tuple(items) => items.iter().collect(),
569                FieldType::Record(fields) => fields.iter().map(|(_, t)| t).collect(),
570                _ => unreachable!("matched a tuple form"),
571            };
572            let elems: Vec<BoundaryType> = items
573                .iter()
574                .filter_map(|p| boundary_of_field_type(p, user_types, interner))
575                .collect();
576            if elems.len() != items.len() || elems.is_empty() {
577                None
578            } else if elems.windows(2).all(|w| w[0] == w[1]) {
579                Some(BoundaryType::Seq(Box::new(elems[0].clone())))
580            } else {
581                Some(BoundaryType::Tuple(elems))
582            }
583        }
584        FieldType::TypeParam(_) | FieldType::Generic { .. } => None,
585    }
586}
587
588/// Resolve the static [`BoundaryType`] of a `Let`-binding's VALUE expression — for a Main top-level
589/// binding promoted to a global, so a closure capturing it can be typed with the composite's shape
590/// (the capture analog of a parameter's declared type). Handles the constructor forms whose type is
591/// statically evident (`new Struct`, `new Map of K to V`, `a new EnumVariant`), and a call to one of
592/// the program's functions by `calls`, its declared return type; `None` otherwise (the global stays
593/// Kind-only — fine for self-describing values like a `Seq` and for scalars).
594fn boundary_of_value_expr(
595    e: &crate::ast::stmt::Expr,
596    user_types: &std::collections::HashMap<Symbol, bool>,
597    interner: &Interner,
598    calls: &dyn Fn(Symbol) -> Option<BoundaryType>,
599) -> Option<BoundaryType> {
600    use crate::ast::stmt::{Expr, Literal};
601    match e {
602        Expr::New {
603            type_name,
604            type_args,
605            ..
606        } => {
607            if matches!(interner.resolve(*type_name), "Map" | "HashMap") && type_args.len() == 2 {
608                let k = boundary_of_type_expr(&type_args[0], user_types, interner)?;
609                let v = boundary_of_type_expr(&type_args[1], user_types, interner)?;
610                Some(BoundaryType::Map(Box::new(k), Box::new(v)))
611            } else if matches!(interner.resolve(*type_name), "Set" | "HashSet")
612                && type_args.len() == 1
613            {
614                let elem = boundary_of_type_expr(&type_args[0], user_types, interner)?;
615                Some(BoundaryType::Set(Box::new(elem)))
616            } else if matches!(interner.resolve(*type_name), "Seq" | "List") && type_args.len() == 1
617            {
618                // ★ `a new Seq of Todo` SAYS WHAT IT HOLDS, and a global that says so is how a
619                // reader of it resolves a field of a row. Without this the type was `None`, and a
620                // function looping the global had no element layout to resolve against — so a
621                // page whose `State:` holds a list of records could not read one field of one row.
622                let elem = boundary_of_type_expr(&type_args[0], user_types, interner)?;
623                Some(BoundaryType::Seq(Box::new(elem)))
624            } else {
625                boundary_of_name(*type_name, user_types, interner)
626            }
627        }
628        // ★ A NON-EMPTY MAP LITERAL says it through its first ENTRY — the same rule as the list
629        // literal below, one collection along. `{k: v, …}` lowers to the variadic `mapOf` builtin,
630        // so that call is what a global actually holds, and without this arm a program writing
631        // `Let m be {"a": 1}.` gave the backend a map of unknown value kind — the exact refusal
632        // `wasm_map_global_lock` exists for, arriving by the other construction route.
633        Expr::Call { function, args }
634            if interner.resolve(*function) == "mapOf" && args.len() >= 2 =>
635        {
636            let k = boundary_of_value_expr(args[0], user_types, interner, calls)?;
637            let v = boundary_of_value_expr(args[1], user_types, interner, calls)?;
638            Some(BoundaryType::Map(Box::new(k), Box::new(v)))
639        }
640        // A call says it through the function's declared return type — at any depth, so a
641        // component's per-instance state seeded by a template (`mapOf("", badge("a"))`, a map of
642        // the program's `__View` enum) is as typed as one seeded by a literal.
643        Expr::Call { function, .. } => calls(*function),
644        // A non-empty list LITERAL says it through its first element — the other way a program
645        // writes a list of records down.
646        Expr::List(items) => {
647            let first = items.first()?;
648            let elem = boundary_of_value_expr(first, user_types, interner, calls)?;
649            Some(BoundaryType::Seq(Box::new(elem)))
650        }
651        Expr::NewVariant { enum_name, .. } => boundary_of_name(*enum_name, user_types, interner),
652        // A scalar literal — also resolves a tuple-literal's elements (below).
653        Expr::Literal(Literal::Number(_)) => Some(BoundaryType::Int),
654        Expr::Literal(Literal::Float(_)) => Some(BoundaryType::Float),
655        Expr::Literal(Literal::Boolean(_)) => Some(BoundaryType::Bool),
656        Expr::Literal(Literal::Text(_)) => Some(BoundaryType::Text),
657        // A tuple literal — every element's type must resolve. A homogeneous tuple lays out like a
658        // `Seq` (self-describing, no shape needed); a heterogeneous one carries its per-position kinds.
659        Expr::Tuple(elems) if !elems.is_empty() => {
660            let bts: Vec<BoundaryType> = elems
661                .iter()
662                .filter_map(|el| boundary_of_value_expr(el, user_types, interner, calls))
663                .collect();
664            if bts.len() != elems.len() {
665                None
666            } else if bts.windows(2).all(|w| w[0] == w[1]) {
667                Some(BoundaryType::Seq(Box::new(bts[0].clone())))
668            } else {
669                Some(BoundaryType::Tuple(bts))
670            }
671        }
672        _ => None,
673    }
674}
675
676pub struct Compiler<'i> {
677    interner: &'i Interner,
678    code: Vec<Op>,
679    constants: Vec<Constant>,
680    const_map: HashMap<ConstKey, ConstIdx>,
681    functions: Vec<CompiledFunction>,
682    fn_index: HashMap<Symbol, FuncIdx>,
683    /// The refusal a `Mount` of each LGX component raises, by component — the cause `lowerable`
684    /// found, worded and located, computed once from the statement list ([`mount_refusals`]).
685    mount_refusals: HashMap<Symbol, Refusal>,
686    /// The refusal each `## Route` this program cannot lower raises, keyed by `(method, path)`.
687    ///
688    /// Computed once from the WHOLE program, because a `-> View` route's lowerability depends on
689    /// the components beside it; the statement arm has no program in hand.
690    route_refusals: HashMap<(Symbol, Symbol), Refusal>,
691    // Struct definitions: field (name, declared-type, is_public) per struct —
692    // from `Stmt::StructDef` and the discovery-pass type registry. Drives
693    // default-fill on construction, like the tree-walker's struct_defs.
694    struct_defs: HashMap<Symbol, Vec<(Symbol, Symbol, bool)>>,
695    // Every enum's own constructor list, in declaration order, from the discovery-pass type
696    // registry — G5's "no arm matched" fallthrough reads this to test each UNCOVERED constructor
697    // against a compile-time-known message, needing no runtime tag extraction at all (`compile_
698    // inspect`). `HashMap::new()` (never populated) when no type registry was given (`Compiler::
699    // compile`'s plain entry) — `compile_inspect` falls back to a dynamic message then.
700    enum_variants: HashMap<Symbol, Vec<Symbol>>,
701    // The reverse index: a constructor's name → the enum it belongs to. Built alongside
702    // `enum_variants` from the same registry pass.
703    variant_enum: HashMap<Symbol, Symbol>,
704    // A constructor's DECLARED field names, in declaration order — mirrors `struct_defs` for
705    // enum variants — keyed by `(enum name, constructor name)`. `Expr::NewVariant` compiles its
706    // `with`-clause fields in WRITE order but must seat each value at its DECLARED position
707    // (`Op::NewInductive`'s `args` are read back positionally by `execute_inspect`'s
708    // binding-by-index, so declared order is the only order that keeps a bind arm correct when a
709    // constructor lists its fields out of order). Also drives default-fill for a field the `with`
710    // clause omits, like `struct_defs` does for structs. Keyed by the constructor alone until this
711    // session: two enums declaring a same-named variant with DIFFERENT field shapes (`a new
712    // Failure from Outcome`/`a new Failure from Status`, constructible together for the first time
713    // by lang5's `from`-qualification) collided on one shared entry, whichever registered second in
714    // the discovery pass's own `HashMap` iteration order silently winning.
715    variant_fields: HashMap<(Symbol, Symbol), Vec<Symbol>>,
716    // Every user type's name → is-it-a-struct (true) / enum (false), built once before statement
717    // compilation. Lets a CLOSURE resolve a struct/enum PARAMETER's declared type (the closure path
718    // has no other access to the type registry the top-level function path uses).
719    user_types: HashMap<Symbol, bool>,
720    // Lexical block scopes for the frame currently being compiled (Main or one
721    // function body). scopes[0] is the frame root; If/While/Repeat bodies push
722    // a child scope whose registers are recycled on exit — mirroring the
723    // tree-walker's execute_block undo-scope.
724    scopes: Vec<HashMap<Symbol, Reg>>,
725    next_reg: Reg,
726    /// DEBUG-ONLY: when set (the debugger's compile path), capture source variable
727    /// names so the debug drawer can show `x` rather than `R0`. Off in production.
728    debug_names: bool,
729    /// When FALSE, division/modulo by a constant is NOT strength-reduced to
730    /// `DivPow2`/`MagicDivU`/`BitAnd` — plain `Div`/`Mod` are emitted instead.
731    /// The soft-core chip backend sets this off: it has a real sequential
732    /// `shared_divider`, so magic-reciprocal division (a 64-bit magic constant
733    /// that cannot ride the 32-bit chip instruction word) is neither needed nor
734    /// representable. Correctness is identical — strength reduction is exact — so
735    /// the VM and the chip agree on every result. Default TRUE everywhere else.
736    strength_reduce: bool,
737    /// DEBUG-ONLY: (register, name-symbol) bound in the CURRENT frame; cleared per
738    /// frame in `begin_scope`, resolved into `CompiledProgram::reg_names` for Main.
739    dbg_names: Vec<(Reg, Symbol)>,
740    /// OBSERVED profile (Wave 13): when set, `Note`/`Warn`/`Record`/`During` lower
741    /// to `Op::Obs` + entries in `observation_sites`. Off in the elided
742    /// (compiled/release) profile, where observation is erased — so ordinary
743    /// programs and every AOT/WASM compile are byte-unchanged.
744    emit_observation: bool,
745    /// The observation sites accumulated while compiling in the OBSERVED profile,
746    /// handed to `CompiledProgram::observation_sites`.
747    observation_sites: Vec<ObsSiteDesc>,
748    /// `(pc, site_id)` pairs accumulated while compiling, handed to `CompiledProgram::site_at` —
749    /// see that field's own doc comment (Wave 3: "runtime failures carry a location").
750    site_at: Vec<(u32, u32)>,
751    /// TIERS-CHECK mode (`largo test --tiers all`, Wave 13): compile a `## Test`
752    /// body's test-only statements (`Expect`/`ForAll`/…) as NO-OPS so the VM can
753    /// run the test's COMPUTATION and its agreement with the tree-walker can be
754    /// checked (the assertions themselves stay the interpreter's authoritative
755    /// verdict). Off everywhere else — a test statement outside the runner is an
756    /// error, as before.
757    test_noop: bool,
758    /// Registers bound to a NAME (Let targets, params, loop variables,
759    /// captures) in any frame compiled so far. Everything else is a
760    /// statement-local scratch — dead at every statement boundary by the
761    /// allocator's recycling discipline. Snapshotted for Main into
762    /// `CompiledProgram::named_regs`, where the region JIT uses it to skip
763    /// write-back (and pre-state preservation) for scratch slots.
764    named: Vec<bool>,
765    /// Loop heads (back-edge target pcs) currently being compiled, outermost
766    /// first. Every `mark_named` while this is non-empty records the register as
767    /// a LOOP-LOCAL of each enclosing loop — bound inside a loop body, so it is
768    /// lexically dead the instant the loop exits (the scope is popped).
769    loop_stack: Vec<usize>,
770    /// `loop_locals[head]` = the registers bound inside the loop whose region
771    /// head is `head` (absolute pc). The region JIT subtracts these from the
772    /// write-back set: a slot dead at the loop exit must not be written back,
773    /// which is what lets copy-prop/CSE/fusion treat it as true scratch. Keyed
774    /// by absolute pc (Main and every function share one code array), valued by
775    /// the OWNING frame's register indices.
776    loop_locals: std::collections::HashMap<usize, Vec<bool>>,
777    /// High-water mark of `next_reg` for the current frame — block scopes
778    /// recycle registers, so the frame's true size is the maximum ever
779    /// reached, not the final `next_reg`.
780    max_reg: Reg,
781    expr_depth: usize,
782    // Enclosing control-flow contexts (innermost last). Loops collect Break
783    // jumps; Zones (and Concurrent/Parallel tasks) SWALLOW Break/Return — the
784    // tree-walker's execute path discards their ControlFlow.
785    flow_stack: Vec<FlowCtx>,
786    // Whether we are compiling a function body (false ⇒ Main, where a
787    // top-level Break/Return halts the program).
788    in_function: bool,
789    /// The return type of the function currently being compiled — so a `Return (a, b)` in a
790    /// NAMED-RECORD-returning function builds a self-describing struct (`RuntimeValue::Struct` with the
791    /// record's field names) rather than a bare tuple, mirroring the interpreter's `coerce_record_return`.
792    current_return_type: Option<&'i crate::ast::stmt::TypeExpr<'i>>,
793    /// Self-tail-call optimization context for the function currently being
794    /// compiled: `(name, entry_pc, param_count)`. A self-call in TAIL position
795    /// (`Return f(args)`, or a `Set/Let x = f(args)` immediately followed by
796    /// `Return x`) is lowered to "reassign params 0..param_count, jump to
797    /// entry_pc" instead of Call+Return — turning self-tail-recursion into a
798    /// loop (constant stack, no per-call frame round-trip). `None` outside any
799    /// function and for non-self / non-arity-matching calls.
800    tail_fn: Option<(Symbol, usize, u16)>,
801    // Promoted globals: Main TOP-LEVEL Let names referenced from function or
802    // closure bodies, with their slot in the runtime globals table.
803    promoted: HashMap<Symbol, u16>,
804    // When compiling a closure body: per promoted capture, its (value, flag)
805    // frame registers — a captured-global access reads the snapshot when the
806    // flag is set and the LIVE global otherwise (tree-walker fall-through).
807    closure_ctx: Option<HashMap<Symbol, (Reg, Reg)>>,
808    /// Oracle range-analysis facts (M9) for the program being compiled.
809    /// Present only on the live run path; when set, an `Index` whose
810    /// `index_provably_in_bounds` holds is emitted as `IndexUnchecked`
811    /// (bounds-check elimination, V8/LLVM-style). Keyed on the AST `Expr`
812    /// pointers of THESE stmts, so the facts must be analyzed on the exact
813    /// snapshot being compiled.
814    oracle: Option<crate::optimize::OracleFacts>,
815    /// Per-enclosing-loop sets of arrays whose region-entry `RegionBoundsGuard`
816    /// was successfully emitted. A speculative access elides ONLY when its
817    /// array is in some enclosing frame — the compiler's half of the
818    /// elision ⟺ guard ⟺ VM-check invariant.
819    hoist_enabled: Vec<std::collections::HashSet<Symbol>>,
820    /// `new Seq of Int` declarations in the body CURRENTLY being compiled whose
821    /// every element provably fits `i32` (the `codegen::narrow` proof). Their
822    /// empty-constructor lowers to [`Op::NewEmptyListI32`] (half-width storage),
823    /// observably identical to the i64 form. Populated per-body only when
824    /// `LOGOS_NARROW_VM=1`; empty otherwise (default OFF).
825    narrowable_seqs: std::collections::HashSet<Symbol>,
826    /// Exact capacities for non-escaping fixed `Seq` locals, produced by the
827    /// same proof Rust and syntax-tree C consume. A proven declaration lowers
828    /// to `NewEmptyListFixed`, making support explicit to every bytecode tier.
829    fixed_seq_caps: HashMap<(Option<Symbol>, Symbol), usize>,
830    /// What the program declares values to be, by the absolute pc of the defining op
831    /// ([`CompiledProgram::declared_types`]); sorted when the program is finalized.
832    declared_types: Vec<(u32, BoundaryType)>,
833    /// Inferred MUTABLE-BORROW params per function: `fn → set of param indices` that
834    /// are mutated in place and returned (the AOT's `&mut [T]` set, computed by the
835    /// SAME eligibility). Their frame registers are copy-on-write-exempt so the
836    /// callee's element writes stay in place; each call site gets an `EnsureOwned`
837    /// barrier so an aliasing caller still observes value semantics. Only populated
838    /// when the type registry is available (`compile_with_types`).
839    mut_borrow_params: HashMap<Symbol, std::collections::HashSet<usize>>,
840    /// Per function, the positions of its parameters declared `mutable`: IN-OUT. A call passing a
841    /// binding there isolates the binding's value first (so the callee's writes reach no copy of
842    /// it) and takes the parameter's final value back into the binding when the call returns (so
843    /// every write the callee made — a field, a whole replacement — is the caller's).
844    inout_params: HashMap<Symbol, Vec<usize>>,
845    /// Functions declared `## To native` (EMPTY bodies), each with the Rust path it names: calls to
846    /// the known system natives among them compile to the shared seams instead of the empty body,
847    /// and a call no seam takes is refused by name. Membership is the declarer-wins guard — a user
848    /// function with a real body is never in this map, so it compiles as an ordinary call.
849    native_fns: HashMap<Symbol, Option<Symbol>>,
850    /// Per function, the consume-alias LOCAL of each mutable-borrow param (`Let
851    /// result be arr`): its register must ALSO be COW-exempt (the in-place writes
852    /// land on the alias, not the param). Recorded during body compile.
853    mut_borrow_alias_syms: HashMap<Symbol, std::collections::HashSet<Symbol>>,
854    /// The alias symbols of the function CURRENTLY being compiled (from
855    /// `mut_borrow_alias_syms`); a `let_reg` for one of these appends its register to
856    /// `current_exempt_regs`.
857    current_exempt_syms: std::collections::HashSet<Symbol>,
858    /// Registers bound to `current_exempt_syms` in the current function body — merged
859    /// into `CompiledFunction::mutable_param_regs` after the body compiles.
860    current_exempt_regs: Vec<Reg>,
861    /// Nesting depth of the enclosing `Reversibly:` / `Uncompute:` block. When positive, an
862    /// IN-PLACE ABELIAN scalar update (`Set x to x + e` / `x - e` / `x xor e` / `-x`, where `x`
863    /// is a local and `e` provably never observes `x`) lowers to the zero-garbage reversible ISA
864    /// (`Op::RevAdd`/`RevSub`/`RevXor`/`RevNeg`) instead of the plain journaling op — the region
865    /// then reverses with NO history tape. Everything else lowers identically to outside the block,
866    /// so program OUTPUT is unchanged; only the emitted ops differ. A counter (not a bool) so a
867    /// nested block leaves the outer mode intact on exit.
868    reversible_depth: usize,
869}
870
871/// Which reversible additive/XOR op a recognized `Set x to x ⊕ e` form lowers to inside a
872/// `Reversibly:` block — the delta-carrying members of the zero-garbage abelian core.
873enum RevOp {
874    Add,
875    Sub,
876    Xor,
877}
878
879/// A mutable argument's place, with every index already evaluated.
880struct LentPlace {
881    root: Symbol,
882    steps: Vec<LentStep>,
883}
884
885enum LentStep {
886    Field(u32),
887    Item(Reg),
888}
889
890/// How a name resolves at a point in compilation.
891enum NameRef {
892    Local(Reg),
893    /// A closure capture whose name is also a promoted global: snapshot when
894    /// present, live global otherwise.
895    CaptureOrGlobal {
896        value: Reg,
897        flag: Reg,
898        global: u16,
899    },
900    Global(u16),
901    Unbound,
902}
903
904enum FlowCtx {
905    Loop {
906        breaks: Vec<usize>,
907        /// Repeat loops own a live iterator that must be IterPop'd when a
908        /// Return jumps out across them into a Zone.
909        is_repeat: bool,
910    },
911    Zone {
912        exits: Vec<usize>,
913    },
914}
915
916impl<'i> Compiler<'i> {
917    /// Compile a statement block to a runnable program.
918    pub fn compile(stmts: &[Stmt], interner: &'i Interner) -> Result<CompiledProgram, String> {
919        Self::compile_with_types(stmts, interner, None)
920    }
921
922    /// Compile with the discovery-pass type registry (struct definitions that
923    /// never appear as `Stmt::StructDef`).
924    pub fn compile_with_types(
925        stmts: &[Stmt],
926        interner: &'i Interner,
927        types: Option<&crate::analysis::TypeRegistry>,
928    ) -> Result<CompiledProgram, String> {
929        Self::compile_with_oracle(stmts, interner, types, None)
930    }
931
932    /// Like `compile_with_types`, plus the Oracle's range-analysis facts
933    /// (M9) for bounds-check elimination. The live run path computes these
934    /// on the exact (optimized) snapshot it then compiles, so an `Index`
935    /// proven in-bounds becomes `IndexUnchecked`. `None` ⇒ every index
936    /// stays checked (the codegen / test paths).
937    pub fn compile_with_oracle(
938        stmts: &[Stmt],
939        interner: &'i Interner,
940        types: Option<&crate::analysis::TypeRegistry>,
941        oracle: Option<crate::optimize::OracleFacts>,
942    ) -> Result<CompiledProgram, String> {
943        Self::compile_with_oracle_located(stmts, interner, types, oracle)
944            .map_err(Refusal::into_message)
945    }
946
947    /// [`Self::compile_with_oracle`], keeping WHERE a refusal happened — the entry a surface that
948    /// points at the author's source (the browser build, its dev overlay, an editor) compiles
949    /// through. The text-only entries are this, with the location dropped.
950    pub fn compile_with_oracle_located(
951        stmts: &[Stmt],
952        interner: &'i Interner,
953        types: Option<&crate::analysis::TypeRegistry>,
954        oracle: Option<crate::optimize::OracleFacts>,
955    ) -> Result<CompiledProgram, Refusal> {
956        Self::compile_inner(stmts, interner, types, oracle, false, false, false, true)
957    }
958
959    /// Compile for the soft-core CHIP backend: identical to `compile_with_oracle` except division /
960    /// modulo by a constant is NOT strength-reduced (no `DivPow2`/`MagicDivU` — the chip issues plain
961    /// `Div`/`Mod` to its sequential `shared_divider`, and a 64-bit magic constant cannot ride the
962    /// 32-bit chip instruction word). Results are bit-identical to `compile_with_oracle` (strength
963    /// reduction is exact), so the VM and the chip agree.
964    pub fn compile_for_chip(
965        stmts: &[Stmt],
966        interner: &'i Interner,
967        types: Option<&crate::analysis::TypeRegistry>,
968        oracle: Option<crate::optimize::OracleFacts>,
969    ) -> Result<CompiledProgram, String> {
970        Self::compile_inner(stmts, interner, types, oracle, false, false, false, false)
971            .map_err(Refusal::into_message)
972    }
973
974    /// Like `compile_with_types` but also captures source variable names into
975    /// `CompiledProgram::reg_names` for the Studio debugger. Used only by the
976    /// debugger's compile path; production callers pay nothing for it.
977    pub fn compile_for_debug(
978        stmts: &[Stmt],
979        interner: &'i Interner,
980        types: Option<&crate::analysis::TypeRegistry>,
981    ) -> Result<CompiledProgram, String> {
982        Self::compile_inner(stmts, interner, types, None, true, false, false, true)
983            .map_err(Refusal::into_message)
984    }
985
986    /// Compile in the OBSERVED profile (Wave 13): `Note`/`Warn`/`Record`/`During`
987    /// lower to `Op::Obs`, so the VM emits the same observation event stream the
988    /// tree-walker does. The dev/test tier — the compiled/release tiers keep the
989    /// elided profile (this op never reaches them).
990    pub fn compile_observed(
991        stmts: &[Stmt],
992        interner: &'i Interner,
993        types: Option<&crate::analysis::TypeRegistry>,
994    ) -> Result<CompiledProgram, String> {
995        Self::compile_observed_located(stmts, interner, types).map_err(Refusal::into_message)
996    }
997
998    /// [`Self::compile_observed`], keeping where a refusal happened.
999    pub fn compile_observed_located(
1000        stmts: &[Stmt],
1001        interner: &'i Interner,
1002        types: Option<&crate::analysis::TypeRegistry>,
1003    ) -> Result<CompiledProgram, Refusal> {
1004        Self::compile_inner(stmts, interner, types, None, false, true, false, true)
1005    }
1006
1007    /// Compile a `## Test` body for the `--tiers all` differential (Wave 13):
1008    /// test-only statements (`Expect`/`ForAll`/…) compile as NO-OPS so the VM can
1009    /// run the test's computation and confirm it agrees with the tree-walker.
1010    pub fn compile_tiers(
1011        stmts: &[Stmt],
1012        interner: &'i Interner,
1013        types: Option<&crate::analysis::TypeRegistry>,
1014    ) -> Result<CompiledProgram, String> {
1015        Self::compile_inner(stmts, interner, types, None, false, false, true, true)
1016            .map_err(Refusal::into_message)
1017    }
1018
1019    #[allow(clippy::too_many_arguments)]
1020    fn compile_inner(
1021        stmts: &[Stmt],
1022        interner: &'i Interner,
1023        types: Option<&crate::analysis::TypeRegistry>,
1024        oracle: Option<crate::optimize::OracleFacts>,
1025        debug_names: bool,
1026        emit_observation: bool,
1027        test_noop: bool,
1028        strength_reduce: bool,
1029    ) -> Result<CompiledProgram, Refusal> {
1030        // Public callers may supply an AST without passing through the parser's depth gate.
1031        // Bound it iteratively before any recursive analysis visits it.
1032        if logicaffeine_language::ast_depth::program_depth(stmts)
1033            > logicaffeine_language::ast_depth::max_ast_depth()
1034        {
1035            return Err("vm: expression too deeply nested".to_string().into());
1036        }
1037        // How each `Repeat` may iterate: the shared optimizer's proofs, on exactly what this compile lowers.
1038        crate::optimize::iteration::prove_iteration_facts(stmts, interner);
1039        let mut c = Compiler {
1040            interner,
1041            debug_names,
1042            strength_reduce,
1043            dbg_names: Vec::new(),
1044            emit_observation,
1045            observation_sites: Vec::new(),
1046            site_at: vec![(0, crate::vm::instruction::NO_SITE)],
1047            test_noop,
1048            code: Vec::new(),
1049            constants: Vec::new(),
1050            const_map: HashMap::new(),
1051            functions: Vec::new(),
1052            fn_index: HashMap::new(),
1053            mount_refusals: HashMap::new(),
1054            route_refusals: HashMap::new(),
1055            struct_defs: HashMap::new(),
1056            enum_variants: HashMap::new(),
1057            variant_enum: HashMap::new(),
1058            variant_fields: HashMap::new(),
1059            user_types: HashMap::new(),
1060            scopes: vec![HashMap::new()],
1061            next_reg: 0,
1062            named: Vec::new(),
1063            loop_stack: Vec::new(),
1064            loop_locals: std::collections::HashMap::new(),
1065            max_reg: 0,
1066            expr_depth: 0,
1067            flow_stack: Vec::new(),
1068            tail_fn: None,
1069            hoist_enabled: Vec::new(),
1070            in_function: false,
1071            current_return_type: None,
1072            promoted: HashMap::new(),
1073            closure_ctx: None,
1074            oracle,
1075            narrowable_seqs: std::collections::HashSet::new(),
1076            fixed_seq_caps: HashMap::new(),
1077            declared_types: Vec::new(),
1078            mut_borrow_params: HashMap::new(),
1079            inout_params: HashMap::new(),
1080            native_fns: HashMap::new(),
1081            mut_borrow_alias_syms: HashMap::new(),
1082            current_exempt_syms: std::collections::HashSet::new(),
1083            current_exempt_regs: Vec::new(),
1084            reversible_depth: 0,
1085        };
1086
1087        // Every user type's name → is-it-a-struct (true) or an enum (false) — so a field or
1088        // parameter referencing a user type resolves to `BoundaryType::Struct`/`Enum`. Collected
1089        // from both the registry and the pass-1 statements (a type can be defined either way).
1090        let mut user_types: std::collections::HashMap<Symbol, bool> =
1091            std::collections::HashMap::new();
1092        for s in stmts {
1093            if let Stmt::StructDef { name, .. } = s {
1094                user_types.insert(*name, true);
1095            }
1096        }
1097        // Enum types are not a top-level `Stmt` — they come from the type registry (below).
1098        // The bytecode's static struct registry (name → resolved field layout). Built from the type
1099        // registry, which (unlike the lossy `struct_defs` map below) preserves `Seq` field elements.
1100        let mut struct_types: Vec<StructTypeDef> = Vec::new();
1101        // The sum-type companion: name → per-variant payload layout, for typing a `When V (binds)`
1102        // extraction on an enum PARAMETER (whose construction isn't in scope).
1103        let mut enum_types: Vec<crate::vm::instruction::EnumTypeDef> = Vec::new();
1104
1105        // Struct definitions from the type registry (mirrors the tree-walker's
1106        // with_type_registry) and from StructDef statements (pass 1 below).
1107        if let Some(registry) = types {
1108            use crate::analysis::registry::{FieldType, TypeDef};
1109            for (name_sym, type_def) in registry.iter_types() {
1110                match type_def {
1111                    TypeDef::Struct { .. } => {
1112                        user_types.insert(*name_sym, true);
1113                    }
1114                    TypeDef::Enum { .. } => {
1115                        user_types.insert(*name_sym, false);
1116                    }
1117                    _ => {}
1118                }
1119            }
1120            for (name_sym, type_def) in registry.iter_types() {
1121                if let TypeDef::Struct { fields, .. } = type_def {
1122                    let field_defs: Vec<(Symbol, Symbol, bool)> = fields
1123                        .iter()
1124                        .map(|f| {
1125                            let type_sym = match &f.ty {
1126                                FieldType::Primitive(s)
1127                                | FieldType::Named(s)
1128                                | FieldType::TypeParam(s) => *s,
1129                                FieldType::Generic { base, .. } => *base,
1130                                // A tuple names no type with a scalar default.
1131                                FieldType::Tuple(_) | FieldType::Record(_) => Symbol::EMPTY,
1132                            };
1133                            (f.name, type_sym, f.is_public)
1134                        })
1135                        .collect();
1136                    c.struct_defs.insert(*name_sym, field_defs);
1137                    // Resolve the FULL field layout; carry the struct only if EVERY field resolves
1138                    // (a partial layout would mis-place slots), so an unmodeled field type (Map, …)
1139                    // simply leaves a parameter of that struct type rejected — never miscompiled.
1140                    let resolved: Option<Vec<(String, BoundaryType)>> = fields
1141                        .iter()
1142                        .map(|f| {
1143                            boundary_of_field_type(&f.ty, &user_types, interner)
1144                                .map(|t| (interner.resolve(f.name).to_string(), t))
1145                        })
1146                        .collect();
1147                    if let Some(field_layout) = resolved {
1148                        struct_types.push(StructTypeDef {
1149                            name: interner.resolve(*name_sym).to_string(),
1150                            fields: field_layout,
1151                        });
1152                    }
1153                }
1154            }
1155            // Every enum's own constructor list (G5's `compile_inspect` fallthrough) — unconditional,
1156            // unlike `enum_types` below: naming an UNCOVERED constructor needs only its name, never
1157            // its payload layout, so an unmodeled payload type must not hide the enum from this table.
1158            for (name_sym, type_def) in registry.iter_types() {
1159                if let TypeDef::Enum { variants, .. } = type_def {
1160                    let names: Vec<Symbol> = variants.iter().map(|v| v.name).collect();
1161                    for v in &names {
1162                        c.variant_enum.insert(*v, *name_sym);
1163                    }
1164                    c.enum_variants.insert(*name_sym, names);
1165                    for v in variants {
1166                        let field_names: Vec<Symbol> = v.fields.iter().map(|f| f.name).collect();
1167                        c.variant_fields.insert((*name_sym, v.name), field_names);
1168                    }
1169                }
1170            }
1171            // Enum variant payload layouts. Carry the enum only if EVERY variant's EVERY field
1172            // resolves (a partial layout could mis-type a `BindArm`), so an unmodeled payload type
1173            // simply leaves a parameter of that enum's payload extraction rejected — never miscompiled.
1174            for (name_sym, type_def) in registry.iter_types() {
1175                if let TypeDef::Enum { variants, .. } = type_def {
1176                    let resolved: Option<Vec<crate::vm::instruction::EnumVariantDef>> = variants
1177                        .iter()
1178                        .map(|v| {
1179                            let field_types: Option<Vec<BoundaryType>> = v
1180                                .fields
1181                                .iter()
1182                                .map(|f| boundary_of_field_type(&f.ty, &user_types, interner))
1183                                .collect();
1184                            field_types.map(|ft| crate::vm::instruction::EnumVariantDef {
1185                                name: interner.resolve(v.name).to_string(),
1186                                field_types: ft,
1187                            })
1188                        })
1189                        .collect();
1190                    if let Some(variant_layouts) = resolved {
1191                        enum_types.push(crate::vm::instruction::EnumTypeDef {
1192                            name: interner.resolve(*name_sym).to_string(),
1193                            variants: variant_layouts,
1194                        });
1195                    }
1196                }
1197            }
1198        }
1199        // Expose the fully-built user-type map so `compile_closure` can resolve a struct/enum
1200        // closure PARAMETER's declared type (it runs deep in statement compilation, below).
1201        c.user_types = user_types.clone();
1202
1203        // Inferred mutable-borrow params (value-semantics COW exemption): compute the
1204        // SAME set the AOT uses (`codegen/program.rs`) so the eager VM mutates a
1205        // consumed-and-returned Seq param in place instead of deep-cloning on every
1206        // `SetIndex` (the heap_sort/quicksort O(n²) collapse). Gated on the type
1207        // registry being available AND value semantics being on (else the exemption
1208        // is irrelevant). See [`Op::EnsureOwned`] for the call-site soundness barrier.
1209        if let Some(registry) = types {
1210            if crate::semantics::collections::value_semantics_enabled() {
1211                use crate::analysis::readonly::{detect_consume_alias, MutableBorrowParams};
1212                use crate::codegen::detection::is_vec_type_expr;
1213                use crate::codegen::program::body_contains_escape;
1214                use crate::codegen::tce::is_tail_recursive;
1215                use crate::optimization::Opt;
1216                use crate::optimize::active_config;
1217                use crate::tail_call::detect_accumulator_pattern;
1218                let cg = crate::analysis::callgraph::CallGraph::build(stmts, interner);
1219                let type_env = crate::analysis::TypeEnv::infer_program(stmts, interner, registry);
1220                let mb = MutableBorrowParams::analyze(stmts, &cg, &type_env);
1221                for s in stmts {
1222                    if let Stmt::FunctionDef {
1223                        name,
1224                        params,
1225                        body,
1226                        is_native,
1227                        is_exported,
1228                        opt_flags,
1229                        ..
1230                    } = s
1231                    {
1232                        if *is_native || *is_exported {
1233                            continue;
1234                        }
1235                        if !active_config().merged(opt_flags).is_on(Opt::Borrow) {
1236                            continue;
1237                        }
1238                        if is_tail_recursive(*name, body)
1239                            || detect_accumulator_pattern(*name, body).is_some()
1240                            || body_contains_escape(body)
1241                        {
1242                            continue;
1243                        }
1244                        let mut idxs = std::collections::HashSet::new();
1245                        let mut aliases = std::collections::HashSet::new();
1246                        for (i, (psym, pty)) in params.iter().enumerate() {
1247                            if mb.is_mutable_borrow(*name, *psym) && is_vec_type_expr(pty, interner)
1248                            {
1249                                idxs.insert(i);
1250                                if let Some(alias) = detect_consume_alias(body, *psym) {
1251                                    aliases.insert(alias);
1252                                }
1253                            }
1254                        }
1255                        if !idxs.is_empty() {
1256                            c.mut_borrow_params.insert(*name, idxs);
1257                            c.mut_borrow_alias_syms.insert(*name, aliases);
1258                        }
1259                    }
1260                }
1261            }
1262        }
1263
1264        if let Some(registry) = types {
1265            if crate::optimize::active_config().is_on(crate::optimization::Opt::Scalarize) {
1266                use crate::analysis::readonly::ReadonlyParams;
1267                let callgraph = crate::analysis::callgraph::CallGraph::build(stmts, interner);
1268                let type_env = crate::analysis::TypeEnv::infer_program(stmts, interner, registry);
1269                let readonly = ReadonlyParams::analyze(stmts, &callgraph, &type_env);
1270                let mut borrow = HashMap::<Symbol, std::collections::HashSet<usize>>::new();
1271                for stmt in stmts {
1272                    let Stmt::FunctionDef { name, params, .. } = stmt else {
1273                        continue;
1274                    };
1275                    let indices = params
1276                        .iter()
1277                        .enumerate()
1278                        .filter_map(|(index, (param, _))| {
1279                            readonly.is_readonly(*name, *param).then_some(index)
1280                        })
1281                        .collect::<std::collections::HashSet<_>>();
1282                    if !indices.is_empty() {
1283                        borrow.insert(*name, indices);
1284                    }
1285                }
1286                c.fixed_seq_caps =
1287                    crate::codegen::affine_array::fixed_stack_seq_plan(stmts, &borrow, interner);
1288                if !c.fixed_seq_caps.is_empty() {
1289                    crate::optimize::mark_fired(crate::optimization::Opt::Scalarize);
1290                }
1291            }
1292        }
1293
1294        // Pass 1: register every function name → index (entry_pc filled later)
1295        // and every struct definition.
1296        for s in stmts {
1297            if let Stmt::StructDef { name, fields, .. } = s {
1298                c.struct_defs.insert(*name, fields.clone());
1299            }
1300            if let Stmt::FunctionDef {
1301                name,
1302                is_native: true,
1303                native_path,
1304                ..
1305            } = s
1306            {
1307                c.native_fns.insert(*name, *native_path);
1308            }
1309            if let Stmt::FunctionDef {
1310                name,
1311                params,
1312                return_type,
1313                ..
1314            } = s
1315            {
1316                if c.fn_index.contains_key(name) {
1317                    return Err(format!(
1318                        "vm: function '{}' defined twice",
1319                        interner.resolve(*name)
1320                    )
1321                    .into());
1322                }
1323                let idx = c.functions.len() as FuncIdx;
1324                c.fn_index.insert(*name, idx);
1325                let inout: Vec<usize> = params
1326                    .iter()
1327                    .enumerate()
1328                    .filter(|(_, (_, ty))| matches!(ty, crate::ast::stmt::TypeExpr::Mutable { .. }))
1329                    .map(|(i, _)| i)
1330                    .collect();
1331                if !inout.is_empty() {
1332                    c.inout_params.insert(*name, inout);
1333                }
1334                c.functions.push(CompiledFunction {
1335                    name: *name,
1336                    entry_pc: 0,
1337                    param_count: u16::try_from(params.len())
1338                        .map_err(|_| "vm: too many parameters".to_string())?,
1339                    register_count: 0,
1340                    captures: Vec::new(),
1341                    named_regs: Vec::new(),
1342                    param_kinds: params
1343                        .iter()
1344                        .map(|(_, ty)| {
1345                            param_kind_of_type(ty, interner).or_else(|| {
1346                                matches!(
1347                                    boundary_of_type_expr(ty, &user_types, interner),
1348                                    Some(BoundaryType::Enum(_))
1349                                )
1350                                .then_some(super::native_tier::ParamKind::Inductive)
1351                            })
1352                        })
1353                        .collect(),
1354                    ret_kind: return_type.and_then(|ty| slot_kind_of_type(ty, interner)),
1355                    param_types: params
1356                        .iter()
1357                        .map(|(_, ty)| boundary_of_type_expr(ty, &user_types, interner))
1358                        .collect(),
1359                    return_type: return_type
1360                        .and_then(|ty| boundary_of_type_expr(ty, &user_types, interner)),
1361                    mutable_param_regs: {
1362                        // `mutable` param at position `i` → frame register `i`; plus
1363                        // every INFERRED mutable-borrow param (same reg == index).
1364                        let inferred = c.mut_borrow_params.get(name);
1365                        let mut mp: Vec<Reg> = Vec::new();
1366                        for (i, (_psym, ty)) in params.iter().enumerate() {
1367                            if matches!(ty, crate::ast::stmt::TypeExpr::Mutable { .. })
1368                                || inferred.is_some_and(|s| s.contains(&i))
1369                            {
1370                                mp.push(i as Reg);
1371                            }
1372                        }
1373                        mp
1374                    },
1375                    cow_exempt_regs: params
1376                        .iter()
1377                        .enumerate()
1378                        .filter(|(i, (_, ty))| {
1379                            !matches!(ty, crate::ast::stmt::TypeExpr::Mutable { .. })
1380                                && c.mut_borrow_params.get(name).is_some_and(|p| p.contains(i))
1381                        })
1382                        .map(|(i, _)| i as Reg)
1383                        .collect(),
1384                });
1385            }
1386        }
1387
1388        // The refusals the `Mount` and `## Route` arms raise, decided once from the whole
1389        // program — the same ones `lgx_refusals` hands an editor.
1390        c.mount_refusals = mount_refusals(stmts, interner, types);
1391        c.route_refusals =
1392            route_refusal_map(stmts, interner, &|sym| c.struct_defs.contains_key(&sym));
1393
1394        // Pass 1.5: promote Main TOP-LEVEL Let names referenced from any
1395        // function or closure body to globals (lexically visible everywhere).
1396        let mut nonlocal_idents: std::collections::HashSet<Symbol> =
1397            std::collections::HashSet::new();
1398        for s in stmts {
1399            collect_nonlocal_idents_stmt(s, true, &mut nonlocal_idents);
1400        }
1401        let mut global_names: Vec<String> = Vec::new();
1402        // Parallel to `global_names`: each promoted global's resolved composite type (for typing a
1403        // closure capture of it); `None` for a scalar / self-describing / unmodeled value.
1404        let mut global_types: Vec<Option<BoundaryType>> = Vec::new();
1405        for s in stmts {
1406            if let Stmt::Let { var, ty, value, .. } = s {
1407                if nonlocal_idents.contains(var) && !c.promoted.contains_key(var) {
1408                    let idx = u16::try_from(c.promoted.len())
1409                        .map_err(|_| "vm: too many globals".to_string())?;
1410                    c.promoted.insert(*var, idx);
1411                    global_names.push(interner.resolve(*var).to_string());
1412                    // What the binding declares — its annotation, or the declared return type of the
1413                    // function its value calls — and only then what its value's construction shows.
1414                    let declared = c.declared_binding(*ty, value);
1415                    global_types.push(declared.or_else(|| {
1416                        boundary_of_value_expr(value, &user_types, interner, &|f| {
1417                            c.return_type_of(f)
1418                        })
1419                    }));
1420                }
1421            }
1422        }
1423
1424        // Pass 2a: compile Main (every non-FunctionDef top-level statement).
1425        // Behind `LOGOS_NARROW_VM`: certify which top-level `new Seq of Int`
1426        // declarations fit `i32` (the AOT narrowing proof), so their empty
1427        // constructor lowers to the half-width `NewEmptyListI32`. The proof's
1428        // `walk`/`escapes` ignore `FunctionDef` statements (none of the write
1429        // forms it tracks), and the runtime widen-on-overflow is the ultimate
1430        // safety net, so feeding the full statement list is sound.
1431        if narrow_vm_enabled() {
1432            c.narrowable_seqs = crate::codegen::narrow::narrowable_seqs_for_body(stmts, interner);
1433            if !c.narrowable_seqs.is_empty() {
1434                crate::optimize::mark_fired(crate::optimization::Opt::NarrowVm);
1435            }
1436        }
1437        c.begin_scope();
1438        for s in stmts {
1439            if !matches!(s, Stmt::FunctionDef { .. }) {
1440                c.compile_stmt(s)?;
1441            }
1442        }
1443        c.narrowable_seqs.clear();
1444        c.emit(Op::Halt);
1445        let main_regs = c.max_reg as usize;
1446        let mut named_regs = c.named.clone();
1447        named_regs.resize(main_regs, false);
1448        // Snapshot Main's variable names NOW — the per-function `begin_scope` below
1449        // clears `dbg_names`. Empty unless the debugger enabled name capture.
1450        let reg_names: Vec<(u16, String)> = c
1451            .dbg_names
1452            .iter()
1453            .map(|(r, sym)| (*r, c.interner.resolve(*sym).to_string()))
1454            .collect();
1455
1456        // DEBUG-ONLY: each function's name and, once its body compiles, its variable names.
1457        let mut fn_debug: Vec<FnDebugInfo> = if c.debug_names {
1458            c.functions
1459                .iter()
1460                .map(|f| FnDebugInfo {
1461                    name: c.interner.resolve(f.name).to_string(),
1462                    reg_names: Vec::new(),
1463                })
1464                .collect()
1465        } else {
1466            Vec::new()
1467        };
1468
1469        // Pass 2b: compile each function body, recording its entry point.
1470        for s in stmts {
1471            if let Stmt::FunctionDef {
1472                name,
1473                params,
1474                body,
1475                return_type,
1476                ..
1477            } = s
1478            {
1479                let idx = c.fn_index[name];
1480                let entry_pc = c.code.len();
1481                c.site_at
1482                    .push((entry_pc as u32, crate::vm::instruction::NO_SITE));
1483                c.begin_scope();
1484                c.in_function = true;
1485                c.current_return_type = *return_type;
1486                c.named.clear();
1487                for (i, (psym, _ty)) in params.iter().enumerate() {
1488                    c.scopes.last_mut().unwrap().insert(*psym, i as Reg);
1489                    c.mark_named(i as Reg);
1490                    c.record_dbg_name(*psym, i as Reg);
1491                }
1492                c.next_reg = params.len() as Reg;
1493                // Parameters occupy registers 0..n even when the body
1494                // allocates no temps — register_count must cover them or
1495                // the native frame's limit slot aliases a parameter.
1496                c.max_reg = c.max_reg.max(c.next_reg);
1497                debug_assert!(params.len() <= MAX_REGISTERS_PER_FRAME);
1498                c.tail_fn = Some((*name, entry_pc, params.len() as u16));
1499                // COW-exempt the consume-alias locals of this function's mutable-borrow
1500                // params: `let_reg` appends each one's register as the body compiles.
1501                c.current_exempt_syms = c
1502                    .mut_borrow_alias_syms
1503                    .get(name)
1504                    .cloned()
1505                    .unwrap_or_default();
1506                c.current_exempt_regs.clear();
1507                let body_slice: &[Stmt] = body;
1508                let mut bk = 0;
1509                while bk < body_slice.len() {
1510                    // TAIL-CALL PAIR: `Set/Let x = self(args)` immediately
1511                    // followed by `Return x` is a self-tail-call (x is returned,
1512                    // never read after) — lower it to the loop-back instead of
1513                    // call+return. A direct `Return self(args)` is handled in the
1514                    // Return arm of compile_stmt (a Return is inherently tail).
1515                    if bk + 1 < body_slice.len() {
1516                        if let Some(args) = crate::tail_call::tail_pair_args(
1517                            &body_slice[bk],
1518                            &body_slice[bk + 1],
1519                            *name,
1520                            params.len(),
1521                        ) {
1522                            let mark = c.next_reg;
1523                            c.emit_tail_call(args, entry_pc)?;
1524                            c.reclaim_scratch(mark);
1525                            bk += 2;
1526                            continue;
1527                        }
1528                    }
1529                    c.compile_stmt(&body_slice[bk])?;
1530                    bk += 1;
1531                }
1532                c.tail_fn = None;
1533                // Fall off the end → return nothing.
1534                c.emit(Op::ReturnNothing);
1535                // Merge the consume-alias exempt registers discovered while compiling
1536                // the body into this function's COW-exempt set.
1537                let exempt = std::mem::take(&mut c.current_exempt_regs);
1538                c.current_exempt_syms.clear();
1539                let f = &mut c.functions[idx as usize];
1540                for r in exempt {
1541                    if !f.mutable_param_regs.contains(&r) {
1542                        f.mutable_param_regs.push(r);
1543                    }
1544                    if !f.cow_exempt_regs.contains(&r) {
1545                        f.cow_exempt_regs.push(r);
1546                    }
1547                }
1548                f.entry_pc = entry_pc;
1549                f.register_count = c.max_reg as usize;
1550                let mut fnamed = c.named.clone();
1551                fnamed.resize(f.register_count, false);
1552                f.named_regs = fnamed;
1553                if let Some(info) = fn_debug.get_mut(idx as usize) {
1554                    info.reg_names = c
1555                        .dbg_names
1556                        .iter()
1557                        .map(|(r, sym)| (*r, c.interner.resolve(*sym).to_string()))
1558                        .collect();
1559                }
1560            }
1561        }
1562        // Closures compiled along the way have no source name of their own.
1563        if c.debug_names {
1564            fn_debug.resize_with(c.functions.len(), FnDebugInfo::default);
1565        }
1566
1567        Ok(CompiledProgram {
1568            constants: c.constants,
1569            code: c.code,
1570            register_count: main_regs,
1571            functions: c.functions,
1572            fn_index: c.fn_index,
1573            globals: global_names,
1574            named_regs,
1575            loop_locals: c.loop_locals,
1576            reg_names,
1577            fn_debug,
1578            struct_types,
1579            enum_types,
1580            global_types,
1581            declared_types: {
1582                let mut declared = std::mem::take(&mut c.declared_types);
1583                declared.sort_by_key(|(pc, _)| *pc);
1584                declared
1585            },
1586            observation_sites: c.observation_sites,
1587            site_at: c.site_at,
1588        })
1589    }
1590
1591    fn begin_scope(&mut self) {
1592        self.scopes = vec![HashMap::new()];
1593        self.next_reg = 0;
1594        self.max_reg = 0;
1595        self.in_function = false;
1596        self.current_return_type = None;
1597        self.dbg_names.clear();
1598    }
1599
1600    /// Enter a child block scope (If/While/Repeat body).
1601    fn enter_block(&mut self) -> Reg {
1602        self.scopes.push(HashMap::new());
1603        self.next_reg
1604    }
1605
1606    /// Leave a block scope, recycling every register it allocated (its values
1607    /// are dead — the tree-walker's pop_scope undoes the bindings too).
1608    fn exit_block(&mut self, mark: Reg) {
1609        self.scopes.pop();
1610        self.next_reg = mark;
1611    }
1612
1613    /// Resolve a name through the enclosing block scopes (innermost first).
1614    fn lookup_local(&self, sym: Symbol) -> Option<Reg> {
1615        self.scopes.iter().rev().find_map(|s| s.get(&sym).copied())
1616    }
1617
1618    /// Is `sym`'s region-entry bounds guard active in some enclosing loop?
1619    fn is_hoist_enabled(&self, sym: Symbol) -> bool {
1620        self.hoist_enabled.iter().any(|s| s.contains(&sym))
1621    }
1622
1623    /// Should `item index of collection` be emitted UNCHECKED? Either the
1624    /// Oracle proved it in range on every run, or it is speculatively in bounds
1625    /// AND its array's region-entry guard was emitted for an enclosing loop (so
1626    /// the VM verifies it before any unchecked native access runs). A proof that
1627    /// holds only under a `% m` precondition keeps the check.
1628    fn index_in_bounds(&self, collection: &Expr, index: &Expr) -> bool {
1629        // The shared optimizer can attach an unconditional proof directly to
1630        // this exact index node (for example, the TileLegal matrix clone).
1631        // Consume that proof before asking the Oracle for an independently
1632        // reconstructed interval.  Requiring both proofs made `InBounds`
1633        // unreachable whenever optimization changed the loop shape enough
1634        // that the Oracle no longer rediscovered the same relation.
1635        if crate::optimize::active_config().is_on(crate::optimization::Opt::Unchecked)
1636            && crate::optimize::facts::holds_expr(crate::optimize::facts::Fact::InBounds, index)
1637        {
1638            return true;
1639        }
1640        let Some(o) = self.oracle.as_ref() else {
1641            return false;
1642        };
1643        if o.index_provably_in_bounds(collection, index) {
1644            return o.index_always_in_bounds(collection, index);
1645        }
1646        o.index_is_speculative(index)
1647            && matches!(collection, Expr::Identifier(s) if self.is_hoist_enabled(*s))
1648    }
1649
1650    /// `x / 2^k` where the divisor is a literal power of two and the Oracle
1651    /// proves the dividend is `Int` → the shift amount `k` (`1..=62`), else
1652    /// `None`. Type-safety is the crux: `Op::Div` dispatches int/float at
1653    /// runtime on the dividend, so lowering to a shift is sound ONLY for an
1654    /// integer dividend. The literal divisor is visible here pre-hoist, so this
1655    /// fires for loop-invariant divisors the JIT's in-region detector misses.
1656    fn divpow2_shift(&self, left: &Expr, right: &Expr) -> Option<u32> {
1657        let Expr::Literal(Literal::Number(d)) = right else {
1658            return None;
1659        };
1660        let d = *d;
1661        if d < 2 || (d & (d - 1)) != 0 {
1662            return None;
1663        }
1664        let k = d.trailing_zeros();
1665        if !(1..=62).contains(&k) {
1666            return None;
1667        }
1668        if self.oracle.as_ref()?.expr_scalar(left)? != crate::optimize::ScalarKind::Int {
1669            return None;
1670        }
1671        Some(k)
1672    }
1673
1674    /// `x % 2^k` where the divisor is a literal power of two AND the Oracle
1675    /// proves the dividend is `Int` and NON-NEGATIVE → the low-bit mask
1676    /// `2^k - 1`, else `None`. On a two's-complement i64 the truncated
1677    /// remainder agrees with `x & (2^k - 1)` only when `x >= 0` (the sign of
1678    /// `x % m` follows the dividend, so `(-1) % 8 == -1 != 7 == (-1) & 7`); the
1679    /// non-negativity gate is the SOUNDNESS condition — exactly the gate the AOT
1680    /// e-graph's `mod-pow2-and` rule applies. The literal divisor is visible
1681    /// here pre-hoist, so this fires for loop-invariant moduli the JIT's
1682    /// in-region detector misses (histogram's `% 2^31` LCG feedback). The win:
1683    /// a register-form `BitAnd` (1-cycle AND, which the JIT lowers to a
1684    /// `BitAnd` stencil) instead of `Op::Mod`'s idiv on BOTH the VM and JIT.
1685    fn modpow2_mask(&self, left: &Expr, right: &Expr) -> Option<i64> {
1686        let Expr::Literal(Literal::Number(d)) = right else {
1687            return None;
1688        };
1689        let d = *d;
1690        if d < 2 || (d & (d - 1)) != 0 {
1691            return None;
1692        }
1693        let k = d.trailing_zeros();
1694        if !(1..=62).contains(&k) {
1695            return None;
1696        }
1697        let oracle = self.oracle.as_ref()?;
1698        if oracle.expr_scalar(left)? != crate::optimize::ScalarKind::Int {
1699            return None;
1700        }
1701        if !oracle.expr_proven_nonneg(left) {
1702            return None;
1703        }
1704        Some(d - 1)
1705    }
1706
1707    /// `x / c` or `x % c` where the divisor is a literal constant `c > 0` that is
1708    /// NOT a power of two (W5's `divpow2_shift`/`modpow2_mask` own powers of two)
1709    /// AND the Oracle proves `x` is `Int` and NON-NEGATIVE → the precomputed
1710    /// `(magic, more)` for the unsigned magic-reciprocal sequence, else `None`.
1711    ///
1712    /// SOUNDNESS — the unsigned magic equals the signed truncating `/`/`%` only
1713    /// for a non-negative dividend: `x.wrapping_div(c)` / `x.wrapping_rem(c)`
1714    /// equal `(x as u64) / c` / `(x as u64) % c` exactly when `x >= 0` and
1715    /// `c > 0` (both operands non-negative, no overflow edge — `c` is a literal
1716    /// `> 0` so `MIN/-1` is impossible). For `x < 0` the signs disagree, so the
1717    /// non-negativity gate is the soundness condition — exactly the gate
1718    /// `modpow2_mask` and the AOT `fast_div` lever apply. The literal divisor is
1719    /// visible here pre-hoist, so this fires for loop-invariant moduli the JIT's
1720    /// in-region detector misses (matrix's `% 1000000007`, histogram's `% 1000`).
1721    fn magic_div_const(&self, left: &Expr, right: &Expr) -> Option<(u64, u8, i64)> {
1722        if !magic_div_enabled() {
1723            return None;
1724        }
1725        let Expr::Literal(Literal::Number(d)) = right else {
1726            return None;
1727        };
1728        let d = *d;
1729        // `c > 0` and NOT a power of two (pow2 is W5's AND/shift territory).
1730        if d < 2 || (d & (d - 1)) == 0 {
1731            return None;
1732        }
1733        let oracle = self.oracle.as_ref()?;
1734        if oracle.expr_scalar(left)? != crate::optimize::ScalarKind::Int {
1735            return None;
1736        }
1737        // The magic reciprocal is emitted OPTIMISTICALLY on a proven-non-negative dividend, whose
1738        // interval may be unbounded above (the AI cannot narrow a loop induction var like `i < 5000`
1739        // that stays i64 at runtime — the perf lock `magic_nonneg_div_rewrite_fires` depends on this).
1740        // Soundness for a value that IS a `BigInt` at runtime is restored by `Op::MagicDivU`'s carried
1741        // `divisor`: the VM handler falls back to exact `Div`/`Mod` when the operand does not fit i64.
1742        if !oracle.expr_proven_nonneg(left) {
1743            return None;
1744        }
1745        let (magic, more) = magic_u64_gen(d as u64);
1746        crate::optimize::mark_fired(crate::optimization::Opt::FastDiv);
1747        Some((magic, more, d))
1748    }
1749
1750    /// `Opt::ModWrap` for `x % c`: how the remainder reduces when `c` is a literal and the Oracle proves `x` an
1751    /// `Int` within a finite range ([`crate::optimize::modwrap::mod_wrap`]), or `None` when it must divide. The
1752    /// AST emitters decide the same reduction from the same Oracle.
1753    fn mod_wrap_const(&self, left: &Expr, right: &Expr) -> Option<crate::optimize::modwrap::ModWrap> {
1754        if !crate::optimize::active_config().is_on(crate::optimization::Opt::ModWrap) {
1755            return None;
1756        }
1757        let Expr::Literal(Literal::Number(c)) = right else {
1758            return None;
1759        };
1760        let oracle = self.oracle.as_ref()?;
1761        if oracle.expr_scalar(left)? != crate::optimize::ScalarKind::Int {
1762            return None;
1763        }
1764        let (lo, hi) = oracle.expr_int_range(left)?;
1765        crate::optimize::modwrap::mod_wrap(*c, Some((i128::from(lo), i128::from(hi))))
1766    }
1767
1768    /// Emit `RegionBoundsGuard` for each hoist descriptor the Oracle recorded
1769    /// for the loop `stmt`, returning the set of arrays whose guard was
1770    /// emitted (only those are then eligible for speculative elision). All
1771    /// three symbols must resolve to local registers, and the loop must read
1772    /// the array's length nowhere stale — guaranteed by the Oracle's analysis.
1773    fn emit_hoist_guards(&mut self, stmt: &Stmt) -> std::collections::HashSet<Symbol> {
1774        let mut enabled = std::collections::HashSet::new();
1775        let Some(oracle) = self.oracle.as_ref() else {
1776            return enabled;
1777        };
1778        let descs = oracle
1779            .hoist_descs_for(stmt as *const Stmt as usize)
1780            .to_vec();
1781        for d in descs {
1782            let (Some(array), Some(bound), Some(iv)) = (
1783                self.lookup_local(d.array),
1784                self.lookup_local(d.bound),
1785                self.lookup_local(d.iv),
1786            ) else {
1787                continue;
1788            };
1789            self.emit(Op::RegionBoundsGuard {
1790                array,
1791                bound,
1792                iv,
1793                add_max: d.add_max,
1794                add_min: d.add_min,
1795            });
1796            enabled.insert(d.array);
1797        }
1798        enabled
1799    }
1800
1801    /// Emit the runtime "Undefined variable" failure — unbound names are a
1802    /// RUNTIME error in the tree-walker, so dead branches stay free.
1803    fn emit_unbound(&mut self, sym: Symbol) -> Result<(), Refusal> {
1804        let msg = format!("Undefined variable: {}", self.interner.resolve(sym));
1805        let idx = self.add_const(Constant::Text(msg))?;
1806        self.emit(Op::FailWith { msg: idx });
1807        Ok(())
1808    }
1809
1810    /// Emit an unconditional runtime failure with a fixed message — the
1811    /// pattern for statements the interpreter spec rejects WHEN EXECUTED.
1812    fn emit_fail(&mut self, msg: &str) -> Result<(), Refusal> {
1813        let idx = self.add_const(Constant::Text(msg.to_string()))?;
1814        self.emit(Op::FailWith { msg: idx });
1815        Ok(())
1816    }
1817
1818    /// Resolve a name: block locals (and closure captures) shadow promoted
1819    /// globals; a promoted capture in a closure body needs the
1820    /// snapshot-or-live-global split.
1821    fn resolve_name(&self, sym: Symbol) -> NameRef {
1822        if let Some(r) = self.lookup_local(sym) {
1823            if let Some(ctx) = &self.closure_ctx {
1824                if let Some(&(value, flag)) = ctx.get(&sym) {
1825                    // Only when the local resolution IS the capture slot (a
1826                    // body-local `Let` shadows the capture entirely).
1827                    if r == value {
1828                        if let Some(&global) = self.promoted.get(&sym) {
1829                            return NameRef::CaptureOrGlobal {
1830                                value,
1831                                flag,
1832                                global,
1833                            };
1834                        }
1835                    }
1836                }
1837            }
1838            NameRef::Local(r)
1839        } else if let Some(&g) = self.promoted.get(&sym) {
1840            NameRef::Global(g)
1841        } else {
1842            NameRef::Unbound
1843        }
1844    }
1845
1846    /// Emit a read of `sym` into `dst`.
1847    fn emit_read(&mut self, sym: Symbol, dst: Reg) -> Result<(), Refusal> {
1848        match self.resolve_name(sym) {
1849            NameRef::Local(src) => {
1850                if src != dst {
1851                    self.emit(Op::Move { dst, src });
1852                }
1853                Ok(())
1854            }
1855            NameRef::CaptureOrGlobal {
1856                value,
1857                flag,
1858                global,
1859            } => {
1860                let jg = self.emit_placeholder_jump_if_false(flag);
1861                self.emit(Op::Move { dst, src: value });
1862                let jend = self.emit_placeholder_jump();
1863                self.patch_jump_target(jg, self.current_pc())?;
1864                self.emit(Op::GlobalGet { dst, idx: global });
1865                self.patch_jump_target(jend, self.current_pc())?;
1866                Ok(())
1867            }
1868            NameRef::Global(idx) => {
1869                self.emit(Op::GlobalGet { dst, idx });
1870                Ok(())
1871            }
1872            NameRef::Unbound => self.emit_unbound(sym),
1873        }
1874    }
1875
1876    /// Emit a write of `R[src]` to `sym` (Set semantics: the binding must
1877    /// already exist somewhere).
1878    fn emit_write(&mut self, sym: Symbol, src: Reg) -> Result<(), Refusal> {
1879        match self.resolve_name(sym) {
1880            NameRef::Local(dst) => {
1881                if src != dst {
1882                    self.emit(Op::Move { dst, src });
1883                }
1884                Ok(())
1885            }
1886            NameRef::CaptureOrGlobal {
1887                value,
1888                flag,
1889                global,
1890            } => {
1891                let jg = self.emit_placeholder_jump_if_false(flag);
1892                self.emit(Op::Move { dst: value, src });
1893                let jend = self.emit_placeholder_jump();
1894                self.patch_jump_target(jg, self.current_pc())?;
1895                self.emit(Op::GlobalSet { idx: global, src });
1896                self.patch_jump_target(jend, self.current_pc())?;
1897                Ok(())
1898            }
1899            NameRef::Global(idx) => {
1900                self.emit(Op::GlobalSet { idx, src });
1901                Ok(())
1902            }
1903            NameRef::Unbound => self.emit_unbound(sym),
1904        }
1905    }
1906
1907    /// `Click "#go".` / `Type … into "#draft".` on this tier: find the element, hand each event the
1908    /// verb raises (`semantics::drive::Verb::events`) to the page's node dispatcher
1909    /// (`__lgx_dispatch_node`) with what the verb carries, and fail in `semantics::drive`'s words —
1910    /// the ones every tier reports — when nothing matches the selector or nothing answered. The
1911    /// one drive semantics every tier shares: a browser, the page host and this tier all deliver
1912    /// an element's event through the same entry. A program with no dispatcher attaches no handler
1913    /// at all, and saying so is more use than a call to a function that does not exist.
1914    fn compile_lgx_drive(
1915        &mut self,
1916        verb: crate::semantics::drive::Verb,
1917        selector: &Expr,
1918        carried: Option<&Expr>,
1919        key: Option<&Expr>,
1920    ) -> Result<(), Refusal> {
1921        use crate::semantics::drive;
1922        let first_event = verb.events()[0];
1923        let dispatcher = logicaffeine_language::parser::lgx_lower::dispatch_node_fn_name();
1924        let func = self
1925            .interner
1926            .lookup(dispatcher)
1927            .and_then(|s| self.fn_index.get(&s).copied());
1928        let Some(func) = func else {
1929            return Err(format!(
1930                "this page answers no {first_event}: nothing in it attaches a handler, so there is \
1931                 nothing for the {first_event} to reach on this tier."
1932            )
1933            .into());
1934        };
1935        let kept_selector = self.keep_operand(selector)?;
1936        let kept_key = key.map(|k| self.keep_operand(k)).transpose()?;
1937        // Typing and choosing are the browser's own default action first — the control takes the
1938        // value whether or not the page listens — so they are answered by the control itself,
1939        // refused only when it cannot take them (`drive::cannot_take`), and their events need no
1940        // listener.
1941        let enters = match verb {
1942            drive::Verb::Type => Some("type"),
1943            drive::Verb::Choose => Some("choose"),
1944            _ => None,
1945        };
1946        let kept_value = match (enters, carried) {
1947            (Some(_), Some(v)) => Some(self.keep_operand(v)?),
1948            _ => None,
1949        };
1950        let found = self.alloc_reg()?;
1951        let value = self.alloc_reg()?;
1952        let answered = self.alloc_reg()?;
1953        match carried {
1954            Some(v) => {
1955                self.compile_expr_into(v, value)?;
1956                if let Some(k) = kept_key.as_ref().or(kept_value.as_ref()) {
1957                    self.keep_move(k, value);
1958                }
1959            }
1960            None => {
1961                let idx = self.add_const(Constant::Text(String::new()))?;
1962                self.emit(Op::LoadConst { dst: value, idx });
1963            }
1964        }
1965        let query = self.reserve_regs(1)?;
1966        self.compile_expr_into(selector, query)?;
1967        self.keep_move(&kept_selector, query);
1968        self.emit(Op::CallBuiltin {
1969            dst: found,
1970            builtin: crate::semantics::builtins::BuiltinId::DomQuerySelector,
1971            args_start: query,
1972            arg_count: 1,
1973        });
1974
1975        let no_element = DriveText::render(|sel, _| drive::no_element(sel), &kept_selector, None);
1976        let nothing_answers = DriveText::render(
1977            |sel, k| drive::nothing_answers(verb.events(), k, sel),
1978            &kept_selector,
1979            kept_key.as_ref(),
1980        );
1981
1982        let zero = self.alloc_reg()?;
1983        let zidx = self.add_const(Constant::Int(0))?;
1984        self.emit(Op::LoadConst {
1985            dst: zero,
1986            idx: zidx,
1987        });
1988        let absent = self.alloc_reg()?;
1989        self.emit(Op::Lt {
1990            dst: absent,
1991            lhs: found,
1992            rhs: zero,
1993        });
1994        let missing_branch = self.code.len();
1995        self.emit(Op::JumpIfTrue {
1996            cond: absent,
1997            target: usize::MAX,
1998        });
1999        if let Some(verb_name) = enters {
2000            let args = self.reserve_regs(3)?;
2001            let vidx = self.add_const(Constant::Text(verb_name.to_string()))?;
2002            self.emit(Op::LoadConst {
2003                dst: args,
2004                idx: vidx,
2005            });
2006            match &kept_selector {
2007                DriveOperand::Known(s) => {
2008                    let sidx = self.add_const(Constant::Text(s.clone()))?;
2009                    self.emit(Op::LoadConst {
2010                        dst: args + 1,
2011                        idx: sidx,
2012                    });
2013                }
2014                DriveOperand::Held(r) => self.emit(Op::Move {
2015                    dst: args + 1,
2016                    src: *r,
2017                }),
2018            }
2019            self.emit(Op::Move {
2020                dst: args + 2,
2021                src: value,
2022            });
2023            let took = self.alloc_reg()?;
2024            self.emit(Op::CallBuiltin {
2025                dst: took,
2026                builtin: crate::semantics::builtins::BuiltinId::DomEnterValue,
2027                args_start: args,
2028                arg_count: 3,
2029            });
2030            let takes = self.code.len();
2031            self.emit(Op::JumpIfTrue {
2032                cond: took,
2033                target: usize::MAX,
2034            });
2035            let cannot_take = DriveText::render(
2036                |sel, v| drive::cannot_take(verb, sel, v.unwrap_or("")),
2037                &kept_selector,
2038                kept_value.as_ref(),
2039            );
2040            self.emit_fail_text(&cannot_take)?;
2041            self.patch_jump_target(takes, self.current_pc())?;
2042        } else {
2043            let no = self.add_const(Constant::Bool(false))?;
2044            self.emit(Op::LoadConst {
2045                dst: answered,
2046                idx: no,
2047            });
2048        }
2049        let yes = if enters.is_none() {
2050            Some(self.add_const(Constant::Bool(true))?)
2051        } else {
2052            None
2053        };
2054        // The page hears each event as the HOST's entry into it, as it hears a visitor's: a turn
2055        // that fails there is contained to it and heard by the page's failure door, and the
2056        // program runs on (`BuiltinId::DomDispatchEntry`). The door is the page's own two
2057        // functions, when it has them.
2058        let page_function = |c: &Self, name: &str| -> i64 {
2059            c.interner
2060                .lookup(name)
2061                .and_then(|s| c.fn_index.get(&s))
2062                .map_or(-1, |&f| i64::from(f))
2063        };
2064        let door = [
2065            i64::from(func),
2066            page_function(
2067                self,
2068                logicaffeine_language::parser::lgx_lower::failure_context_fn_name(),
2069            ),
2070            page_function(
2071                self,
2072                logicaffeine_language::parser::lgx_lower::on_failure_fn_name(),
2073            ),
2074        ];
2075        for event in verb.events() {
2076            let args_start = self.reserve_regs(6)?;
2077            for (k, f) in door.into_iter().enumerate() {
2078                let idx = self.add_const(Constant::Int(f))?;
2079                self.emit(Op::LoadConst {
2080                    dst: args_start + k as Reg,
2081                    idx,
2082                });
2083            }
2084            self.emit(Op::Move {
2085                dst: args_start + 3,
2086                src: found,
2087            });
2088            let name = self.add_const(Constant::Text(event.to_string()))?;
2089            self.emit(Op::LoadConst {
2090                dst: args_start + 4,
2091                idx: name,
2092            });
2093            self.emit(Op::Move {
2094                dst: args_start + 5,
2095                src: value,
2096            });
2097            let heard = self.alloc_reg()?;
2098            self.emit(Op::CallBuiltin {
2099                dst: heard,
2100                builtin: crate::semantics::builtins::BuiltinId::DomDispatchEntry,
2101                args_start,
2102                arg_count: 6,
2103            });
2104            if let Some(yes) = yes {
2105                let unheard = self.code.len();
2106                self.emit(Op::JumpIfFalse {
2107                    cond: heard,
2108                    target: usize::MAX,
2109                });
2110                self.emit(Op::LoadConst {
2111                    dst: answered,
2112                    idx: yes,
2113                });
2114                self.patch_jump_target(unheard, self.current_pc())?;
2115            }
2116        }
2117        let ok = self.code.len();
2118        if enters.is_some() {
2119            self.emit(Op::Jump { target: usize::MAX });
2120        } else {
2121            self.emit(Op::JumpIfTrue {
2122                cond: answered,
2123                target: usize::MAX,
2124            });
2125            self.emit_fail_text(&nothing_answers)?;
2126        }
2127        self.patch_jump_target(missing_branch, self.current_pc())?;
2128        self.emit_fail_text(&no_element)?;
2129        self.patch_jump_target(ok, self.current_pc())?;
2130        Ok(())
2131    }
2132
2133    /// Call a PAGE-level driver — `__lgx_raise` (a window event), `__lgx_tick` (the page clock).
2134    /// The page always exists and an event it ignores is not a mistake, so these drivers always
2135    /// answer 2 and there is no failure to raise.
2136    fn compile_page_drive(&mut self, func: FuncIdx, args: &[&Expr]) -> Result<(), Refusal> {
2137        let arg_count =
2138            u16::try_from(args.len()).map_err(|_| "vm: too many arguments".to_string())?;
2139        let args_start = self.reserve_regs(arg_count)?;
2140        for (i, arg) in args.iter().enumerate() {
2141            self.compile_expr_into(arg, args_start + i as Reg)?;
2142        }
2143        let dst = self.alloc_reg()?;
2144        self.emit(Op::Call {
2145            dst,
2146            func,
2147            args_start,
2148            arg_count,
2149        });
2150        Ok(())
2151    }
2152
2153    /// Stop the program with `text`: one constant when every piece was known at compile time,
2154    /// otherwise the pieces concatenated at run time and handed to the failing builtin.
2155    fn emit_fail_text(&mut self, text: &DriveText) -> Result<(), Refusal> {
2156        if let [DrivePiece::Text(whole)] = text.pieces.as_slice() {
2157            let idx = self.add_const(Constant::Text(whole.clone()))?;
2158            self.emit(Op::FailWith { msg: idx });
2159            return Ok(());
2160        }
2161        let arg = self.reserve_regs(1)?;
2162        let empty = self.add_const(Constant::Text(String::new()))?;
2163        self.emit(Op::LoadConst {
2164            dst: arg,
2165            idx: empty,
2166        });
2167        for piece in &text.pieces {
2168            let part = match piece {
2169                DrivePiece::Text(t) => {
2170                    let idx = self.add_const(Constant::Text(t.clone()))?;
2171                    let r = self.alloc_reg()?;
2172                    self.emit(Op::LoadConst { dst: r, idx });
2173                    r
2174                }
2175                DrivePiece::Plain(r) => *r,
2176            };
2177            self.emit(Op::Concat {
2178                dst: arg,
2179                lhs: arg,
2180                rhs: part,
2181            });
2182        }
2183        let dst = self.alloc_reg()?;
2184        self.emit(Op::CallBuiltin {
2185            dst,
2186            builtin: crate::semantics::builtins::BuiltinId::Fail,
2187            args_start: arg,
2188            arg_count: 1,
2189        });
2190        Ok(())
2191    }
2192
2193    /// Stop the program with a reason computed at run time: evaluate `reason` into an argument
2194    /// register and call the failing builtin, whose `Err` is the program's error text.
2195    fn emit_fail_builtin(
2196        &mut self,
2197        builtin: crate::semantics::builtins::BuiltinId,
2198        reason: &Expr,
2199    ) -> Result<(), Refusal> {
2200        let arg = self.reserve_regs(1)?;
2201        self.compile_expr_into(reason, arg)?;
2202        let dst = self.alloc_reg()?;
2203        self.emit(Op::CallBuiltin {
2204            dst,
2205            builtin,
2206            args_start: arg,
2207            arg_count: 1,
2208        });
2209        Ok(())
2210    }
2211
2212    /// Compile one statement, then reclaim the scratch registers it allocated.
2213    ///
2214    /// ★ SCRATCH IS DEAD AT THE STATEMENT BOUNDARY — this is where that promise is kept, in every frame (Main,
2215    /// function, closure) and every block (`If`/`While`/`Repeat`/`Inspect` arm, zone, splice). Before it, the
2216    /// only recycler was `exit_block`, which fires when a whole block closes, so a straight-line run of
2217    /// statements never gave a register back: two or three per statement, and the 16,384-register frame ran
2218    /// out near 5,000–8,000 statements — below a single real-width Qwen3.8 tensor fill, and at the same length
2219    /// inside a function or a loop body.
2220    ///
2221    /// What survives a statement is exactly what a NAME holds. So the new floor is the higher of where the
2222    /// statement began and one past the highest register any live binding occupies; everything above it was
2223    /// the statement's own scratch. A binding created by this statement is a live name, so it is kept, and
2224    /// anything from before it — earlier bindings, a loop's iterator, a closure's capture slots — sits below
2225    /// the mark. The floor is never lowered below the mark, so reclaiming can only ever reuse registers this
2226    /// statement itself allocated.
2227    fn compile_stmt(&mut self, s: &Stmt) -> Result<(), Refusal> {
2228        let mark = self.next_reg;
2229        self.lower_stmt(s)?;
2230        self.reclaim_scratch(mark);
2231        Ok(())
2232    }
2233
2234    fn reclaim_scratch(&mut self, mark: Reg) {
2235        let named_top = self
2236            .scopes
2237            .iter()
2238            .flat_map(|scope| scope.values())
2239            .map(|r| *r as usize + 1)
2240            .max()
2241            .unwrap_or(0);
2242        let floor = (mark as usize).max(named_top);
2243        if (self.next_reg as usize) > floor {
2244            self.next_reg = floor as Reg;
2245        }
2246    }
2247
2248    fn alloc_reg(&mut self) -> Result<Reg, Refusal> {
2249        self.reserve_regs(1)
2250    }
2251
2252    /// A drive failure text's operand, known at compile time when `e` is a literal; otherwise a
2253    /// register reserved to hold it, ahead of whatever the value's own register will be. A
2254    /// register at or above a call's `args_start` does not survive the call: `Op::Call`'s callee
2255    /// frame overlays it (`Vm::enter_call`'s `callee_base = self.base + args_start`, free to leave
2256    /// its own locals there on return), and `Op::CallBuiltin` clears its argument registers when
2257    /// it returns. Reserving the keeping register FIRST, before the value's own register, puts it
2258    /// below either, so [`keep_move`](Self::keep_move) can copy the value there once it is known
2259    /// and read it back after the call untouched.
2260    fn keep_operand(&mut self, e: &Expr) -> Result<DriveOperand, Refusal> {
2261        Ok(match e {
2262            Expr::Literal(Literal::Text(sym)) => {
2263                DriveOperand::Known(self.interner.resolve(*sym).to_string())
2264            }
2265            _ => DriveOperand::Held(self.alloc_reg()?),
2266        })
2267    }
2268
2269    /// Copy `src` (the operand's own, about-to-be-unsafe register) into `operand`'s kept register,
2270    /// once its value is known; a no-op for a compile-time-known operand.
2271    fn keep_move(&mut self, operand: &DriveOperand, src: Reg) {
2272        if let DriveOperand::Held(dst) = *operand {
2273            self.emit(Op::Move { dst, src });
2274        }
2275    }
2276
2277    /// Emit a self-tail-call as a LOOP-BACK (TCO): evaluate every argument into a
2278    /// FRESH temp first — so a parameter read by a later argument is never
2279    /// clobbered by an earlier parameter store — then move the temps into the
2280    /// parameter slots `0..param_count` and jump to the function entry. This
2281    /// turns self-tail-recursion into constant-stack iteration (no per-call frame
2282    /// round-trip, no `MAX_CALL_DEPTH` ceiling for tail calls).
2283    fn emit_tail_call(&mut self, args: &[&Expr], entry_pc: usize) -> Result<(), Refusal> {
2284        let mut temps = Vec::with_capacity(args.len());
2285        for a in args {
2286            let t = self.alloc_reg()?;
2287            self.compile_expr_into(a, t)?;
2288            temps.push(t);
2289        }
2290        for (i, t) in temps.into_iter().enumerate() {
2291            if t != i as Reg {
2292                self.emit(Op::Move {
2293                    dst: i as Reg,
2294                    src: t,
2295                });
2296            }
2297        }
2298        self.emit(Op::Jump { target: entry_pc });
2299        Ok(())
2300    }
2301
2302    /// Reserve `n` consecutive registers, returning the first.
2303    fn reserve_regs(&mut self, n: u16) -> Result<Reg, Refusal> {
2304        let start = self.next_reg;
2305        let next = (self.next_reg as usize) + n as usize;
2306        if next > MAX_REGISTERS_PER_FRAME {
2307            return Err(format!(
2308                "vm: out of registers (frame limit is {})",
2309                MAX_REGISTERS_PER_FRAME
2310            )
2311            .into());
2312        }
2313        self.next_reg = next as Reg;
2314        if self.next_reg > self.max_reg {
2315            self.max_reg = self.next_reg;
2316        }
2317        // Scratch reserved inside a loop is a per-iteration temp, dead at the
2318        // loop exit — record it as a loop-local so the region JIT treats it as
2319        // true scratch even when it recycled a (now-dead) named variable's slot
2320        // (the fannkuch `perm[hi]` transfer temp that blocked swap fusion).
2321        if !self.loop_stack.is_empty() {
2322            for r in start..(next as Reg) {
2323                self.record_loop_local(r);
2324            }
2325        }
2326        Ok(start)
2327    }
2328
2329    /// Resolve a mutation-target collection (`Push … to xs`) to its name
2330    /// reference. The caller materializes it (Rc-backed collections mutate
2331    /// through any clone) or emits the unbound failure AFTER the value's side
2332    /// effects, matching the tree-walker.
2333    fn resolve_collection(&mut self, e: &Expr) -> Result<(Symbol, NameRef), Refusal> {
2334        match e {
2335            Expr::Identifier(sym) => Ok((*sym, self.resolve_name(*sym))),
2336            _ => Err("vm: expected an identifier collection".to_string().into()),
2337        }
2338    }
2339
2340    /// Materialize a resolved collection into a register (None = unbound).
2341    fn collection_reg(&mut self, sym: Symbol, nr: &NameRef) -> Result<Option<Reg>, Refusal> {
2342        match nr {
2343            NameRef::Local(r) => Ok(Some(*r)),
2344            NameRef::Unbound => Ok(None),
2345            _ => {
2346                let scratch = self.alloc_reg()?;
2347                self.emit_read(sym, scratch)?;
2348                Ok(Some(scratch))
2349            }
2350        }
2351    }
2352
2353    /// The ONE lowering every mutating statement's target goes through: `Push`/`Add`/`Remove`/
2354    /// `SetIndex`/`SetAdd`/`RemoveFrom`'s collection may be a local, a field, an item, a field of a
2355    /// field, an item of a field, a field of an item — arbitrarily nested. `mutate` receives the
2356    /// register holding the LEAF collection and emits whatever op the statement itself performs;
2357    /// the mutated value is threaded back up through every level to the root binding, so the write
2358    /// always lands where the author's sentence says it does. Returns `Ok(false)` only when the
2359    /// place bottoms out at an unbound name (mirrors `collection_reg`); every other place shape is
2360    /// always "bound" (a non-identifier root, e.g. a call's result, is mutated as a bare value with
2361    /// no place to write back into — unchanged from every statement's own prior fallback).
2362    ///
2363    /// A `FieldAccess`/`Index` step reads its target the ordinary way (`GetField`/`Index`, an `Rc`
2364    /// clone for a List/Map/Set) and then IMMEDIATELY clears its PARENT's own reference to it
2365    /// (`SetIndex` to `Nothing`) before recursing further — so by the time the leaf is reached, the
2366    /// chain's own projection reads have left no trace, and the runtime's ordinary `ensure_reg_owned`
2367    /// gate (already wired into `ListPush`/`SetAdd`/`RemoveFrom`/`SetIndex`) sees a `strong_count`
2368    /// that reflects ONLY a real alias — never the artifact this lowering's own reads would
2369    /// otherwise add. A real alias still forces its own deep clone, exactly as it should; the
2370    /// steady-state, unaliased case never clones at all. Restoring is the same walk in reverse: the
2371    /// mutated (or cloned) leaf is written back into its parent, that parent's own possibly-changed
2372    /// value into ITS parent, and so on to the root — a `Local` root's register IS the binding, so
2373    /// nothing further is needed there; a `Global`/captured root gets one final `emit_write`.
2374    fn compile_place_mutation(
2375        &mut self,
2376        place: &Expr,
2377        mutate: &mut dyn FnMut(&mut Self, Reg) -> Result<(), Refusal>,
2378    ) -> Result<bool, Refusal> {
2379        match place {
2380            Expr::Identifier(sym) => {
2381                let nr = self.resolve_name(*sym);
2382                match self.collection_reg(*sym, &nr)? {
2383                    Some(reg) => {
2384                        // The same "release the binding's own reference before checking
2385                        // ownership" trick, generalized from `Stmt::SetIndex`'s original
2386                        // internal-global case: restricted to a COMPILER-WRITTEN name (an
2387                        // author's global is left on the ordinary path, where an occasional
2388                        // extra clone is the price of the semantics they can observe — see
2389                        // that case's own long-form rationale, unchanged).
2390                        let internal = !matches!(nr, NameRef::Local(_))
2391                            && logicaffeine_language::parser::lgx_lower::is_compiler_written(
2392                                self.interner.resolve(*sym),
2393                            );
2394                        if internal {
2395                            let nothing = self.add_const(Constant::Nothing)?;
2396                            let clear = self.alloc_reg()?;
2397                            self.emit(Op::LoadConst {
2398                                dst: clear,
2399                                idx: nothing,
2400                            });
2401                            self.emit_write(*sym, clear)?;
2402                        }
2403                        mutate(self, reg)?;
2404                        if !matches!(nr, NameRef::Local(_)) {
2405                            self.emit_write(*sym, reg)?;
2406                        }
2407                        Ok(true)
2408                    }
2409                    // Matches every caller's own prior `None` arm: the name is unbound, so the
2410                    // statement unconditionally fails at RUNTIME — `mutate`'s own value/index
2411                    // operands are already compiled by the time this is reached (tree-walker
2412                    // order: evaluate, then look up), so nothing is lost by not calling it.
2413                    None => {
2414                        self.emit_unbound(*sym)?;
2415                        Ok(false)
2416                    }
2417                }
2418            }
2419            _ if Self::place_key_count(place).is_some() => {
2420                let keys = u16::try_from(Self::place_key_count(place).unwrap())
2421                    .map_err(|_| "vm: too many mutation target keys".to_string())?;
2422                let mut next_key = self.reserve_regs(keys)?;
2423                let captured = self
2424                    .compile_lent_place(place, &mut next_key)?
2425                    .expect("a rooted mutation target");
2426                self.mutate_lent_place(&captured, mutate)
2427            }
2428            _ => {
2429                // Not a place at all — a call's result, a literal, any other value-producing
2430                // expression used directly as a mutation target. No binding to write back into;
2431                // mutate the value exactly as it stands, unchanged from every caller's own prior
2432                // catch-all.
2433                let reg = self.compile_expr(place)?;
2434                mutate(self, reg)?;
2435                Ok(true)
2436            }
2437        }
2438    }
2439
2440    /// Bind `sym` for a `Let`: reuse its register when the innermost scope
2441    /// already has it (re-Let overwrites), otherwise allocate a fresh one in
2442    /// the innermost scope (shadowing any outer binding).
2443    /// Record that the op just emitted defines a value the program declares to be `bt`
2444    /// ([`CompiledProgram::declared_types`]).
2445    fn note_declared(&mut self, bt: BoundaryType) {
2446        let pc = self.code.len().saturating_sub(1) as u32;
2447        self.declared_types.push((pc, bt));
2448    }
2449
2450    /// The type a collection construction names: `a new Seq of T`, `a new Set of T`,
2451    /// `a new Map of K to V`. `None` for a record, or for an element type the boundary does not model.
2452    fn declared_collection(
2453        &self,
2454        type_name: Symbol,
2455        type_args: &[crate::ast::stmt::TypeExpr],
2456    ) -> Option<BoundaryType> {
2457        let arg = |i: usize| boundary_of_type_expr(&type_args[i], &self.user_types, self.interner);
2458        match (self.interner.resolve(type_name), type_args.len()) {
2459            ("Seq" | "List", 1) => Some(BoundaryType::Seq(Box::new(arg(0)?))),
2460            ("Set" | "HashSet", 1) => Some(BoundaryType::Set(Box::new(arg(0)?))),
2461            ("Map" | "HashMap", 2) => Some(BoundaryType::Map(Box::new(arg(0)?), Box::new(arg(1)?))),
2462            _ => None,
2463        }
2464    }
2465
2466    /// The type a `Let` binding declares for its value: its annotation (`Let x: Seq of Text be …`),
2467    /// else the declared return type of the function its value calls. A construction declares its
2468    /// own type where it is compiled ([`Compiler::declared_collection`]).
2469    fn declared_binding(
2470        &self,
2471        ty: Option<&crate::ast::stmt::TypeExpr>,
2472        value: &Expr,
2473    ) -> Option<BoundaryType> {
2474        if let Some(ty) = ty {
2475            return boundary_of_type_expr(ty, &self.user_types, self.interner);
2476        }
2477        match value {
2478            Expr::Call { function, .. } => self.return_type_of(*function),
2479            _ => None,
2480        }
2481    }
2482
2483    /// The declared return type of the program's function `f`; `None` for a builtin or a function
2484    /// whose return type the boundary does not model.
2485    fn return_type_of(&self, f: Symbol) -> Option<BoundaryType> {
2486        self.fn_index
2487            .get(&f)
2488            .and_then(|&idx| self.functions[idx as usize].return_type.clone())
2489    }
2490
2491    fn let_reg(&mut self, sym: Symbol) -> Result<Reg, Refusal> {
2492        let r = if let Some(&r) = self.scopes.last().unwrap().get(&sym) {
2493            self.mark_named(r);
2494            r
2495        } else {
2496            let r = self.alloc_reg()?;
2497            self.scopes.last_mut().unwrap().insert(sym, r);
2498            self.mark_named(r);
2499            r
2500        };
2501        self.record_dbg_name(sym, r);
2502        // A consume-alias of a mutable-borrow param (`Let result be arr`): its
2503        // register is COW-exempt, since the in-place writes land on it, not the param.
2504        if self.current_exempt_syms.contains(&sym) && !self.current_exempt_regs.contains(&r) {
2505            self.current_exempt_regs.push(r);
2506        }
2507        Ok(r)
2508    }
2509
2510    /// DEBUG-ONLY: remember that register `r` holds source variable `sym` in the
2511    /// current frame (last name wins after block-scope register reuse). A no-op
2512    /// unless the debugger's compile path enabled name capture.
2513    fn record_dbg_name(&mut self, sym: Symbol, r: Reg) {
2514        if !self.debug_names {
2515            return;
2516        }
2517        match self.dbg_names.iter_mut().find(|(rr, _)| *rr == r) {
2518            Some(slot) => slot.1 = sym,
2519            None => self.dbg_names.push((r, sym)),
2520        }
2521    }
2522
2523    /// Record that `r` carries a user-visible name in the current frame.
2524    fn mark_named(&mut self, r: Reg) {
2525        let i = r as usize;
2526        if self.named.len() <= i {
2527            self.named.resize(i + 1, false);
2528        }
2529        self.named[i] = true;
2530        self.record_loop_local(r);
2531    }
2532
2533    /// Record register `r` as LOCAL to every enclosing loop — lexically dead at
2534    /// each loop's exit — so the region JIT drops it from the write-back set.
2535    /// Called for named bindings (`mark_named`) AND for anonymous scratch
2536    /// reserved inside a loop: a per-iteration temp is dead at the loop exit too,
2537    /// and may have recycled a now-dead named variable's slot (block-scope reuse).
2538    /// Without this, such a temp keeps that slot's stale `named` flag and the
2539    /// region JIT treats it as live — blocking fusions like the swap idiom
2540    /// (fannkuch's `perm[hi]` transfer temp).
2541    fn record_loop_local(&mut self, r: Reg) {
2542        let i = r as usize;
2543        for &head in &self.loop_stack {
2544            let m = self.loop_locals.entry(head).or_default();
2545            if m.len() <= i {
2546                m.resize(i + 1, false);
2547            }
2548            m[i] = true;
2549        }
2550    }
2551
2552    fn add_const(&mut self, c: Constant) -> Result<ConstIdx, Refusal> {
2553        let key = const_key(&c);
2554        if let Some(&idx) = self.const_map.get(&key) {
2555            return Ok(idx);
2556        }
2557        let idx = ConstIdx::try_from(self.constants.len())
2558            .map_err(|_| "vm: constant pool overflow".to_string())?;
2559        self.constants.push(c);
2560        self.const_map.insert(key, idx);
2561        Ok(idx)
2562    }
2563
2564    /// Register an observation site (Wave 13), returning its `Op::Obs { site }`
2565    /// index. Only ever called in the OBSERVED profile.
2566    fn add_obs_site(&mut self, desc: ObsSiteDesc) -> u32 {
2567        let idx = self.observation_sites.len() as u32;
2568        self.observation_sites.push(desc);
2569        idx
2570    }
2571
2572    fn emit(&mut self, op: Op) {
2573        self.code.push(op);
2574    }
2575
2576    fn lower_stmt(&mut self, s: &Stmt) -> Result<(), Refusal> {
2577        match s {
2578            // A runtime failure-site marker (Wave 3): no op, just the pc it stood at — see
2579            // `CompiledProgram::site_at`'s own doc comment.
2580            Stmt::Site(id) => {
2581                self.site_at.push((self.code.len() as u32, *id));
2582                Ok(())
2583            }
2584            // A component is a DECLARATION here: the parser has already lowered a renderable
2585            // view into a `__render_<Name>` function, which compiles like any other. An
2586            // `## Error page` is one too — the router renders it in place of the bare status —
2587            // unless the server-side walk cannot render its template, which is refused at the
2588            // node the walk refused. This guard sits BEFORE the general arm below, which would
2589            // otherwise take every component first.
2590            Stmt::ComponentDef(def)
2591                if matches!(
2592                    def.kind,
2593                    crate::ast::component::ComponentKind::ErrorPage { .. }
2594                ) =>
2595            {
2596                error_page_refusal(def, self.interner).map_or(Ok(()), Err)
2597            }
2598            Stmt::ComponentDef(_) => Ok(()),
2599            // `Mount App [at "#sel"].` — resolve the mount point, then call the lowered render
2600            // function. A component whose view needs the runtime has none, and this refuses by
2601            // name rather than rendering part of a page.
2602            Stmt::Ui(crate::ast::stmt::UiStmt::Mount {
2603                component,
2604                selector,
2605            }) => {
2606                let name = self.interner.resolve(*component).to_string();
2607                let fn_name =
2608                    self.interner
2609                        .lookup(&logicaffeine_language::parser::lgx_lower::mount_fn_name(
2610                            &name,
2611                        ));
2612                let func = fn_name.and_then(|s| self.fn_index.get(&s).copied());
2613                let Some(func) = func else {
2614                    return Err(self
2615                        .mount_refusals
2616                        .get(component)
2617                        .cloned()
2618                        .unwrap_or_else(|| {
2619                            format!(
2620                            "`Mount {name}` cannot run on this tier: this file does not declare it \
2621                             as a mountable component."
2622                        )
2623                            .into()
2624                        }));
2625                };
2626                let parent = self.alloc_reg()?;
2627                match selector {
2628                    None => self.emit(Op::CallBuiltin {
2629                        dst: parent,
2630                        builtin: crate::semantics::builtins::BuiltinId::DomBody,
2631                        args_start: 0,
2632                        arg_count: 0,
2633                    }),
2634                    Some(sel) => {
2635                        // `querySelector` answers -1 when nothing matches, and a page appended to
2636                        // -1 would parent every node to a node that is not there while reporting
2637                        // success. The failure is raised here — where the selector's text is
2638                        // known — in the reference tier's words; a non-literal selector is kept
2639                        // where `CallBuiltin`'s post-return argument clear cannot reach it.
2640                        let selector = self.keep_operand(sel)?;
2641                        let arg = self.reserve_regs(1)?;
2642                        self.compile_expr_into(sel, arg)?;
2643                        self.keep_move(&selector, arg);
2644                        self.emit(Op::CallBuiltin {
2645                            dst: parent,
2646                            builtin: crate::semantics::builtins::BuiltinId::DomQuerySelector,
2647                            args_start: arg,
2648                            arg_count: 1,
2649                        });
2650                        let missing_text = DriveText::render(
2651                            |s, _| crate::semantics::drive::mount_target_missing(&name, s),
2652                            &selector,
2653                            None,
2654                        );
2655                        let zero = self.alloc_reg()?;
2656                        let zidx = self.add_const(Constant::Int(0))?;
2657                        self.emit(Op::LoadConst {
2658                            dst: zero,
2659                            idx: zidx,
2660                        });
2661                        let missing = self.alloc_reg()?;
2662                        self.emit(Op::Lt {
2663                            dst: missing,
2664                            lhs: parent,
2665                            rhs: zero,
2666                        });
2667                        let ok = self.code.len();
2668                        self.emit(Op::JumpIfFalse {
2669                            cond: missing,
2670                            target: usize::MAX,
2671                        });
2672                        self.emit_fail_text(&missing_text)?;
2673                        self.patch_jump_target(ok, self.current_pc())?;
2674                    }
2675                }
2676                let args_start = self.reserve_regs(1)?;
2677                self.emit(Op::Move {
2678                    dst: args_start,
2679                    src: parent,
2680                });
2681                let dst = self.alloc_reg()?;
2682                self.emit(Op::Call {
2683                    dst,
2684                    func,
2685                    args_start,
2686                    arg_count: 1,
2687                });
2688                Ok(())
2689            }
2690            // The driving verbs route through the synthesized dispatcher, which the parser
2691            // built from the handlers the views attach. This tier cannot call a closure it
2692            // found at run time, so the routing is decided where the handlers are known.
2693            // ★ `Raise "offline".` — a WINDOW event, delivered to the page. It routes through the
2694            // same dispatcher every other driving verb uses; what differs is that the page always
2695            // exists and an unanswered raise is not a mistake, so `__lgx_raise` reports "answered"
2696            // whatever happened and this never raises the "nothing answers" failure.
2697            Stmt::Ui(crate::ast::stmt::UiStmt::RaiseWindowEvent {
2698                event,
2699                target,
2700                value,
2701            }) => {
2702                // ★ A PAGE THAT ANSWERS NOTHING STILL ACCEPTS A RAISE. Every other driving verb
2703                // fails when the program has no dispatcher, and rightly: clicking an element
2704                // nothing listens to is a test naming the wrong element. Going offline is not
2705                // something the page did, and a page is entitled to ignore it — the reference tier
2706                // says exactly that by delivering with `must_answer: false`. With no dispatcher
2707                // there is nothing to call and nothing to report, so this compiles to nothing.
2708                let driver = logicaffeine_language::parser::lgx_lower::raise_fn_name();
2709                match self
2710                    .interner
2711                    .lookup(driver)
2712                    .and_then(|s| self.fn_index.get(&s).copied())
2713                {
2714                    Some(func) => self.compile_page_drive(func, &[target, event, value]),
2715                    None => Ok(()),
2716                }
2717            }
2718            Stmt::Ui(crate::ast::stmt::UiStmt::Click { selector }) => {
2719                self.compile_lgx_drive(crate::semantics::drive::Verb::Click, selector, None, None)
2720            }
2721            // A press with no selector goes to the page; the parser fills in that selector, so
2722            // both forms arrive here the same shape.
2723            Stmt::Ui(crate::ast::stmt::UiStmt::Press {
2724                key,
2725                selector: Some(selector),
2726            }) => self.compile_lgx_drive(
2727                crate::semantics::drive::Verb::Press,
2728                selector,
2729                Some(key),
2730                Some(key),
2731            ),
2732            Stmt::Ui(crate::ast::stmt::UiStmt::TypeInto { text, selector }) => self
2733                .compile_lgx_drive(
2734                    crate::semantics::drive::Verb::Type,
2735                    selector,
2736                    Some(text),
2737                    None,
2738                ),
2739            // `Submit SEL.` had the AST, the parser and the reference tier and NO lowering here,
2740            // so it fell through to the generic refusal below — a verb that looked landed and
2741            // only ever worked on one tier.
2742            Stmt::Ui(crate::ast::stmt::UiStmt::Submit { selector }) => {
2743                self.compile_lgx_drive(crate::semantics::drive::Verb::Submit, selector, None, None)
2744            }
2745            Stmt::Ui(crate::ast::stmt::UiStmt::Choose { value, selector }) => self
2746                .compile_lgx_drive(
2747                    crate::semantics::drive::Verb::Choose,
2748                    selector,
2749                    Some(value),
2750                    None,
2751                ),
2752            // A directive is a declaration: nothing to emit here, and a component that uses one
2753            // is refused where it MOUNTS, by name — which is the message worth reading.
2754            Stmt::DirectiveDef { .. } => Ok(()),
2755            // A `## Route` whose body lowered to a function is a DECLARATION here — the function
2756            // carries it, and `route(method, path)` dispatches. One that could not lower is
2757            // refused BY NAME, saying which part is missing, rather than silently never being
2758            // reachable through the dispatcher (which would read as a 404 for a route the author
2759            // can see in their file).
2760            Stmt::RouteDef { method, path, .. } => match self.route_refusals.get(&(*method, *path))
2761            {
2762                None => Ok(()),
2763                Some(refusal) => Err(refusal.clone()),
2764            },
2765            // A `## Before each request` is a DECLARATION here — it lowered to a function and
2766            // `route(method, path)` calls it before matching.
2767            Stmt::MiddlewareDef { .. } => Ok(()),
2768            // A `## Redirect` is a DECLARATION — the router carries it.
2769            Stmt::RedirectDef { .. } => Ok(()),
2770            // A typed request is REFUSED BY NAME, not left to the generic message below. Its
2771            // answer arrives in a CLOSURE, and this tier cannot call a closure it found at run
2772            // time — the same constraint that made the driving verbs route through a synthesized
2773            // dispatcher. Saying that is worth more than "the remaining action verbs".
2774            Stmt::Fetch { .. } => Err(
2775                "a typed request (`Get … as T, then action.`) cannot run on this tier yet: its \
2776                 answer arrives in a closure, and this tier cannot call a closure it found at \
2777                 run time. Drive the page on the tree-walker, or answer the request with a \
2778                 `Given that …` stub in a test."
2779                    .to_string()
2780                    .into(),
2781            ),
2782            // An `Actions:` verb with no lowering on this tier is refused by its own sentence
2783            // (`action_verb_tier_lock` holds the catalogue of which verbs lower). The tree-walker
2784            // runs every one of them, so the browser build is the one place such a gap shows, and
2785            // the refusal has to say WHICH sentence.
2786            Stmt::Ui(u) => Err(format!(
2787                "`{}` cannot run in a browser yet: it is an `Actions:` verb this tier has no \
2788                 lowering for. It works on the tree-walker (`largo test` runs it), so a page using \
2789                 it renders in a test and fails to build for the browser — rewrite that sentence, \
2790                 or drive it from a `## Test`.",
2791                ui_verb_phrase(u)
2792            )
2793            .into()),
2794            Stmt::GivenFetch { .. } | Stmt::ServeFetches | Stmt::Replay { .. } => {
2795                // The SAME words the tree-walker uses. Two tiers refusing the same construct
2796                // differently is a small thing that costs real time: whoever reads one message
2797                // and searches for it does not find the other.
2798                Err(
2799                    "LGX routes and the remaining action verbs are not executable on this tier yet"
2800                        .to_string()
2801                        .into(),
2802                )
2803            }
2804            Stmt::Splice { body } => {
2805                // Scope-transparent desugar output: compile the statements in
2806                // order, no scope of their own (temporaries are gensym'd).
2807                for inner in body.iter() {
2808                    self.compile_stmt(inner)?;
2809                }
2810                Ok(())
2811            }
2812            Stmt::Reversibly { body } => {
2813                // Output-transparent block: the body compiles in the enclosing scope, but while
2814                // `reversible_depth` is positive an in-place abelian scalar update lowers to the
2815                // zero-garbage reversible ISA (`Op::RevAdd`/`RevSub`/`RevXor`/`RevNeg`) rather than
2816                // the plain journaling op — so the region reverses with no history tape. The
2817                // FORWARD result is identical to the same statements outside the block.
2818                self.reversible_depth += 1;
2819                let result = (|| {
2820                    for inner in body.iter() {
2821                        self.compile_stmt(inner)?;
2822                    }
2823                    Ok(())
2824                })();
2825                self.reversible_depth -= 1;
2826                result
2827            }
2828            Stmt::Let { var, ty, value, .. } => {
2829                // A promoted Main TOP-LEVEL Let defines the global; everywhere
2830                // else (function bodies, Main blocks — which shadow) a
2831                // register binding.
2832                if !self.in_function && self.scopes.len() == 1 && self.promoted.contains_key(var) {
2833                    let scratch = self.alloc_reg()?;
2834                    self.compile_expr_into(value, scratch)?;
2835                    let idx = self.promoted[var];
2836                    self.emit(Op::GlobalSet { idx, src: scratch });
2837                    return Ok(());
2838                }
2839                // `Let var be a new Seq/Set/Map` (a fresh EMPTY collection):
2840                // bind first and construct directly into the var's register.
2841                // An empty constructor reads nothing, so the
2842                // evaluate-in-old-environment rule below is moot — and writing
2843                // into the var's stable register lets the loop-carried reuse
2844                // path (NewEmptyList over a sole-owned buffer) fire across
2845                // iterations instead of allocating fresh every pass.
2846                if let Expr::New {
2847                    type_name,
2848                    init_fields,
2849                    type_args,
2850                } = value
2851                {
2852                    if init_fields.is_empty()
2853                        && matches!(
2854                            self.interner.resolve(*type_name),
2855                            "Seq" | "List" | "Set" | "HashSet" | "Map" | "HashMap"
2856                        )
2857                    {
2858                        let dst = self.let_reg(*var)?;
2859                        // A narrowing-proven `new Seq of Int` allocates the
2860                        // half-width (`Vec<i32>`) buffer directly into the var's
2861                        // stable register (so the loop-carried reuse path fires).
2862                        let fixed_key = (self.tail_fn.map(|(function, _, _)| function), *var);
2863                        if matches!(self.interner.resolve(*type_name), "Seq" | "List")
2864                            && self.fixed_seq_caps.contains_key(&fixed_key)
2865                        {
2866                            let capacity =
2867                                u16::try_from(self.fixed_seq_caps[&fixed_key]).map_err(|_| {
2868                                    "vm: fixed sequence capacity exceeds 65535".to_string()
2869                                })?;
2870                            self.emit(Op::NewEmptyListFixed { dst, capacity });
2871                            if let Some(bt) = self.declared_collection(*type_name, type_args) {
2872                                self.note_declared(bt);
2873                            }
2874                        } else if self.narrowable_seqs.contains(var)
2875                            && matches!(self.interner.resolve(*type_name), "Seq" | "List")
2876                        {
2877                            self.emit(Op::NewEmptyListI32 { dst });
2878                            if let Some(bt) = self.declared_collection(*type_name, type_args) {
2879                                self.note_declared(bt);
2880                            }
2881                        } else {
2882                            self.compile_expr_into(value, dst)?;
2883                        }
2884                        return Ok(());
2885                    }
2886                }
2887                // The value is evaluated BEFORE the new binding exists (the
2888                // tree-walker evaluates in the old environment): `Let x be
2889                // x + 1` in a block reads the OUTER x. Compile into a scratch
2890                // register first, then bind.
2891                let scratch = self.alloc_reg()?;
2892                self.compile_expr_into(value, scratch)?;
2893                let dst = self.let_reg(*var)?;
2894                self.emit(Op::Move { dst, src: scratch });
2895                if let Some(bt) = self.declared_binding(*ty, value) {
2896                    self.note_declared(bt);
2897                }
2898                Ok(())
2899            }
2900            Stmt::Swap { a, b } => {
2901                // The zero-garbage reversible register exchange. Two distinct locals emit the abelian
2902                // `RevSwap` directly (its own inverse, no history-tape cost); equal names are a no-op;
2903                // anything else (e.g. a promoted global) falls back to a correct temp-mediated swap.
2904                match (self.resolve_name(*a), self.resolve_name(*b)) {
2905                    (NameRef::Local(ra), NameRef::Local(rb)) => {
2906                        if ra != rb {
2907                            self.emit(Op::RevSwap { a: ra, b: rb });
2908                        }
2909                    }
2910                    _ => {
2911                        let ta = self.alloc_reg()?;
2912                        self.emit_read(*a, ta)?;
2913                        let tb = self.alloc_reg()?;
2914                        self.emit_read(*b, tb)?;
2915                        self.emit_write(*a, tb)?;
2916                        self.emit_write(*b, ta)?;
2917                    }
2918                }
2919                Ok(())
2920            }
2921            Stmt::Set { target, value } => {
2922                match self.resolve_name(*target) {
2923                    NameRef::Local(dst) => {
2924                        // Inside a `Reversibly:` block, an in-place abelian scalar update lowers to
2925                        // the zero-garbage reversible ISA (`RevAdd`/`RevSub`/`RevXor`/`RevNeg`). The
2926                        // FORWARD result is identical to the plain lowering below, so program output
2927                        // is unchanged; only the emitted ops (and their tape-free reversibility)
2928                        // differ. Declines (falls through) for any non-abelian value form.
2929                        if self.reversible_depth > 0
2930                            && self.try_emit_reversible_set(*target, dst, value)?
2931                        {
2932                            return Ok(());
2933                        }
2934                        // `Set x to x + e1 + … + ek`: lower to an AddAssign
2935                        // chain (in-place Text append; identical fold for
2936                        // every other type). Only when each later term
2937                        // provably never observes x — see add_assign_chain.
2938                        if let Some(terms) = add_assign_chain(*target, value) {
2939                            for term in terms {
2940                                let scratch = self.alloc_reg()?;
2941                                self.compile_expr_into(term, scratch)?;
2942                                self.emit(Op::AddAssign { dst, src: scratch });
2943                            }
2944                            return Ok(());
2945                        }
2946                        // `Set x to f(…)`: compile the call straight into `x`. A call
2947                        // writes its destination LAST (after its arguments are read into
2948                        // the arg window), so `x` is never clobbered before use — even
2949                        // in the self-consuming `Set x to f(x, …)` shape. This avoids a
2950                        // scratch whose lingering `Rc` clone would leave `x` spuriously
2951                        // shared (`strong == 2`) and force the next mutable-borrow call's
2952                        // `EnsureOwned` barrier to deep-clone every iteration (the
2953                        // heap_sort O(n²) collapse under value semantics). Skipped when
2954                        // `x` is a COW-exempt local (its writes never clone anyway) so a
2955                        // self-recursive function's tier-able body is left untouched.
2956                        if matches!(value, Expr::Call { .. })
2957                            && !self.current_exempt_syms.contains(target)
2958                        {
2959                            self.compile_expr_into(value, dst)?;
2960                            return Ok(());
2961                        }
2962                        // Never compile directly into the live target: a
2963                        // multi-op value (interpolation accumulation, branch
2964                        // joins) would clobber the register before reading it
2965                        // — `Set result to "{result}{s}"` must accumulate.
2966                        let scratch = self.alloc_reg()?;
2967                        self.compile_expr_into(value, scratch)?;
2968                        self.emit(Op::Move { dst, src: scratch });
2969                        Ok(())
2970                    }
2971                    NameRef::Unbound => {
2972                        // The tree-walker evaluates the value FIRST (its side
2973                        // effects happen), then fails the assignment — and only
2974                        // when the statement actually executes.
2975                        let scratch = self.alloc_reg()?;
2976                        self.compile_expr_into(value, scratch)?;
2977                        self.emit_unbound(*target)
2978                    }
2979                    _ => {
2980                        let scratch = self.alloc_reg()?;
2981                        self.compile_expr_into(value, scratch)?;
2982                        self.emit_write(*target, scratch)
2983                    }
2984                }
2985            }
2986            Stmt::Return { value } => {
2987                // A Zone swallows Return (the tree-walker discards the zone
2988                // body's ControlFlow): jump to the zone's end instead of
2989                // returning, popping the iterator of every Repeat crossed.
2990                let zone_pos = self
2991                    .flow_stack
2992                    .iter()
2993                    .rposition(|c| matches!(c, FlowCtx::Zone { .. }));
2994                if let Some(pos) = zone_pos {
2995                    if let Some(e) = value {
2996                        let scratch = self.alloc_reg()?;
2997                        self.compile_expr_into(e, scratch)?;
2998                    }
2999                    let crossed_repeats = self.flow_stack[pos + 1..]
3000                        .iter()
3001                        .filter(|c| {
3002                            matches!(
3003                                c,
3004                                FlowCtx::Loop {
3005                                    is_repeat: true,
3006                                    ..
3007                                }
3008                            )
3009                        })
3010                        .count();
3011                    for _ in 0..crossed_repeats {
3012                        self.emit(Op::IterPop);
3013                    }
3014                    let j = self.code.len();
3015                    self.emit(Op::Jump { target: usize::MAX });
3016                    if let FlowCtx::Zone { exits } = &mut self.flow_stack[pos] {
3017                        exits.push(j);
3018                    }
3019                } else if self.in_function {
3020                    match value {
3021                        Some(e) => {
3022                            // A NAMED-RECORD return of a tuple literal `(a, b)` builds a self-describing struct
3023                            // with the record's field names, so `r's quotient` resolves via ordinary struct
3024                            // field access — mirroring the interpreter's `coerce_record_return`.
3025                            if let Some(crate::ast::stmt::TypeExpr::Record {
3026                                field_names, ..
3027                            }) = self.current_return_type
3028                            {
3029                                if let Expr::Tuple(items) = e {
3030                                    if field_names.len() == items.len() {
3031                                        let dst = self.alloc_reg()?;
3032                                        let name_idx =
3033                                            self.add_const(Constant::Text("Record".to_string()))?;
3034                                        self.emit(Op::NewStruct {
3035                                            dst,
3036                                            type_name: name_idx,
3037                                        });
3038                                        for (n, item) in field_names.iter().zip(items.iter()) {
3039                                            let fname = self.interner.resolve(*n).to_string();
3040                                            let fidx = self.add_const(Constant::Text(fname))?;
3041                                            let v = self.compile_expr(item)?;
3042                                            self.emit(Op::StructInsert {
3043                                                obj: dst,
3044                                                field: fidx,
3045                                                value: v,
3046                                            });
3047                                        }
3048                                        self.emit(Op::Return { src: dst });
3049                                        return Ok(());
3050                                    }
3051                                }
3052                            }
3053                            // TCO: a direct self-tail-call `Return self(args)` is
3054                            // inherently in tail position — lower it to the
3055                            // loop-back (reassign params + jump to entry) instead
3056                            // of a real call + return.
3057                            if let Some((tf, entry_pc, pc)) = self.tail_fn {
3058                                // Do NOT TCO across a `Repeat` (for-in): the
3059                                // loop-back jump would skip its `IterPop`,
3060                                // stacking abandoned iterators. (A `While`
3061                                // holds no runtime state, so jumping out of it
3062                                // is fine; `Zone`s are handled above.)
3063                                let in_repeat = self.flow_stack.iter().any(|c| {
3064                                    matches!(
3065                                        c,
3066                                        FlowCtx::Loop {
3067                                            is_repeat: true,
3068                                            ..
3069                                        }
3070                                    )
3071                                });
3072                                if !in_repeat {
3073                                    if let Some(args) =
3074                                        crate::tail_call::direct_self_tail_args(*e, tf, pc as usize)
3075                                    {
3076                                        self.emit_tail_call(args, entry_pc)?;
3077                                        return Ok(());
3078                                    }
3079                                }
3080                            }
3081                            let src = self.compile_expr(e)?;
3082                            self.emit(Op::Return { src });
3083                        }
3084                        None => self.emit(Op::ReturnNothing),
3085                    }
3086                } else {
3087                    // Return at Main top level = stop the program (the value's
3088                    // side effects still happen first).
3089                    if let Some(e) = value {
3090                        let scratch = self.alloc_reg()?;
3091                        self.compile_expr_into(e, scratch)?;
3092                    }
3093                    self.emit(Op::Halt);
3094                }
3095                Ok(())
3096            }
3097            Stmt::Break => {
3098                // The innermost Loop or Zone catches it, whichever is nearer.
3099                match self.flow_stack.last_mut() {
3100                    Some(FlowCtx::Loop { breaks, .. }) => {
3101                        let j = self.code.len();
3102                        breaks.push(j);
3103                        self.emit(Op::Jump { target: usize::MAX });
3104                    }
3105                    Some(FlowCtx::Zone { .. }) => {
3106                        let j = self.code.len();
3107                        self.emit(Op::Jump { target: usize::MAX });
3108                        if let Some(FlowCtx::Zone { exits }) = self.flow_stack.last_mut() {
3109                            exits.push(j);
3110                        }
3111                    }
3112                    None => {
3113                        if self.in_function {
3114                            // A Break with no enclosing loop ends the function
3115                            // body (the tree-walker's call loop treats Break
3116                            // as "stop executing the body").
3117                            self.emit(Op::ReturnNothing);
3118                        } else {
3119                            // At Main top level it stops the program.
3120                            self.emit(Op::Halt);
3121                        }
3122                    }
3123                }
3124                Ok(())
3125            }
3126            Stmt::Call { function, args } => {
3127                // A call used for its effect; the result register is discarded.
3128                let dst = self.alloc_reg()?;
3129                self.compile_call(*function, args, dst)
3130            }
3131            Stmt::Push { value, collection } => {
3132                // Value evaluated before the place (matches the tree-walker's `Stmt::Push`);
3133                // `compile_place_mutation` handles an unbound root itself.
3134                let val = self.compile_expr_before(value, &[collection])?;
3135                // FAST PATH: `Push V to <name>'s <field>.` with `<name>` a local — the ONE shape
3136                // `Op::ListPushField` exists for. It pushes onto the field of the record in the
3137                // binding's OWN register, taking the field's list for that record first when
3138                // another value shares it (a copy of the record, a plain parameter's caller), so
3139                // the push is seen through this binding and no other. A global or a capture is
3140                // read into a scratch copy, where a push would be lost; those take the general
3141                // place mechanism, which writes the record back. Kept as its own op rather than
3142                // folded into the general mechanism: every other backend (RISC-V/C/wasm/SVA/DRAM)
3143                // still lowers this op, and letting it go unemitted silently breaks their own
3144                // coverage censuses.
3145                if let Expr::FieldAccess {
3146                    object: Expr::Identifier(obj_sym),
3147                    field,
3148                } = collection
3149                {
3150                    if let NameRef::Local(obj) = self.resolve_name(*obj_sym) {
3151                        let name = self.interner.resolve(*field).to_string();
3152                        let fidx = self.add_const(Constant::Text(name))?;
3153                        self.emit(Op::ListPushField {
3154                            obj,
3155                            field: fidx,
3156                            src: val,
3157                        });
3158                        return Ok(());
3159                    }
3160                }
3161                self.compile_place_mutation(collection, &mut |c, list| {
3162                    c.emit(Op::ListPush { list, value: val });
3163                    Ok(())
3164                })?;
3165                Ok(())
3166            }
3167            Stmt::Add { value, collection } => {
3168                // Value evaluated before the place (matches the tree-walker's `Stmt::Add`).
3169                let val = self.compile_expr_before(value, &[collection])?;
3170                self.compile_place_mutation(collection, &mut |c, set| {
3171                    c.emit(Op::SetAdd { set, value: val });
3172                    Ok(())
3173                })?;
3174                Ok(())
3175            }
3176            Stmt::Remove { value, collection } => {
3177                // Value evaluated before the place (matches the tree-walker's `Stmt::Remove`).
3178                let val = self.compile_expr_before(value, &[collection])?;
3179                self.compile_place_mutation(collection, &mut |c, coll| {
3180                    c.emit(Op::RemoveFrom {
3181                        collection: coll,
3182                        value: val,
3183                    });
3184                    Ok(())
3185                })?;
3186                Ok(())
3187            }
3188            Stmt::SetIndex {
3189                collection,
3190                index,
3191                value,
3192            } => {
3193                // Tree-walker order: index, then value, then the place itself.
3194                let proven = self.index_in_bounds(collection, index);
3195                let idx = self.compile_expr_before(index, &[value, collection])?;
3196                let val = self.compile_expr_before(value, &[collection])?;
3197                self.compile_place_mutation(collection, &mut |c, coll| {
3198                    if proven {
3199                        c.emit(Op::SetIndexUnchecked {
3200                            collection: coll,
3201                            index: idx,
3202                            value: val,
3203                        });
3204                    } else {
3205                        c.emit(Op::SetIndex {
3206                            collection: coll,
3207                            index: idx,
3208                            value: val,
3209                        });
3210                    }
3211                    Ok(())
3212                })?;
3213                Ok(())
3214            }
3215            Stmt::Show { object, recipient } => {
3216                if let Expr::Identifier(sym) = recipient {
3217                    self.compile_recipient_call(*sym, object)
3218                } else {
3219                    // Non-identifier recipient: the tree-walker still evaluates
3220                    // the object (side effects), then silently moves on.
3221                    let scratch = self.alloc_reg()?;
3222                    self.compile_expr_into(object, scratch)?;
3223                    Ok(())
3224                }
3225            }
3226            Stmt::Give { object, recipient } => {
3227                if let Expr::Identifier(sym) = recipient {
3228                    self.compile_recipient_call(*sym, object)
3229                } else {
3230                    // Non-identifier recipient: the tree-walker evaluates the
3231                    // object (side effects) and silently moves on.
3232                    let scratch = self.alloc_reg()?;
3233                    self.compile_expr_into(object, scratch)?;
3234                    Ok(())
3235                }
3236            }
3237            Stmt::If {
3238                cond,
3239                then_block,
3240                else_block,
3241            } => {
3242                let c = self.compile_expr(cond)?;
3243                let jif = self.emit_placeholder_jump_if_false(c);
3244                let mark = self.enter_block();
3245                for st in *then_block {
3246                    self.compile_stmt(st)?;
3247                }
3248                self.exit_block(mark);
3249                match else_block {
3250                    Some(eb) => {
3251                        let jend = self.emit_placeholder_jump();
3252                        self.patch_jump_target(jif, self.current_pc())?;
3253                        let mark = self.enter_block();
3254                        for st in *eb {
3255                            self.compile_stmt(st)?;
3256                        }
3257                        self.exit_block(mark);
3258                        self.patch_jump_target(jend, self.current_pc())?;
3259                    }
3260                    None => {
3261                        self.patch_jump_target(jif, self.current_pc())?;
3262                    }
3263                }
3264                Ok(())
3265            }
3266            Stmt::While { cond, body, .. } => {
3267                // Region-entry bounds hoists go at the loop head (the back-edge
3268                // target), so they fall inside any region formed for the loop.
3269                let loop_start = self.current_pc();
3270                // Track names bound inside this loop body (the region head is
3271                // `loop_start`, the back-edge target) so the JIT can treat them
3272                // as dead-at-exit scratch. Pushed before the cond (re-evaluated
3273                // each iteration, so cond-bound names are loop-local too).
3274                self.loop_stack.push(loop_start);
3275                let enabled = self.emit_hoist_guards(s);
3276                self.hoist_enabled.push(enabled);
3277                let c = self.compile_expr(cond)?;
3278                let jexit = self.emit_placeholder_jump_if_false(c);
3279                self.flow_stack.push(FlowCtx::Loop {
3280                    breaks: Vec::new(),
3281                    is_repeat: false,
3282                });
3283                let mark = self.enter_block();
3284                let buffer_swap = detect_loop_buffer_swap(body, self.interner);
3285                for (body_idx, st) in body.iter().enumerate() {
3286                    if let Some(reuse) = buffer_swap.filter(|reuse| reuse.set_idx == body_idx) {
3287                        if let (NameRef::Local(inner), NameRef::Local(outer)) = (
3288                            self.resolve_name(reuse.inner),
3289                            self.resolve_name(reuse.outer),
3290                        ) {
3291                            if inner != outer {
3292                                self.emit(Op::RevSwap { a: outer, b: inner });
3293                                crate::optimize::mark_fired(crate::optimization::Opt::Peephole);
3294                                continue;
3295                            }
3296                        }
3297                    }
3298                    self.compile_stmt(st)?;
3299                }
3300                self.exit_block(mark);
3301                self.hoist_enabled.pop();
3302                self.loop_stack.pop();
3303                self.emit(Op::Jump { target: loop_start });
3304                let exit_pc = self.current_pc();
3305                self.patch_jump_target(jexit, exit_pc)?;
3306                if let Some(FlowCtx::Loop { breaks, .. }) = self.flow_stack.pop() {
3307                    for j in breaks {
3308                        self.patch_jump_target(j, exit_pc)?;
3309                    }
3310                }
3311                Ok(())
3312            }
3313            Stmt::Repeat {
3314                pattern,
3315                iterable,
3316                body,
3317            } => self.compile_repeat(s, pattern, iterable, body),
3318            Stmt::Pop { collection, into } => {
3319                if !matches!(collection, Expr::Identifier(_)) {
3320                    // A list in a field or an item (`Pop from c's tags.`): the place mechanism takes
3321                    // it out, pops, and puts it back, whatever holds it.
3322                    let dst = match into {
3323                        Some(var) => self.let_reg(*var)?,
3324                        None => self.alloc_reg()?,
3325                    };
3326                    self.compile_place_mutation(collection, &mut |c, list| {
3327                        c.emit(Op::ListPop { list, dst });
3328                        Ok(())
3329                    })?;
3330                    return Ok(());
3331                }
3332                let (sym, nr) = self.resolve_collection(collection)?;
3333                match self.collection_reg(sym, &nr)? {
3334                    Some(list) => {
3335                        let dst = match into {
3336                            Some(var) => self.let_reg(*var)?,
3337                            None => self.alloc_reg()?,
3338                        };
3339                        self.emit(Op::ListPop { list, dst });
3340                        if !matches!(nr, NameRef::Local(_)) {
3341                            self.emit_write(sym, list)?;
3342                        }
3343                        Ok(())
3344                    }
3345                    None => self.emit_unbound(sym),
3346                }
3347            }
3348            Stmt::RuntimeAssert {
3349                condition, reason, ..
3350            } => {
3351                let c = self.compile_expr(condition)?;
3352                let jok = self.code.len();
3353                self.emit(Op::JumpIfTrue {
3354                    cond: c,
3355                    target: usize::MAX,
3356                });
3357                match reason {
3358                    // A CONSTANT reason is the message itself (`contract_reason_text` of a Text is that Text),
3359                    // so it needs no builtin: the core `FailWith` op carries it, and every tier that lowers
3360                    // from bytecode reports the same words.
3361                    Some(Expr::Literal(Literal::Text(sym))) => {
3362                        let idx = self
3363                            .add_const(Constant::Text(self.interner.resolve(*sym).to_string()))?;
3364                        self.emit(Op::FailWith { msg: idx });
3365                    }
3366                    Some(r) => self
3367                        .emit_fail_builtin(crate::semantics::builtins::BuiltinId::FailReason, r)?,
3368                    None => {
3369                        let idx = self.add_const(Constant::Text("Assertion failed".to_string()))?;
3370                        self.emit(Op::FailWith { msg: idx });
3371                    }
3372                }
3373                self.patch_jump_target(jok, self.current_pc())?;
3374                Ok(())
3375            }
3376            Stmt::Fail { reason } => {
3377                self.emit_fail_builtin(crate::semantics::builtins::BuiltinId::Fail, reason)
3378            }
3379            // A `## Test` block is a declaration — the VM emits nothing for it;
3380            // the `largo test` runner drives test bodies itself (Wave 3).
3381            Stmt::TestDef { .. } => Ok(()),
3382            // `Advance time by …` drives the page's timers through the same function a browser's
3383            // interval calls. Where the program has no timers there is no tick to call, and it is
3384            // a test-only statement that compiles away.
3385            Stmt::AdvanceTime { millis }
3386                if self
3387                    .interner
3388                    .lookup(logicaffeine_language::parser::lgx_lower::tick_fn_name())
3389                    .and_then(|s| self.fn_index.get(&s).copied())
3390                    .is_some() =>
3391            {
3392                let tick = self
3393                    .interner
3394                    .lookup(logicaffeine_language::parser::lgx_lower::tick_fn_name())
3395                    .and_then(|s| self.fn_index.get(&s).copied())
3396                    .ok_or_else(|| {
3397                        Refusal::from("vm: the page clock's tick is not compiled".to_string())
3398                    })?;
3399                self.compile_page_drive(tick, &[millis])
3400            }
3401            // Test-only statements are parser-gated to `## Test` bodies; the
3402            // main program's bytecode can never contain them.
3403            Stmt::Expect { .. }
3404            | Stmt::ExpectFail { .. }
3405            | Stmt::ExpectOutput { .. }
3406            | Stmt::AdvanceTime { .. }
3407            | Stmt::GivenFile { .. }
3408            | Stmt::ForAll { .. } => {
3409                if self.test_noop {
3410                    // `--tiers all`: the test's assertions are the interpreter's
3411                    // authoritative verdict; here the VM runs the computation
3412                    // around them, so these compile away.
3413                    Ok(())
3414                } else {
3415                    Err("test-only statement outside the test runner (`largo test` lands in Wave 3)"
3416                        .to_string().into())
3417                }
3418            }
3419            // Observation (Wave 13). OBSERVED profile ⇒ lower to `Op::Obs` so the
3420            // VM emits the tree-walker's event stream; ELIDED profile ⇒ erase
3421            // (`During` is scope-transparent — its body compiles inline).
3422            Stmt::Observe {
3423                category,
3424                message,
3425                payloads,
3426                sample,
3427            } => {
3428                if self.emit_observation {
3429                    let count = u16::try_from(payloads.len()).map_err(|_| {
3430                        "vm: observation has too many payloads (max 65535)".to_string()
3431                    })?;
3432                    let start = if count > 0 {
3433                        self.reserve_regs(count)?
3434                    } else {
3435                        0
3436                    };
3437                    let mut names = Vec::with_capacity(payloads.len());
3438                    for (i, (name, expr)) in payloads.iter().enumerate() {
3439                        self.compile_expr_into(expr, start + i as Reg)?;
3440                        names.push(self.interner.resolve(*name).to_string());
3441                    }
3442                    let site = self.add_obs_site(ObsSiteDesc {
3443                        kind: ObsSiteKind::Message(map_obs_cat(*category)),
3444                        message: self.interner.resolve(*message).to_string(),
3445                        payload_names: names,
3446                        sample: *sample,
3447                    });
3448                    self.emit(Op::Obs {
3449                        site,
3450                        args_start: start,
3451                        args_count: count,
3452                    });
3453                }
3454                Ok(())
3455            }
3456            Stmt::During { label, body } => {
3457                if self.emit_observation {
3458                    let name = self.interner.resolve(*label).to_string();
3459                    let enter = self.add_obs_site(ObsSiteDesc {
3460                        kind: ObsSiteKind::SpanEnter,
3461                        message: name.clone(),
3462                        payload_names: Vec::new(),
3463                        sample: None,
3464                    });
3465                    self.emit(Op::Obs {
3466                        site: enter,
3467                        args_start: 0,
3468                        args_count: 0,
3469                    });
3470                    for s in body.iter() {
3471                        self.compile_stmt(s)?;
3472                    }
3473                    let exit = self.add_obs_site(ObsSiteDesc {
3474                        kind: ObsSiteKind::SpanExit,
3475                        message: name,
3476                        payload_names: Vec::new(),
3477                        sample: None,
3478                    });
3479                    self.emit(Op::Obs {
3480                        site: exit,
3481                        args_start: 0,
3482                        args_count: 0,
3483                    });
3484                } else {
3485                    for s in body.iter() {
3486                        self.compile_stmt(s)?;
3487                    }
3488                }
3489                Ok(())
3490            }
3491            Stmt::Zone { name, body, .. } => self.compile_zone(*name, body),
3492            Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => {
3493                // Sequential in the interpreter spec. Each task runs WITHOUT a
3494                // block scope (its Lets persist), and its Break/Return is
3495                // swallowed — the tree-walker discards each task's ControlFlow.
3496                for task in tasks.iter() {
3497                    self.flow_stack.push(FlowCtx::Zone { exits: Vec::new() });
3498                    self.compile_stmt(task)?;
3499                    let end_pc = self.current_pc();
3500                    if let Some(FlowCtx::Zone { exits }) = self.flow_stack.pop() {
3501                        for j in exits {
3502                            self.patch_jump_target(j, end_pc)?;
3503                        }
3504                    }
3505                }
3506                Ok(())
3507            }
3508            Stmt::Sleep { milliseconds } => {
3509                let duration = self.compile_expr(milliseconds)?;
3510                self.emit(Op::Sleep { duration });
3511                Ok(())
3512            }
3513            // Verification-only / declaration statements: no runtime effect.
3514            Stmt::Assert { .. }
3515            | Stmt::Trust { .. }
3516            | Stmt::Require { .. }
3517            | Stmt::Theorem(_)
3518            | Stmt::Definition(_)
3519            | Stmt::Axiom(_)
3520            | Stmt::Theory(_) => Ok(()),
3521            // Definitions were registered in pass 1.
3522            Stmt::StructDef { .. } => Ok(()),
3523            Stmt::SetField {
3524                object,
3525                field,
3526                value,
3527            } => {
3528                let field_name = self.interner.resolve(*field).to_string();
3529                let fidx = self.add_const(Constant::Text(field_name))?;
3530                if let Expr::Identifier(obj_sym) = object {
3531                    // Tree-walker order: value first, then the target lookup.
3532                    match self.resolve_name(*obj_sym) {
3533                        NameRef::Local(obj) => {
3534                            let v = self.compile_expr(value)?;
3535                            self.emit(Op::StructInsert {
3536                                obj,
3537                                field: fidx,
3538                                value: v,
3539                            });
3540                            Ok(())
3541                        }
3542                        NameRef::Unbound => {
3543                            let scratch = self.alloc_reg()?;
3544                            self.compile_expr_into(value, scratch)?;
3545                            self.emit_unbound(*obj_sym)
3546                        }
3547                        _ => {
3548                            // Structs are VALUES: load the global's copy,
3549                            // mutate it, store it back.
3550                            let v = self.compile_expr(value)?;
3551                            let obj = self.alloc_reg()?;
3552                            self.emit_read(*obj_sym, obj)?;
3553                            self.emit(Op::StructInsert {
3554                                obj,
3555                                field: fidx,
3556                                value: v,
3557                            });
3558                            self.emit_write(*obj_sym, obj)
3559                        }
3560                    }
3561                } else {
3562                    // A field of a field (`Set a's session's name to who`): the value first, then the
3563                    // place mechanism takes the inner record out, writes its field, and puts it back
3564                    // — through every level, whatever holds the outer one.
3565                    let v = self.compile_expr(value)?;
3566                    self.compile_place_mutation(object, &mut |c, obj| {
3567                        c.emit(Op::StructInsert {
3568                            obj,
3569                            field: fidx,
3570                            value: v,
3571                        });
3572                        Ok(())
3573                    })?;
3574                    Ok(())
3575                }
3576            }
3577            Stmt::Inspect { target, arms, .. } => self.compile_inspect(target, arms),
3578            Stmt::IncreaseCrdt {
3579                object,
3580                field,
3581                amount,
3582            }
3583            | Stmt::DecreaseCrdt {
3584                object,
3585                field,
3586                amount,
3587            } => {
3588                let negate = matches!(s, Stmt::DecreaseCrdt { .. });
3589                let amt = self.compile_expr(amount)?;
3590                let fname = self.interner.resolve(*field).to_string();
3591                let fidx = self.add_const(Constant::Text(fname))?;
3592                if let Expr::Identifier(obj_sym) = object {
3593                    match self.resolve_name(*obj_sym) {
3594                        NameRef::Local(obj) => {
3595                            self.emit(Op::CrdtBump {
3596                                obj,
3597                                field: fidx,
3598                                amount: amt,
3599                                negate,
3600                            });
3601                            Ok(())
3602                        }
3603                        NameRef::Unbound => self.emit_unbound(*obj_sym),
3604                        _ => {
3605                            let obj = self.alloc_reg()?;
3606                            self.emit_read(*obj_sym, obj)?;
3607                            self.emit(Op::CrdtBump {
3608                                obj,
3609                                field: fidx,
3610                                amount: amt,
3611                                negate,
3612                            });
3613                            self.emit_write(*obj_sym, obj)
3614                        }
3615                    }
3616                } else {
3617                    let msg = if negate {
3618                        "DecreaseCrdt target must be an identifier"
3619                    } else {
3620                        "IncreaseCrdt target must be an identifier"
3621                    };
3622                    let idx = self.add_const(Constant::Text(msg.to_string()))?;
3623                    self.emit(Op::FailWith { msg: idx });
3624                    Ok(())
3625                }
3626            }
3627            Stmt::MergeCrdt { source, target } => {
3628                let src = self.compile_expr(source)?;
3629                if let Expr::Identifier(target_sym) = target {
3630                    match self.resolve_name(*target_sym) {
3631                        NameRef::Local(tgt) => {
3632                            self.emit(Op::CrdtMerge {
3633                                target: tgt,
3634                                source: src,
3635                            });
3636                            Ok(())
3637                        }
3638                        NameRef::Unbound => self.emit_unbound(*target_sym),
3639                        _ => {
3640                            let tgt = self.alloc_reg()?;
3641                            self.emit_read(*target_sym, tgt)?;
3642                            self.emit(Op::CrdtMerge {
3643                                target: tgt,
3644                                source: src,
3645                            });
3646                            self.emit_write(*target_sym, tgt)
3647                        }
3648                    }
3649                } else {
3650                    let idx = self.add_const(Constant::Text(
3651                        "Merge target must be an identifier".to_string(),
3652                    ))?;
3653                    self.emit(Op::FailWith { msg: idx });
3654                    Ok(())
3655                }
3656            }
3657            // The IDEMPOTENT sibling of `MergeCrdt`: emits `Op::CrdtJoin` (per-field MAX for bare-Int, so a
3658            // redelivered state never double-counts). Register handling / unbound checks mirror `MergeCrdt`.
3659            Stmt::JoinCrdt { source, target } => {
3660                let src = self.compile_expr(source)?;
3661                if let Expr::Identifier(target_sym) = target {
3662                    match self.resolve_name(*target_sym) {
3663                        NameRef::Local(tgt) => {
3664                            self.emit(Op::CrdtJoin {
3665                                target: tgt,
3666                                source: src,
3667                            });
3668                            Ok(())
3669                        }
3670                        NameRef::Unbound => self.emit_unbound(*target_sym),
3671                        _ => {
3672                            let tgt = self.alloc_reg()?;
3673                            self.emit_read(*target_sym, tgt)?;
3674                            self.emit(Op::CrdtJoin {
3675                                target: tgt,
3676                                source: src,
3677                            });
3678                            self.emit_write(*target_sym, tgt)
3679                        }
3680                    }
3681                } else {
3682                    let idx = self.add_const(Constant::Text(
3683                        "Converge target must be an identifier".to_string(),
3684                    ))?;
3685                    self.emit(Op::FailWith { msg: idx });
3686                    Ok(())
3687                }
3688            }
3689            Stmt::ReadFrom { var, source } => {
3690                use crate::ast::stmt::ReadSource;
3691                match source {
3692                    ReadSource::Console => {
3693                        // Console reads yield empty Text in the interpreter.
3694                        let dst = self.let_reg(*var)?;
3695                        let idx = self.add_const(Constant::Text(String::new()))?;
3696                        self.emit(Op::LoadConst { dst, idx });
3697                        Ok(())
3698                    }
3699                    ReadSource::File(path_expr) => {
3700                        // The SAME sandboxed VFS the tree-walker's `ReadFrom` reads through
3701                        // (`BuiltinId::VfsReadFile`), so a file read errors identically on both
3702                        // tiers rather than the VM reporting an uninitialized VFS the
3703                        // tree-walker never has.
3704                        let arg = self.reserve_regs(1)?;
3705                        self.compile_expr_into(path_expr, arg)?;
3706                        let dst = self.let_reg(*var)?;
3707                        self.emit(Op::CallBuiltin {
3708                            dst,
3709                            builtin: crate::semantics::builtins::BuiltinId::VfsReadFile,
3710                            args_start: arg,
3711                            arg_count: 1,
3712                        });
3713                        Ok(())
3714                    }
3715                }
3716            }
3717            Stmt::WriteFile { content, path } => {
3718                // The SAME sandboxed VFS the tree-walker's `WriteFile` writes through
3719                // (`BuiltinId::VfsWriteFile`): the content, then the path, in the order the
3720                // tree-walker evaluates them, so a failing expression fails first on both tiers.
3721                let args = self.reserve_regs(2)?;
3722                self.compile_expr_into(content, args)?;
3723                self.compile_expr_into(path, args + 1)?;
3724                let dst = self.alloc_reg()?;
3725                self.emit(Op::CallBuiltin {
3726                    dst,
3727                    builtin: crate::semantics::builtins::BuiltinId::VfsWriteFile,
3728                    args_start: args,
3729                    arg_count: 2,
3730                });
3731                Ok(())
3732            }
3733            Stmt::Mount { var, path } => {
3734                // The journal's text from the same VFS, or empty Text when there is none yet
3735                // (`BuiltinId::VfsMount`) — the tree-walker's `Mount` arm, on the VM.
3736                let arg = self.reserve_regs(1)?;
3737                self.compile_expr_into(path, arg)?;
3738                let dst = self.let_reg(*var)?;
3739                self.emit(Op::CallBuiltin {
3740                    dst,
3741                    builtin: crate::semantics::builtins::BuiltinId::VfsMount,
3742                    args_start: arg,
3743                    arg_count: 1,
3744                });
3745                Ok(())
3746            }
3747            Stmt::Spawn { name, .. } => {
3748                // Agents do not run in the interpreter: the handle is Nothing.
3749                let dst = self.let_reg(*name)?;
3750                let idx = self.add_const(Constant::Nothing)?;
3751                self.emit(Op::LoadConst { dst, idx });
3752                Ok(())
3753            }
3754            // Peer messaging: emit the networking opcodes the async VM net driver
3755            // (`run_vm_net_async`) services through the shared `NetInbox` — the same inbox the
3756            // tree-walker uses, so a `Send`/`Await` is byte-identical on both tiers. (The dial
3757            // knobs — compression/cached/redundant/view — are not yet threaded here; the default
3758            // self-describing encode still decodes identically, so output parity holds.)
3759            Stmt::SendMessage {
3760                message,
3761                destination,
3762                ..
3763            } => {
3764                let to = self.compile_expr(destination)?;
3765                let msg = self.compile_expr(message)?;
3766                self.emit(Op::NetSend { to, msg });
3767                Ok(())
3768            }
3769            Stmt::StreamMessage {
3770                values,
3771                destination,
3772            } => {
3773                let to = self.compile_expr(destination)?;
3774                let vals = self.compile_expr(values)?;
3775                self.emit(Op::NetStream { to, values: vals });
3776                Ok(())
3777            }
3778            Stmt::AwaitMessage {
3779                source,
3780                into,
3781                stream,
3782                ..
3783            } => {
3784                let from = self.compile_expr(source)?;
3785                let dst = self.let_reg(*into)?;
3786                self.emit(Op::NetAwait {
3787                    dst,
3788                    from,
3789                    stream: *stream,
3790                });
3791                Ok(())
3792            }
3793            Stmt::Check {
3794                subject,
3795                predicate,
3796                is_capability,
3797                object,
3798                source_text,
3799                ..
3800            } => {
3801                let subj = self.alloc_reg()?;
3802                self.emit_read(*subject, subj)?;
3803                // The object is only looked up for capability checks.
3804                let obj = if *is_capability {
3805                    match object {
3806                        Some(obj_sym) => {
3807                            let r = self.alloc_reg()?;
3808                            self.emit_read(*obj_sym, r)?;
3809                            r
3810                        }
3811                        None => Reg::MAX,
3812                    }
3813                } else {
3814                    Reg::MAX
3815                };
3816                let st = self.add_const(Constant::Text(source_text.clone()))?;
3817                self.emit(Op::CheckPolicy {
3818                    subject: subj,
3819                    predicate: *predicate,
3820                    is_capability: *is_capability,
3821                    object: obj,
3822                    source_text: st,
3823                });
3824                Ok(())
3825            }
3826            Stmt::AppendToSequence { sequence, value } => {
3827                // The RGA is always behind a shared `Rc` (whether a bare variable or a
3828                // struct field), so appending in place propagates — no write-back needed.
3829                // Value compiled first, matching the tree-walker's evaluation order.
3830                let val = self.compile_expr(value)?;
3831                let seq = self.compile_expr(sequence)?;
3832                self.emit(Op::CrdtAppend { seq, value: val });
3833                Ok(())
3834            }
3835            Stmt::ResolveConflict {
3836                object,
3837                field,
3838                value,
3839            } => {
3840                let val = self.compile_expr(value)?;
3841                let fname = self.interner.resolve(*field).to_string();
3842                let fidx = self.add_const(Constant::Text(fname))?;
3843                // Mirrors `IncreaseCrdt`: a register field resolves in place via its shared
3844                // `Rc`; a plain field is overwritten, so it needs the read/write-back path
3845                // (structs have value semantics).
3846                if let Expr::Identifier(obj_sym) = object {
3847                    match self.resolve_name(*obj_sym) {
3848                        NameRef::Local(obj) => {
3849                            self.emit(Op::CrdtResolve {
3850                                obj,
3851                                field: fidx,
3852                                value: val,
3853                            });
3854                            Ok(())
3855                        }
3856                        NameRef::Unbound => self.emit_unbound(*obj_sym),
3857                        _ => {
3858                            let obj = self.alloc_reg()?;
3859                            self.emit_read(*obj_sym, obj)?;
3860                            self.emit(Op::CrdtResolve {
3861                                obj,
3862                                field: fidx,
3863                                value: val,
3864                            });
3865                            self.emit_write(*obj_sym, obj)
3866                        }
3867                    }
3868                } else {
3869                    let idx = self.add_const(Constant::Text(
3870                        "Resolve target must be a struct field".to_string(),
3871                    ))?;
3872                    self.emit(Op::FailWith { msg: idx });
3873                    Ok(())
3874                }
3875            }
3876            // Relay networking opcodes — serviced by the async VM net driver (`run_vm_net_async`)
3877            // through the shared `NetInbox`, byte-identically to the tree-walker. `LetPeerAgent`
3878            // and `Sync` are not yet driven on the VM net runner (they stay async-tier below).
3879            Stmt::Listen { address, secure } => {
3880                if secure.is_some() {
3881                    return Err("the PNP one-time pad (`with pad`) is only supported by the interpreter tier, not the bytecode VM".to_string().into());
3882                }
3883                let topic = self.compile_expr(address)?;
3884                self.emit(Op::NetListen { topic });
3885                Ok(())
3886            }
3887            Stmt::Serve { port, handler } => {
3888                let handler_sym = match handler {
3889                    Expr::Identifier(sym) => *sym,
3890                    _ => {
3891                        return Err("Serve: the handler must be a named function"
3892                            .to_string()
3893                            .into())
3894                    }
3895                };
3896                let &func = self.fn_index.get(&handler_sym).ok_or_else(|| {
3897                    format!(
3898                        "Serve: the handler '{}' is not a defined function",
3899                        self.interner.resolve(handler_sym)
3900                    )
3901                })?;
3902                let port = self.compile_expr(port)?;
3903                self.emit(Op::Serve {
3904                    port,
3905                    handler: func,
3906                });
3907                Ok(())
3908            }
3909            Stmt::ConnectTo { address, secure } => {
3910                if secure.is_some() {
3911                    return Err("the PNP one-time pad (`with pad`) is only supported by the interpreter tier, not the bytecode VM".to_string().into());
3912                }
3913                let url = self.compile_expr(address)?;
3914                self.emit(Op::NetConnect { url });
3915                Ok(())
3916            }
3917            Stmt::LetPeerAgent { var, address } => {
3918                let addr = self.compile_expr(address)?;
3919                let dst = self.let_reg(*var)?;
3920                self.emit(Op::NetMakePeer { dst, addr });
3921                Ok(())
3922            }
3923            Stmt::Sync { var, topic } => {
3924                // Read the local counter, sync+merge over the relay, write the merged value back —
3925                // a read-modify-write on `var` through `Op::NetSync`.
3926                let topic_reg = self.compile_expr(topic)?;
3927                let tmp = self.alloc_reg()?;
3928                self.emit_read(*var, tmp)?;
3929                self.emit(Op::NetSync {
3930                    dst: tmp,
3931                    topic: topic_reg,
3932                });
3933                self.emit_write(*var, tmp)
3934            }
3935            // Go-like concurrency (T11d). The VM emits the scheduler opcodes; a
3936            // concurrent program is then driven through `run_until_block` by a
3937            // `VmTask`. (Concurrent programs currently route to the tree-walker
3938            // before the VM, so these are exercised via the dedicated VM-scheduler
3939            // entry; the default routing is unchanged.)
3940            Stmt::CreatePipe {
3941                var,
3942                element_type,
3943                capacity,
3944            } => {
3945                let dst = self.let_reg(*var)?;
3946                let cap = capacity.map(|c| c as i32).unwrap_or(-1);
3947                let elem = crate::vm::instruction::ChanElem::from_type_name(
3948                    self.interner.resolve(*element_type),
3949                );
3950                self.emit(Op::ChanNew { dst, cap, elem });
3951                Ok(())
3952            }
3953            Stmt::SendPipe { value, pipe } => {
3954                let val = self.compile_expr(value)?;
3955                let chan = self.compile_expr(pipe)?;
3956                self.emit(Op::ChanSend { chan, val });
3957                Ok(())
3958            }
3959            Stmt::ReceivePipe { var, pipe } => {
3960                let chan = self.compile_expr(pipe)?;
3961                let dst = self.let_reg(*var)?;
3962                self.emit(Op::ChanRecv { dst, chan });
3963                Ok(())
3964            }
3965            Stmt::TrySendPipe {
3966                value,
3967                pipe,
3968                result,
3969            } => {
3970                let val = self.compile_expr(value)?;
3971                let chan = self.compile_expr(pipe)?;
3972                let dst = match result {
3973                    Some(sym) => self.let_reg(*sym)?,
3974                    None => self.alloc_reg()?,
3975                };
3976                self.emit(Op::ChanTrySend { dst, chan, val });
3977                Ok(())
3978            }
3979            Stmt::TryReceivePipe { var, pipe } => {
3980                let chan = self.compile_expr(pipe)?;
3981                let dst = self.let_reg(*var)?;
3982                self.emit(Op::ChanTryRecv { dst, chan });
3983                Ok(())
3984            }
3985            Stmt::LaunchTask { function, args } => self.compile_spawn(*function, args, None),
3986            Stmt::LaunchTaskWithHandle {
3987                handle,
3988                function,
3989                args,
3990            } => self.compile_spawn(*function, args, Some(*handle)),
3991            Stmt::StopTask { handle } => {
3992                let h = self.compile_expr(handle)?;
3993                self.emit(Op::TaskAbort { handle: h });
3994                Ok(())
3995            }
3996            Stmt::CloseChannel { channel } => {
3997                let chan = self.compile_expr(channel)?;
3998                self.emit(Op::ChanClose { chan });
3999                Ok(())
4000            }
4001            Stmt::AwaitTask { handle, result } => {
4002                let h = self.compile_expr(handle)?;
4003                // `Op::TaskAwait` always writes a result register; bind it to the named
4004                // variable when `… into r` is given, otherwise a scratch register the
4005                // result is discarded from.
4006                let dst = match result {
4007                    Some(r) => self.let_reg(*r)?,
4008                    None => self.alloc_reg()?,
4009                };
4010                self.emit(Op::TaskAwait { dst, handle: h });
4011                Ok(())
4012            }
4013            Stmt::Select { branches } => {
4014                use crate::ast::stmt::SelectBranch;
4015                // Register each arm. A recv arm allocates and binds its var
4016                // register up front, so the winning branch body reads the value
4017                // `deliver_select` writes there.
4018                for branch in branches.iter() {
4019                    match branch {
4020                        SelectBranch::Receive { var, pipe, .. } => {
4021                            let chan = self.compile_expr(pipe)?;
4022                            let var_reg = self.let_reg(*var)?;
4023                            self.emit(Op::SelectArmRecv { chan, var: var_reg });
4024                        }
4025                        SelectBranch::Timeout { milliseconds, .. } => {
4026                            let ticks = self.compile_expr(milliseconds)?;
4027                            self.emit(Op::SelectArmTimeout { ticks });
4028                        }
4029                    }
4030                }
4031                let dst_arm = self.alloc_reg()?;
4032                self.emit(Op::SelectWait { dst_arm });
4033                // Dispatch on the winning arm index: run that branch's body.
4034                let mut end_jumps = Vec::new();
4035                for (i, branch) in branches.iter().enumerate() {
4036                    let lit = self.alloc_reg()?;
4037                    let idx = self.add_const(Constant::Int(i as i64))?;
4038                    self.emit(Op::LoadConst { dst: lit, idx });
4039                    let cmp = self.alloc_reg()?;
4040                    self.emit(Op::Eq {
4041                        dst: cmp,
4042                        lhs: dst_arm,
4043                        rhs: lit,
4044                    });
4045                    let jskip = self.emit_placeholder_jump_if_false(cmp);
4046                    let body = match branch {
4047                        SelectBranch::Receive { body, .. } | SelectBranch::Timeout { body, .. } => {
4048                            *body
4049                        }
4050                    };
4051                    let mark = self.enter_block();
4052                    for st in body {
4053                        self.compile_stmt(st)?;
4054                    }
4055                    self.exit_block(mark);
4056                    let jend = self.emit_placeholder_jump();
4057                    end_jumps.push(jend);
4058                    self.patch_jump_target(jskip, self.current_pc())?;
4059                }
4060                for j in end_jumps {
4061                    self.patch_jump_target(j, self.current_pc())?;
4062                }
4063                Ok(())
4064            }
4065            Stmt::Escape { .. } => self.emit_fail(crate::semantics::escape::REFUSAL),
4066            Stmt::FunctionDef { .. } => {
4067                // Nested function definitions are unreachable from the parser
4068                // (## To headers are top level); statically registering one
4069                // here cannot model the tree-walker's conditional runtime
4070                // definition, so it is a compile error.
4071                Err("vm: nested function definitions are not supported"
4072                    .to_string()
4073                    .into())
4074            }
4075        }
4076    }
4077
4078    /// Inside a `Reversibly:` block, try to lower a `Set x to <value>` where `x` is the local in
4079    /// register `dst` to the zero-garbage reversible ISA. Recognizes exactly the IN-PLACE ABELIAN
4080    /// forms (`x` on the left, `x` never re-observed on the right):
4081    /// `x + e` → `RevAdd`, `x - e` → `RevSub`, `x xor e` → `RevXor`, and `-x` (`0 - x`) → `RevNeg`.
4082    /// Returns `Ok(true)` if it emitted a reversible op, `Ok(false)` to fall through to the plain
4083    /// lowering (an unrecognized form). The FORWARD semantics are identical to the plain path, so
4084    /// program output is unchanged. The delta rides a FRESH scratch register, so the ISA
4085    /// `place != delta` well-formedness invariant holds by construction.
4086    fn try_emit_reversible_set(
4087        &mut self,
4088        target: Symbol,
4089        dst: Reg,
4090        value: &Expr,
4091    ) -> Result<bool, Refusal> {
4092        // `-x`, which the parser desugars to `0 - x`: `Set x to -x` → in-place `RevNeg`.
4093        if let Expr::BinaryOp {
4094            op: BinaryOpKind::Subtract,
4095            left,
4096            right,
4097        } = value
4098        {
4099            if matches!(left, Expr::Literal(Literal::Number(0)))
4100                && matches!(right, Expr::Identifier(s) if *s == target)
4101            {
4102                self.emit(Op::RevNeg { place: dst });
4103                return Ok(true);
4104            }
4105        }
4106        // `x ⊕ e` where `⊕` is an abelian in-place operator, `x` leads, and `e` provably never
4107        // observes `x` (so the delta read is untouched by the in-place write — a genuine
4108        // group translation, invertible without a tape).
4109        if let Expr::BinaryOp { op, left, right } = value {
4110            let rev = match op {
4111                BinaryOpKind::Add => Some(RevOp::Add),
4112                BinaryOpKind::Subtract => Some(RevOp::Sub),
4113                BinaryOpKind::BitXor => Some(RevOp::Xor),
4114                _ => None,
4115            };
4116            if let Some(kind) = rev {
4117                if matches!(left, Expr::Identifier(s) if *s == target) && expr_avoids(right, target)
4118                {
4119                    let delta = self.alloc_reg()?;
4120                    self.compile_expr_into(right, delta)?;
4121                    self.emit(match kind {
4122                        RevOp::Add => Op::RevAdd { place: dst, delta },
4123                        RevOp::Sub => Op::RevSub { place: dst, delta },
4124                        RevOp::Xor => Op::RevXor { place: dst, delta },
4125                    });
4126                    return Ok(true);
4127                }
4128            }
4129        }
4130        Ok(false)
4131    }
4132
4133    fn current_pc(&self) -> usize {
4134        self.code.len()
4135    }
4136
4137    fn emit_placeholder_jump(&mut self) -> usize {
4138        let idx = self.code.len();
4139        self.emit(Op::Jump { target: usize::MAX });
4140        idx
4141    }
4142
4143    fn emit_placeholder_jump_if_false(&mut self, cond: Reg) -> usize {
4144        let idx = self.code.len();
4145        self.emit(Op::JumpIfFalse {
4146            cond,
4147            target: usize::MAX,
4148        });
4149        idx
4150    }
4151
4152    fn patch_jump_target(&mut self, idx: usize, target: usize) -> Result<(), Refusal> {
4153        Ok(patch_jump(&mut self.code, idx, target)?)
4154    }
4155
4156    /// Compile `e`, returning the register that holds its value. An unbound
4157    /// identifier becomes a runtime failure at this point in the instruction
4158    /// stream (never a compile error — dead branches stay free).
4159    fn compile_expr(&mut self, e: &Expr) -> Result<Reg, Refusal> {
4160        match e {
4161            Expr::Identifier(sym) => match self.interner.resolve(*sym) {
4162                "today" | "now" => {
4163                    let scratch = self.alloc_reg()?;
4164                    self.compile_expr_into(e, scratch)?;
4165                    Ok(scratch)
4166                }
4167                _ => match self.resolve_name(*sym) {
4168                    NameRef::Local(r) => Ok(r),
4169                    _ => {
4170                        let scratch = self.alloc_reg()?;
4171                        self.emit_read(*sym, scratch)?;
4172                        Ok(scratch)
4173                    }
4174                },
4175            },
4176            _ => {
4177                let dst = self.alloc_reg()?;
4178                self.compile_expr_into(e, dst)?;
4179                Ok(dst)
4180            }
4181        }
4182    }
4183
4184    /// Preserve an already evaluated local value across a later function call.
4185    /// A direct local read normally reuses its binding's register; a mutable
4186    /// argument can replace that register before the surrounding operation runs.
4187    /// Pure expressions and values already in temporary registers need no copy.
4188    fn compile_expr_before(&mut self, e: &Expr, later: &[&Expr]) -> Result<Reg, Refusal> {
4189        let src = self.compile_expr(e)?;
4190        if !matches!(e, Expr::Identifier(sym)
4191            if matches!(self.resolve_name(*sym), NameRef::Local(reg) if reg == src))
4192        {
4193            return Ok(src);
4194        }
4195        let mut pending = later.to_vec();
4196        while let Some(next) = pending.pop() {
4197            match next {
4198                Expr::Call { .. } | Expr::CallExpr { .. } => {
4199                    let dst = self.alloc_reg()?;
4200                    self.emit(Op::Move { dst, src });
4201                    return Ok(dst);
4202                }
4203                Expr::Closure { .. } => {}
4204                _ => pending.extend(logicaffeine_language::ast_depth::expr_children(next)),
4205            }
4206        }
4207        Ok(src)
4208    }
4209
4210    /// Compile `e`, placing its value into `dst`. Depth-guarded so adversarially
4211    /// nested expressions fail with an error instead of exhausting the native
4212    /// stack.
4213    fn compile_expr_into(&mut self, e: &Expr, dst: Reg) -> Result<(), Refusal> {
4214        self.expr_depth += 1;
4215        if self.expr_depth > MAX_EXPR_DEPTH {
4216            self.expr_depth -= 1;
4217            return Err("vm: expression too deeply nested".to_string().into());
4218        }
4219        let result = self.compile_expr_into_inner(e, dst);
4220        self.expr_depth -= 1;
4221        result
4222    }
4223
4224    fn compile_expr_into_inner(&mut self, e: &Expr, dst: Reg) -> Result<(), Refusal> {
4225        match e {
4226            Expr::Literal(Literal::Text(sym)) => {
4227                let idx =
4228                    self.add_const(Constant::Text(self.interner.resolve(*sym).to_string()))?;
4229                self.emit(Op::LoadConst { dst, idx });
4230                Ok(())
4231            }
4232            Expr::Literal(lit) => {
4233                let idx = self.add_const(literal_const(lit)?)?;
4234                self.emit(Op::LoadConst { dst, idx });
4235                Ok(())
4236            }
4237            Expr::Identifier(sym) => {
4238                // Temporal builtins: the NAME wins even when shadowed
4239                // (tree-walker checks before the env lookup).
4240                match self.interner.resolve(*sym) {
4241                    "today" => {
4242                        self.emit(Op::LoadToday { dst });
4243                        Ok(())
4244                    }
4245                    "now" => {
4246                        self.emit(Op::LoadNow { dst });
4247                        Ok(())
4248                    }
4249                    _ => self.emit_read(*sym, dst),
4250                }
4251            }
4252            Expr::BinaryOp {
4253                op: BinaryOpKind::And,
4254                left,
4255                right,
4256            } => self.compile_short_circuit(true, left, right, dst),
4257            Expr::BinaryOp {
4258                op: BinaryOpKind::Or,
4259                left,
4260                right,
4261            } => self.compile_short_circuit(false, left, right, dst),
4262            Expr::BinaryOp { op, left, right } => {
4263                // Int `x / 2^k` → single `DivPow2` op (the JIT lowers it to the
4264                // 1-op shift stencil): replaces idiv, fires for loop-invariant
4265                // divisors, no scratch-register pressure.
4266                if self.strength_reduce && matches!(op, BinaryOpKind::Divide) {
4267                    if let Some(k) = self.divpow2_shift(left, right) {
4268                        let lhs = self.compile_expr(left)?;
4269                        self.emit(Op::DivPow2 {
4270                            dst,
4271                            lhs,
4272                            k: k as u8,
4273                        });
4274                        return Ok(());
4275                    }
4276                    // Proven-non-negative Int `x / c` (c a constant non-pow2) →
4277                    // the magic reciprocal (mul-high + shift) instead of idiv.
4278                    if let Some((magic, more, divisor)) = self.magic_div_const(left, right) {
4279                        let lhs = self.compile_expr(left)?;
4280                        self.emit(Op::MagicDivU {
4281                            dst,
4282                            lhs,
4283                            magic,
4284                            more,
4285                            mul_back: 0,
4286                            divisor,
4287                            wrap: false,
4288                        });
4289                        return Ok(());
4290                    }
4291                }
4292                // Proven-non-negative Int `x % 2^k` → `x & (2^k - 1)`, emitted
4293                // as the register-form `BitAnd`: replaces idiv with a 1-cycle
4294                // AND, which the JIT lowers to a `BitAnd` stencil. Gated on
4295                // Oracle-proven non-negativity — unsound for negative dividends.
4296                if self.strength_reduce && matches!(op, BinaryOpKind::Modulo) {
4297                    if let Some(mask) = self.modpow2_mask(left, right) {
4298                        let lhs = self.compile_expr(left)?;
4299                        let rhs = self.alloc_reg()?;
4300                        let idx = self.add_const(Constant::Int(mask))?;
4301                        self.emit(Op::LoadConst { dst: rhs, idx });
4302                        self.emit(Op::BitAnd { dst, lhs, rhs });
4303                        return Ok(());
4304                    }
4305                    // Opt::ModWrap: an `x` the Oracle bounds below `c` is its own remainder; one below
4306                    // `2c` keeps the magic remainder below, marked `wrap` (`crate::optimize::modwrap`).
4307                    let wrap = self.mod_wrap_const(left, right);
4308                    if wrap == Some(crate::optimize::modwrap::ModWrap::Identity) {
4309                        crate::optimize::mark_fired(crate::optimization::Opt::ModWrap);
4310                        return self.compile_expr_into(left, dst);
4311                    }
4312                    // Proven-non-negative Int `x % c` (c a constant non-pow2) →
4313                    // the magic reciprocal: `x - (x/c)*c` via mul-high + shift,
4314                    // instead of idiv. `mul_back == c` selects the remainder.
4315                    if let Expr::Literal(Literal::Number(c)) = right {
4316                        if let Some((magic, more, divisor)) = self.magic_div_const(left, right) {
4317                            let wrap = wrap == Some(crate::optimize::modwrap::ModWrap::Once);
4318                            if wrap {
4319                                crate::optimize::mark_fired(crate::optimization::Opt::ModWrap);
4320                            }
4321                            let lhs = self.compile_expr(left)?;
4322                            self.emit(Op::MagicDivU {
4323                                dst,
4324                                lhs,
4325                                magic,
4326                                more,
4327                                mul_back: *c,
4328                                divisor,
4329                                wrap,
4330                            });
4331                            return Ok(());
4332                        }
4333                    }
4334                }
4335                // ★ ABSENCE IS ONE THING (`semantics::compare`, R2): `x is none` and `x is nothing`
4336                // are equal on every tier, so an equality against `none` loads the one absence
4337                // constant every backend tests a value against, never an `Option` it would have to
4338                // tell apart from a present payload.
4339                if matches!(op, BinaryOpKind::Eq | BinaryOpKind::NotEq)
4340                    && (matches!(left, Expr::OptionNone) || matches!(right, Expr::OptionNone))
4341                {
4342                    let lhs = self.compile_equality_operand(left)?;
4343                    let rhs = self.compile_equality_operand(right)?;
4344                    self.emit(binop_op(*op, dst, lhs, rhs)?);
4345                    return Ok(());
4346                }
4347                let lhs = self.compile_expr_before(left, &[right])?;
4348                let rhs = self.compile_expr(right)?;
4349                self.emit(binop_op(*op, dst, lhs, rhs)?);
4350                Ok(())
4351            }
4352            Expr::Not { operand } => {
4353                let src = self.compile_expr(operand)?;
4354                self.emit(Op::Not { dst, src });
4355                Ok(())
4356            }
4357            Expr::Call { function, args } => self.compile_call(*function, args, dst),
4358            Expr::List(items) => {
4359                let count = u16::try_from(items.len())
4360                    .map_err(|_| "vm: list literal too long (max 65535 elements)".to_string())?;
4361                let start = self.reserve_regs(count)?;
4362                for (i, item) in items.iter().enumerate() {
4363                    self.compile_expr_into(item, start + i as Reg)?;
4364                }
4365                self.emit(Op::NewList { dst, start, count });
4366                Ok(())
4367            }
4368            Expr::New {
4369                type_name,
4370                init_fields,
4371                type_args,
4372            } => {
4373                self.compile_new(*type_name, init_fields, dst)?;
4374                // An EMPTY collection still says what it holds, wherever it is written — bound, pushed
4375                // or handed to a constructor as a field's first value — and nothing else ever will.
4376                if let Some(bt) = self.declared_collection(*type_name, type_args) {
4377                    self.note_declared(bt);
4378                }
4379                Ok(())
4380            }
4381            Expr::FieldAccess { object, field } => {
4382                let obj = self.compile_expr(object)?;
4383                let fname = self.interner.resolve(*field).to_string();
4384                let fidx = self.add_const(Constant::Text(fname))?;
4385                self.emit(Op::GetField {
4386                    dst,
4387                    obj,
4388                    field: fidx,
4389                });
4390                Ok(())
4391            }
4392            Expr::NewVariant {
4393                enum_name,
4394                variant,
4395                fields,
4396            } => {
4397                let tname = self.interner.resolve(*enum_name).to_string();
4398                let cname = self.interner.resolve(*variant).to_string();
4399                let tidx = self.add_const(Constant::Text(tname))?;
4400                let cidx = self.add_const(Constant::Text(cname))?;
4401                // Seat each field at its DECLARED position, not its WRITE position — `Op::
4402                // NewInductive` reads `args_start..args_start+count` back purely positionally, and
4403                // `execute_inspect`'s bind arm reads `ind.args[i]` as "the i-th DECLARED field."
4404                // `a new Circle with label "x" and radius 10` must land `radius` before `label`
4405                // when the type declares `radius` first, regardless of `with`-clause order.
4406                // Values are still evaluated in WRITE order (left to right as authored) — only the
4407                // register each one lands in is reordered. A field the `with` clause omits
4408                // defaults to `Nothing`, mirroring `struct_defs`' default-fill for structs. Keyed
4409                // by `(enum_name, variant)` — `Expr::NewVariant` already names its own enum, so two
4410                // enums sharing a variant name never collide on one shared entry.
4411                match self.variant_fields.get(&(*enum_name, *variant)).cloned() {
4412                    Some(names) => {
4413                        let count = u16::try_from(names.len())
4414                            .map_err(|_| "vm: too many variant fields".to_string())?;
4415                        let args_start = self.reserve_regs(count)?;
4416                        let mut filled = vec![false; names.len()];
4417                        for (field_name, field_expr) in fields.iter() {
4418                            match names.iter().position(|n| n == field_name) {
4419                                Some(pos) => {
4420                                    self.compile_expr_into(field_expr, args_start + pos as Reg)?;
4421                                    filled[pos] = true;
4422                                }
4423                                None => {
4424                                    return Err(format!(
4425                                        "vm: `{}` has no field `{}`",
4426                                        self.interner.resolve(*variant),
4427                                        self.interner.resolve(*field_name)
4428                                    )
4429                                    .into());
4430                                }
4431                            }
4432                        }
4433                        for (pos, done) in filled.iter().enumerate() {
4434                            if !done {
4435                                let reg = args_start + pos as Reg;
4436                                let idx = self.add_const(Constant::Nothing)?;
4437                                self.emit(Op::LoadConst { dst: reg, idx });
4438                            }
4439                        }
4440                        self.emit(Op::NewInductive {
4441                            dst,
4442                            type_name: tidx,
4443                            ctor: cidx,
4444                            args_start,
4445                            count,
4446                        });
4447                    }
4448                    None => {
4449                        let count = u16::try_from(fields.len())
4450                            .map_err(|_| "vm: too many variant fields".to_string())?;
4451                        let args_start = self.reserve_regs(count)?;
4452                        for (i, (_, field_expr)) in fields.iter().enumerate() {
4453                            self.compile_expr_into(field_expr, args_start + i as Reg)?;
4454                        }
4455                        self.emit(Op::NewInductive {
4456                            dst,
4457                            type_name: tidx,
4458                            ctor: cidx,
4459                            args_start,
4460                            count,
4461                        });
4462                    }
4463                }
4464                Ok(())
4465            }
4466            Expr::Range { start, end } => {
4467                let s = self.compile_expr_before(start, &[end])?;
4468                let e = self.compile_expr(end)?;
4469                self.emit(Op::NewRange {
4470                    dst,
4471                    start: s,
4472                    end: e,
4473                });
4474                Ok(())
4475            }
4476            Expr::Length { collection } => {
4477                let c = self.compile_expr(collection)?;
4478                self.emit(Op::Length { dst, collection: c });
4479                Ok(())
4480            }
4481            Expr::Index { collection, index } => {
4482                // Bounds-check elimination: if the Oracle proved this index
4483                // in `[1, length]` (range analysis, M9), emit the unchecked
4484                // form — the JIT drops the bounds branch. Checked otherwise.
4485                let proven = self.index_in_bounds(collection, index);
4486                let c = self.compile_expr_before(collection, &[index])?;
4487                let i = self.compile_expr(index)?;
4488                if proven {
4489                    self.emit(Op::IndexUnchecked {
4490                        dst,
4491                        collection: c,
4492                        index: i,
4493                    });
4494                } else {
4495                    self.emit(Op::Index {
4496                        dst,
4497                        collection: c,
4498                        index: i,
4499                    });
4500                }
4501                Ok(())
4502            }
4503            Expr::Contains { collection, value } => {
4504                let c = self.compile_expr_before(collection, &[value])?;
4505                let v = self.compile_expr(value)?;
4506                self.emit(Op::Contains {
4507                    dst,
4508                    collection: c,
4509                    value: v,
4510                });
4511                Ok(())
4512            }
4513            Expr::InterpolatedString(parts) => self.compile_interpolation(parts, dst),
4514            Expr::Slice {
4515                collection,
4516                start,
4517                end,
4518            } => {
4519                let c = self.compile_expr_before(collection, &[start, end])?;
4520                let st = self.compile_expr_before(start, &[end])?;
4521                let en = self.compile_expr(end)?;
4522                self.emit(Op::SliceOp {
4523                    dst,
4524                    collection: c,
4525                    start: st,
4526                    end: en,
4527                });
4528                Ok(())
4529            }
4530            Expr::Copy { expr } => {
4531                let src = self.compile_expr(expr)?;
4532                self.emit(Op::DeepClone { dst, src });
4533                Ok(())
4534            }
4535            Expr::Give { value } => self.compile_expr_into(value, dst),
4536            Expr::Tuple(items) => {
4537                let count = u16::try_from(items.len())
4538                    .map_err(|_| "vm: tuple literal too long".to_string())?;
4539                let start = self.reserve_regs(count)?;
4540                for (i, item) in items.iter().enumerate() {
4541                    self.compile_expr_into(item, start + i as Reg)?;
4542                }
4543                self.emit(Op::NewTuple { dst, start, count });
4544                Ok(())
4545            }
4546            Expr::Union { left, right } => {
4547                let l = self.compile_expr_before(left, &[right])?;
4548                let r = self.compile_expr(right)?;
4549                self.emit(Op::UnionOp {
4550                    dst,
4551                    lhs: l,
4552                    rhs: r,
4553                });
4554                Ok(())
4555            }
4556            Expr::Intersection { left, right } => {
4557                let l = self.compile_expr_before(left, &[right])?;
4558                let r = self.compile_expr(right)?;
4559                self.emit(Op::IntersectOp {
4560                    dst,
4561                    lhs: l,
4562                    rhs: r,
4563                });
4564                Ok(())
4565            }
4566            // ★ AN OPTION CARRIES ITS OWN TAG. This was the root of the whole defect: `some x`
4567            // compiled to `compile_expr_into(value, dst)` — the `Some` DISCARDED — and `none` to
4568            // the `Nothing` sentinel, so presence was inferred from bits rather than carried. Every
4569            // backend downstream of the bytecode inherited that loss: the VM papered over it with
4570            // runtime tags, and the tiers that erase to machine words could not tell `some 0` from
4571            // `none` at all.
4572            //
4573            // It lowers as an ordinary two-constructor inductive — the same `Op::NewInductive` a
4574            // `Result` uses, whose tag every backend already derives from the constructor NAME. So
4575            // this needs no new op and no ISA change; `TestArm`/`BindArm` already do the right
4576            // thing for it on all eight backends.
4577            Expr::OptionSome { value } => self.compile_option_ctor("Some", Some(value), dst),
4578            Expr::OptionNone => self.compile_option_ctor("None", None, dst),
4579            Expr::WithCapacity { value, capacity } => {
4580                if let Expr::New {
4581                    type_name,
4582                    init_fields,
4583                    ..
4584                } = value
4585                {
4586                    if init_fields.is_empty() {
4587                        match self.interner.resolve(*type_name) {
4588                            "Seq" | "List" | "Vec" => {
4589                                let capacity = self.compile_expr(capacity)?;
4590                                self.emit(Op::NewEmptyListWithCapacity { dst, capacity });
4591                                return Ok(());
4592                            }
4593                            "Map" | "HashMap" => {
4594                                let capacity = self.compile_expr(capacity)?;
4595                                self.emit(Op::NewEmptyMapWithCapacity { dst, capacity });
4596                                return Ok(());
4597                            }
4598                            _ => {}
4599                        }
4600                    }
4601                }
4602                self.compile_expr_into(value, dst)
4603            }
4604            Expr::ManifestOf { .. } => {
4605                self.emit(Op::NewEmptyList { dst });
4606                Ok(())
4607            }
4608            Expr::ChunkAt { .. } => {
4609                let idx = self.add_const(Constant::Nothing)?;
4610                self.emit(Op::LoadConst { dst, idx });
4611                Ok(())
4612            }
4613            Expr::Escape { .. } => {
4614                let idx = self.add_const(Constant::Text(
4615                    crate::semantics::escape::REFUSAL.to_string(),
4616                ))?;
4617                self.emit(Op::FailWith { msg: idx });
4618                Ok(())
4619            }
4620            Expr::Closure { params, body, .. } => self.compile_closure(params, body, dst),
4621            Expr::CallExpr { callee, args } => {
4622                let c = self.compile_expr_before(callee, args)?;
4623                let arg_count =
4624                    u16::try_from(args.len()).map_err(|_| "vm: too many arguments".to_string())?;
4625                let args_start = self.reserve_regs(arg_count)?;
4626                for (i, arg) in args.iter().enumerate() {
4627                    self.compile_expr_into(arg, args_start + i as Reg)?;
4628                }
4629                self.emit(Op::CallValue {
4630                    dst,
4631                    callee: c,
4632                    args_start,
4633                    arg_count,
4634                    name_for_err: u32::MAX,
4635                });
4636                Ok(())
4637            }
4638            // A page query asks about a LIVE DOCUMENT, which this tier has none of — the driving
4639            // verbs reach the page through a synthesized dispatcher instead. That refusal is
4640            // correct; falling into the catch-all below for it was not, because "unsupported
4641            // expression" names neither the sentence nor anything to write instead.
4642            Expr::Dom(q) => Err(format!(
4643                "vm: `the {} of` asks about the page, which this tier does not have. \
4644                 A page query runs on the interpreter (a `## Test` block runs there). \
4645                 For a collection's size on every tier, write `length of`.",
4646                q.noun()
4647            )
4648            .into()),
4649            _ => Err("vm: unsupported expression".to_string().into()),
4650        }
4651    }
4652
4653    /// `Repeat for v from a to b` over Int bounds (`Fact::IntRange`): the bounds are evaluated once, when the loop
4654    /// starts, and `v` takes each Int from `a` up to `b` (none when `a` is past `b`), whatever the body does to `v`. A
4655    /// counter carries the position, so no list of the range's Ints is ever built, and the loop is the counted loop the
4656    /// native tier compiles.
4657    fn compile_counted_range(
4658        &mut self,
4659        var: Symbol,
4660        start: &Expr,
4661        end: &Expr,
4662        body: &[Stmt],
4663    ) -> Result<(), Refusal> {
4664        // The counter, the last value and the step outlive the body: they are reserved before it, below every register
4665        // its statements reclaim. Copies, so the body's writes to a bound's variables cannot move them.
4666        let at = self.alloc_reg()?;
4667        let lo = self.compile_expr(start)?;
4668        self.emit(Op::Move { dst: at, src: lo });
4669        let last = self.alloc_reg()?;
4670        let hi = self.compile_expr(end)?;
4671        self.emit(Op::Move { dst: last, src: hi });
4672        let one = self.add_const(Constant::Int(1))?;
4673        let step = self.alloc_reg()?;
4674        self.emit(Op::LoadConst {
4675            dst: step,
4676            idx: one,
4677        });
4678        let outer_mark = self.enter_block();
4679        let item = self.let_reg(var)?;
4680        let loop_start = self.current_pc();
4681        self.loop_stack.push(loop_start);
4682        let more = self.alloc_reg()?;
4683        self.emit(Op::LtEq {
4684            dst: more,
4685            lhs: at,
4686            rhs: last,
4687        });
4688        let jexit = self.emit_placeholder_jump_if_false(more);
4689        self.emit(Op::Move { dst: item, src: at });
4690        self.flow_stack.push(FlowCtx::Loop {
4691            breaks: Vec::new(),
4692            is_repeat: false,
4693        });
4694        let body_mark = self.enter_block();
4695        for st in body {
4696            self.compile_stmt(st)?;
4697        }
4698        self.exit_block(body_mark);
4699        // The last value has already run. Leaving before its increment avoids constructing
4700        // a value outside the range, including MAX + 1 in machine-word backends.
4701        self.emit(Op::Lt {
4702            dst: more,
4703            lhs: at,
4704            rhs: last,
4705        });
4706        let jlast = self.emit_placeholder_jump_if_false(more);
4707        self.emit(Op::Add {
4708            dst: at,
4709            lhs: at,
4710            rhs: step,
4711        });
4712        self.loop_stack.pop();
4713        self.emit(Op::Jump { target: loop_start });
4714        let exit_pc = self.current_pc();
4715        self.patch_jump_target(jexit, exit_pc)?;
4716        self.patch_jump_target(jlast, exit_pc)?;
4717        if let Some(FlowCtx::Loop { breaks, .. }) = self.flow_stack.pop() {
4718            for j in breaks {
4719                self.patch_jump_target(j, exit_pc)?;
4720            }
4721        }
4722        self.exit_block(outer_mark);
4723        Ok(())
4724    }
4725
4726    /// A `Repeat` over a sequence nothing in the loop can change (`Fact::LentIteration`): the sequence is its own
4727    /// snapshot, so the loop walks it by position (its length once, a counter from 1, each item read in bounds) with no
4728    /// iterator. Every bytecode backend then sees a plain counted loop, the shape the native tier compiles.
4729    fn compile_lent_walk(&mut self, var: Symbol, seq: &Expr, body: &[Stmt]) -> Result<(), Refusal> {
4730        crate::optimize::mark_fired(crate::optimization::Opt::Borrow);
4731        // The sequence, its length, the position and the step outlive the body: they are reserved before it, below
4732        // every register its statements reclaim.
4733        let xs = self.compile_expr(seq)?;
4734        let n = self.alloc_reg()?;
4735        self.emit(Op::Length {
4736            dst: n,
4737            collection: xs,
4738        });
4739        let one = self.add_const(Constant::Int(1))?;
4740        let i = self.alloc_reg()?;
4741        self.emit(Op::LoadConst { dst: i, idx: one });
4742        let step = self.alloc_reg()?;
4743        self.emit(Op::LoadConst {
4744            dst: step,
4745            idx: one,
4746        });
4747        // The loop variable lives in a scope spanning the whole loop, as the snapshot walk's does.
4748        let outer_mark = self.enter_block();
4749        let item = self.let_reg(var)?;
4750        let loop_start = self.current_pc();
4751        self.loop_stack.push(loop_start);
4752        let more = self.alloc_reg()?;
4753        self.emit(Op::LtEq {
4754            dst: more,
4755            lhs: i,
4756            rhs: n,
4757        });
4758        let jexit = self.emit_placeholder_jump_if_false(more);
4759        self.emit(Op::IndexUnchecked {
4760            dst: item,
4761            collection: xs,
4762            index: i,
4763        });
4764        self.flow_stack.push(FlowCtx::Loop {
4765            breaks: Vec::new(),
4766            is_repeat: false,
4767        });
4768        let body_mark = self.enter_block();
4769        for st in body {
4770            self.compile_stmt(st)?;
4771        }
4772        self.exit_block(body_mark);
4773        self.emit(Op::Add {
4774            dst: i,
4775            lhs: i,
4776            rhs: step,
4777        });
4778        self.loop_stack.pop();
4779        self.emit(Op::Jump { target: loop_start });
4780        let exit_pc = self.current_pc();
4781        self.patch_jump_target(jexit, exit_pc)?;
4782        if let Some(FlowCtx::Loop { breaks, .. }) = self.flow_stack.pop() {
4783            for j in breaks {
4784                self.patch_jump_target(j, exit_pc)?;
4785            }
4786        }
4787        self.exit_block(outer_mark);
4788        Ok(())
4789    }
4790
4791    /// Compile a `Repeat` loop (extracted: keeps `compile_stmt`'s recursion
4792    /// frame small in debug builds).
4793    fn compile_repeat(
4794        &mut self,
4795        repeat: &Stmt,
4796        pattern: &crate::ast::stmt::Pattern,
4797        iterable: &Expr,
4798        body: &[Stmt],
4799    ) -> Result<(), Refusal> {
4800        use crate::ast::stmt::Pattern;
4801
4802        if let Pattern::Identifier(var) = pattern {
4803            if let Expr::Range { start, end } = iterable {
4804                if crate::optimize::facts::holds_stmt(
4805                    crate::optimize::facts::Fact::IntRange,
4806                    repeat,
4807                ) {
4808                    return self.compile_counted_range(*var, start, end, body);
4809                }
4810            }
4811            if crate::optimize::facts::holds_stmt(
4812                crate::optimize::facts::Fact::LentIteration,
4813                repeat,
4814            ) {
4815                return self.compile_lent_walk(*var, iterable, body);
4816            }
4817        }
4818        let it_reg = self.compile_expr(iterable)?;
4819        self.emit(Op::IterPrepare { iterable: it_reg });
4820
4821        // The loop variable lives in a scope spanning the whole loop
4822        // (the tree-walker pushes ONE scope outside the iteration).
4823        let outer_mark = self.enter_block();
4824        let loop_start;
4825        let next_idx;
4826        match pattern {
4827            Pattern::Identifier(sym) => {
4828                let dst = self.let_reg(*sym)?;
4829                loop_start = self.current_pc();
4830                next_idx = self.code.len();
4831                self.emit(Op::IterNext {
4832                    dst,
4833                    exit: usize::MAX,
4834                });
4835            }
4836            Pattern::Tuple(syms) => {
4837                let tmp = self.alloc_reg()?;
4838                let count = u16::try_from(syms.len())
4839                    .map_err(|_| "vm: tuple pattern too long".to_string())?;
4840                let start = self.reserve_regs(count)?;
4841                for (i, sym) in syms.iter().enumerate() {
4842                    self.scopes
4843                        .last_mut()
4844                        .unwrap()
4845                        .insert(*sym, start + i as Reg);
4846                    self.mark_named(start + i as Reg);
4847                }
4848                loop_start = self.current_pc();
4849                next_idx = self.code.len();
4850                self.emit(Op::IterNext {
4851                    dst: tmp,
4852                    exit: usize::MAX,
4853                });
4854                self.emit(Op::DestructureTuple {
4855                    src: tmp,
4856                    start,
4857                    count,
4858                });
4859            }
4860        }
4861
4862        self.flow_stack.push(FlowCtx::Loop {
4863            breaks: Vec::new(),
4864            is_repeat: true,
4865        });
4866        let body_mark = self.enter_block();
4867        for st in body {
4868            self.compile_stmt(st)?;
4869        }
4870        self.exit_block(body_mark);
4871        self.emit(Op::Jump { target: loop_start });
4872
4873        let exit_pc = self.current_pc();
4874        self.patch_jump_target(next_idx, exit_pc)?;
4875        if let Some(FlowCtx::Loop { breaks, .. }) = self.flow_stack.pop() {
4876            for j in breaks {
4877                self.patch_jump_target(j, exit_pc)?;
4878            }
4879        }
4880        self.emit(Op::IterPop);
4881        self.exit_block(outer_mark);
4882        Ok(())
4883    }
4884
4885    /// Compile a `Zone`: the name is bound to Nothing for the body's duration,
4886    /// and the zone SWALLOWS Break/Return escaping the body.
4887    fn compile_zone(&mut self, name: Symbol, body: &[Stmt]) -> Result<(), Refusal> {
4888        let outer_mark = self.enter_block();
4889        let name_reg = self.let_reg(name)?;
4890        let idx = self.add_const(Constant::Nothing)?;
4891        self.emit(Op::LoadConst { dst: name_reg, idx });
4892        self.flow_stack.push(FlowCtx::Zone { exits: Vec::new() });
4893        let body_mark = self.enter_block();
4894        for st in body {
4895            self.compile_stmt(st)?;
4896        }
4897        self.exit_block(body_mark);
4898        let end_pc = self.current_pc();
4899        if let Some(FlowCtx::Zone { exits }) = self.flow_stack.pop() {
4900            for j in exits {
4901                self.patch_jump_target(j, end_pc)?;
4902            }
4903        }
4904        self.exit_block(outer_mark);
4905        Ok(())
4906    }
4907
4908    /// `compile_inspect`'s non-exhaustive fallthrough for a STATICALLY known enum (user-declared
4909    /// or a built-in `Option`/`Result`, matched by name via either `variant_enum` or arm-text —
4910    /// see the two call sites): test each of `uncovered`'s constructors against the scrutinee `t`
4911    /// in turn and fail with its OWN compile-time-constant message, so the wording is
4912    /// byte-identical to the tree-walker's `inspect_unhandled` by construction. An EMPTY
4913    /// `uncovered` (the arms already name every constructor the enum has) emits NOTHING — no
4914    /// `TestArm`/`FailWith` chain, no defensive final one either: the fallthrough is provably
4915    /// unreachable for a sound program, so there is nothing left to test or name.
4916    fn emit_inspect_fallthrough(
4917        &mut self,
4918        t: Reg,
4919        enum_name: &str,
4920        uncovered: &[String],
4921    ) -> Result<(), Refusal> {
4922        if uncovered.is_empty() {
4923            return Ok(());
4924        }
4925        for vname in uncovered {
4926            let vidx = self.add_const(Constant::Text(vname.clone()))?;
4927            let flag = self.alloc_reg()?;
4928            self.emit(Op::TestArm {
4929                dst: flag,
4930                target: t,
4931                variant: vidx,
4932            });
4933            let jnext = self.emit_placeholder_jump_if_false(flag);
4934            let msg = crate::semantics::builtins::inspect_unhandled_message(enum_name, vname);
4935            self.emit_fail(&msg)?;
4936            self.patch_jump_target(jnext, self.current_pc())?;
4937        }
4938        // Every constructor of the enum this Inspect matches has now been tested (the covered
4939        // ones by an ARM, the rest just above) — a value that fails ALL of them is not a value of
4940        // this enum at all, which a sound program cannot produce. Defensive, not reachable in
4941        // practice: names the enum, not a specific variant, since none of the KNOWN ones matched.
4942        self.emit_fail(&format!(
4943            "Inspect has no arm for the value (a `{enum_name}`, but not one of its \
4944             known constructors) and no Otherwise (matches must be exhaustive)"
4945        ))
4946    }
4947
4948    /// Compile `Inspect` as a chain of TestArm/JumpIfFalse arms (the
4949    /// tree-walker's linear arm scan).
4950    fn compile_inspect(
4951        &mut self,
4952        target: &Expr,
4953        arms: &[crate::ast::stmt::MatchArm],
4954    ) -> Result<(), Refusal> {
4955        let t = self.compile_expr(target)?;
4956        let mut end_jumps: Vec<usize> = Vec::new();
4957        let mut has_otherwise = false;
4958        for arm in arms.iter() {
4959            match arm.variant {
4960                None => {
4961                    // Otherwise: unconditional, and no arm after it runs.
4962                    has_otherwise = true;
4963                    let mark = self.enter_block();
4964                    for st in arm.body {
4965                        self.compile_stmt(st)?;
4966                    }
4967                    self.exit_block(mark);
4968                    break;
4969                }
4970                Some(variant) => {
4971                    let vname = self.interner.resolve(variant).to_string();
4972                    let vidx = self.add_const(Constant::Text(vname.clone()))?;
4973                    let flag = self.alloc_reg()?;
4974                    self.emit(Op::TestArm {
4975                        dst: flag,
4976                        target: t,
4977                        variant: vidx,
4978                    });
4979                    let jnext = self.emit_placeholder_jump_if_false(flag);
4980
4981                    let mark = self.enter_block();
4982                    // Struct arms bind by field NAME, inductive arms by
4983                    // POSITION; the flavor is only known at runtime, so
4984                    // BindArm carries both and dispatches there.
4985                    for (i, (field_name, binding_name)) in arm.bindings.iter().enumerate() {
4986                        let dst = self.let_reg(*binding_name)?;
4987                        // A `Some` arm binds the whole matched value, not a field of it — say so
4988                        // with a marker rather than leaving `BindArm` to guess from the shape.
4989                        let fname = if vname == "Some" {
4990                            crate::vm::SOME_BINDING_MARKER.to_string()
4991                        } else {
4992                            self.interner.resolve(*field_name).to_string()
4993                        };
4994                        let fidx = self.add_const(Constant::Text(fname))?;
4995                        self.emit(Op::BindArm {
4996                            dst,
4997                            target: t,
4998                            field: fidx,
4999                            index: u16::try_from(i)
5000                                .map_err(|_| "vm: too many arm bindings".to_string())?,
5001                        });
5002                    }
5003                    for st in arm.body {
5004                        self.compile_stmt(st)?;
5005                    }
5006                    self.exit_block(mark);
5007                    let j = self.emit_placeholder_jump();
5008                    end_jumps.push(j);
5009                    self.patch_jump_target(jnext, self.current_pc())?;
5010                }
5011            }
5012        }
5013        // An unmatched scrutinee (no arm's TestArm fired) falls to HERE. Without an Otherwise it is
5014        // a non-exhaustive match — LOUD, never a silent no-op. Matched arms jump PAST this via
5015        // `end_jumps`. Gauntlet finding G5: name the ACTUAL variant and type, with no runtime tag
5016        // extraction and no new `Op`/`BuiltinId` (LANES.md rule 16) — the compiler already knows,
5017        // statically, every OTHER constructor the matched enum has (`enum_variants`/`variant_enum`,
5018        // built from the discovery-pass type registry): test each UNCOVERED one in turn and fail
5019        // with ITS OWN compile-time-constant message, built by the SAME Rust function the
5020        // tree-walker calls (`semantics::builtins::inspect_unhandled_message`) — the wording is
5021        // byte-identical by construction, since both tiers call the identical function with the
5022        // identical two strings.
5023        if !has_otherwise {
5024            let covered: std::collections::HashSet<Symbol> =
5025                arms.iter().filter_map(|a| a.variant).collect();
5026            let enum_of = arms
5027                .iter()
5028                .find_map(|a| a.variant.and_then(|v| self.variant_enum.get(&v).copied()));
5029            let user_enum: Option<(String, Vec<String>)> = enum_of
5030                .and_then(|e| self.enum_variants.get(&e).map(|vs| (e, vs.clone())))
5031                .map(|(e, vs)| {
5032                    let enum_name = self.interner.resolve(e).to_string();
5033                    let uncovered = vs
5034                        .into_iter()
5035                        .filter(|v| !covered.contains(v))
5036                        .map(|v| self.interner.resolve(v).to_string())
5037                        .collect();
5038                    (enum_name, uncovered)
5039                });
5040            match user_enum {
5041                Some((enum_name, uncovered)) => {
5042                    self.emit_inspect_fallthrough(t, &enum_name, &uncovered)?
5043                }
5044                None => {
5045                    // `Option`/`Result` are language built-ins: no `## A ... is either:`
5046                    // declaration ever puts them in the discovery-pass registry, so they are
5047                    // matched by the ARM'S OWN TEXT here, not by `variant_enum`'s Symbol lookup.
5048                    // This also has to work when the Inspect names only ONE of a pair (`When Some
5049                    // (n):` with no `None` arm at all) — constructing `none` embeds the literal
5050                    // string "None" directly in bytecode (`compile_option_ctor`), never interning
5051                    // a Symbol for it, so "None" may not exist as a Symbol in this compilation's
5052                    // Interner AT ALL; text comparison sidesteps that entirely.
5053                    let covered_text: std::collections::HashSet<&str> = arms
5054                        .iter()
5055                        .filter_map(|a| a.variant)
5056                        .map(|v| self.interner.resolve(v))
5057                        .collect();
5058                    let builtin = [("Option", ["Some", "None"]), ("Result", ["Ok", "Err"])]
5059                        .into_iter()
5060                        .find(|(_, ctors)| ctors.iter().any(|c| covered_text.contains(c)));
5061                    match builtin {
5062                        Some((enum_name, ctors)) => {
5063                            let uncovered: Vec<String> = ctors
5064                                .iter()
5065                                .filter(|c| !covered_text.contains(**c))
5066                                .map(|s| s.to_string())
5067                                .collect();
5068                            self.emit_inspect_fallthrough(t, enum_name, &uncovered)?;
5069                        }
5070                        // No statically known enum (a dynamic value, or `types` was not given at
5071                        // all — the simple `Compiler::compile` entry point) — S20:
5072                        // `BuiltinId::InspectUnhandledDynamic` reads the scrutinee's OWN runtime
5073                        // constructor and type at the ONE place that knows them (there is no
5074                        // static enum to look up), the same words the tree-walker's own
5075                        // `inspect_unhandled` builds — fed the ALREADY-EVALUATED scrutinee
5076                        // register directly, no re-compiled source expression needed.
5077                        None => {
5078                            let arg = self.reserve_regs(1)?;
5079                            self.emit(Op::Move { dst: arg, src: t });
5080                            let dst = self.alloc_reg()?;
5081                            self.emit(Op::CallBuiltin {
5082                                dst,
5083                                builtin:
5084                                    crate::semantics::builtins::BuiltinId::InspectUnhandledDynamic,
5085                                args_start: arg,
5086                                arg_count: 1,
5087                            });
5088                        }
5089                    }
5090                }
5091            }
5092        }
5093        let end_pc = self.current_pc();
5094        for j in end_jumps {
5095            self.patch_jump_target(j, end_pc)?;
5096        }
5097        Ok(())
5098    }
5099
5100    /// An operand of an equality: `none` as the absence constant `nothing` (equal to it on every
5101    /// tier), anything else as itself.
5102    fn compile_equality_operand(&mut self, e: &Expr) -> Result<Reg, Refusal> {
5103        if !matches!(e, Expr::OptionNone) {
5104            return self.compile_expr(e);
5105        }
5106        let dst = self.alloc_reg()?;
5107        let idx = self.add_const(Constant::Nothing)?;
5108        self.emit(Op::LoadConst { dst, idx });
5109        Ok(dst)
5110    }
5111
5112    /// Compile `a new T …` — collections, or a struct with default-fill.
5113    /// Lower an Option constructor to the same tagged `Op::NewInductive` a `Result` uses.
5114    ///
5115    /// One place, so the type name and both constructor names are spelled exactly once — every
5116    /// backend derives its discriminant from those strings, so a second spelling would be a silent
5117    /// tier divergence rather than a compile error.
5118    fn compile_option_ctor(
5119        &mut self,
5120        ctor: &str,
5121        payload: Option<&Expr>,
5122        dst: Reg,
5123    ) -> Result<(), Refusal> {
5124        let tidx = self.add_const(Constant::Text("Option".to_string()))?;
5125        let cidx = self.add_const(Constant::Text(ctor.to_string()))?;
5126        let count: u16 = if payload.is_some() { 1 } else { 0 };
5127        let args_start = self.reserve_regs(count)?;
5128        if let Some(value) = payload {
5129            self.compile_expr_into(value, args_start)?;
5130        }
5131        self.emit(Op::NewInductive {
5132            dst,
5133            type_name: tidx,
5134            ctor: cidx,
5135            args_start,
5136            count,
5137        });
5138        Ok(())
5139    }
5140
5141    fn compile_new(
5142        &mut self,
5143        type_name: Symbol,
5144        init_fields: &[(Symbol, &Expr)],
5145        dst: Reg,
5146    ) -> Result<(), Refusal> {
5147        // Collection names win unconditionally (tree-walker order).
5148        match self.interner.resolve(type_name) {
5149            "Seq" | "List" => {
5150                self.emit(Op::NewEmptyList { dst });
5151                return Ok(());
5152            }
5153            "Set" | "HashSet" => {
5154                self.emit(Op::NewEmptySet { dst });
5155                return Ok(());
5156            }
5157            "Map" | "HashMap" => {
5158                self.emit(Op::NewEmptyMap { dst });
5159                return Ok(());
5160            }
5161            _ => {}
5162        }
5163        let name = self.interner.resolve(type_name).to_string();
5164        let name_idx = self.add_const(Constant::Text(name))?;
5165        self.emit(Op::NewStruct {
5166            dst,
5167            type_name: name_idx,
5168        });
5169
5170        let mut provided: std::collections::HashSet<Symbol> = std::collections::HashSet::new();
5171        for (field_sym, field_expr) in init_fields {
5172            provided.insert(*field_sym);
5173            let fname = self.interner.resolve(*field_sym).to_string();
5174            let fidx = self.add_const(Constant::Text(fname))?;
5175            let v = self.compile_expr(field_expr)?;
5176            self.emit(Op::StructInsert {
5177                obj: dst,
5178                field: fidx,
5179                value: v,
5180            });
5181        }
5182
5183        // Default-fill the declared fields not provided (tree-walker defaults
5184        // by declared type name).
5185        if let Some(def) = self.struct_defs.get(&type_name).cloned() {
5186            for (field_sym, type_sym, _) in def {
5187                if provided.contains(&field_sym) {
5188                    continue;
5189                }
5190                let fname = self.interner.resolve(field_sym).to_string();
5191                let fidx = self.add_const(Constant::Text(fname))?;
5192                let v = self.alloc_reg()?;
5193                match self.interner.resolve(type_sym) {
5194                    "Int" | "Byte" => {
5195                        let i = self.add_const(Constant::Int(0))?;
5196                        self.emit(Op::LoadConst { dst: v, idx: i });
5197                    }
5198                    "Float" => {
5199                        let i = self.add_const(Constant::Float(0.0))?;
5200                        self.emit(Op::LoadConst { dst: v, idx: i });
5201                    }
5202                    "Bool" => {
5203                        let i = self.add_const(Constant::Bool(false))?;
5204                        self.emit(Op::LoadConst { dst: v, idx: i });
5205                    }
5206                    "Text" | "String" => {
5207                        let i = self.add_const(Constant::Text(String::new()))?;
5208                        self.emit(Op::LoadConst { dst: v, idx: i });
5209                    }
5210                    "Char" => {
5211                        let i = self.add_const(Constant::Char('\0'))?;
5212                        self.emit(Op::LoadConst { dst: v, idx: i });
5213                    }
5214                    "Seq" | "List" => self.emit(Op::NewEmptyList { dst: v }),
5215                    "Set" | "HashSet" => self.emit(Op::NewEmptySet { dst: v }),
5216                    "Map" | "HashMap" => self.emit(Op::NewEmptyMap { dst: v }),
5217                    // A `Shared` struct's CRDT fields default to an empty live CRDT — the SAME
5218                    // name table the tree-walker's `new`-struct init reads.
5219                    name if crate::semantics::crdt::CrdtKind::of_type_name(name).is_some() => {
5220                        let kind = crate::semantics::crdt::CrdtKind::of_type_name(name)
5221                            .expect("guarded")
5222                            .new_crdt_code();
5223                        self.emit(Op::NewCrdt { dst: v, kind })
5224                    }
5225                    _ => {
5226                        let i = self.add_const(Constant::Nothing)?;
5227                        self.emit(Op::LoadConst { dst: v, idx: i });
5228                    }
5229                }
5230                self.emit(Op::StructInsert {
5231                    obj: dst,
5232                    field: fidx,
5233                    value: v,
5234                });
5235            }
5236        }
5237        Ok(())
5238    }
5239
5240    /// env.lg's `get(name)`, expanded into ops every downstream tier already lowers — the rule
5241    /// `mapOf` follows: whether the variable is set ([`BuiltinId::EnvHas`]), then `some` of its text
5242    /// ([`BuiltinId::EnvValue`]) or `none`, built by `NewInductive` as any other `Option` is. The
5243    /// tree-walker runs [`BuiltinId::EnvGet`] whole; both read the environment through one seam.
5244    ///
5245    /// The `none` is built first and the `some` last, so a backend that reads a register's payload
5246    /// positions from its last construction in program order (`vm/wasm/kind.rs`) binds the `Some`
5247    /// arm's text from the construction that carries it.
5248    fn compile_env_get(&mut self, name: &Expr, dst: Reg) -> Result<(), Refusal> {
5249        use crate::semantics::builtins::BuiltinId;
5250        // A builtin call clears its argument registers, so the first half reads a copy of the name and
5251        // the second takes the name itself.
5252        let key = self.reserve_regs(1)?;
5253        self.compile_expr_into(name, key)?;
5254        let asked = self.reserve_regs(1)?;
5255        self.emit(Op::Move { dst: asked, src: key });
5256        let present = self.alloc_reg()?;
5257        self.emit(Op::CallBuiltin {
5258            dst: present,
5259            builtin: BuiltinId::EnvHas,
5260            args_start: asked,
5261            arg_count: 1,
5262        });
5263        let j_some = self.current_pc();
5264        self.emit(Op::JumpIfTrue {
5265            cond: present,
5266            target: usize::MAX,
5267        });
5268        let option = self.add_const(Constant::Text("Option".to_string()))?;
5269        let none = self.add_const(Constant::Text("None".to_string()))?;
5270        let payload = self.reserve_regs(1)?;
5271        self.emit(Op::NewInductive {
5272            dst,
5273            type_name: option,
5274            ctor: none,
5275            args_start: payload,
5276            count: 0,
5277        });
5278        let j_end = self.emit_placeholder_jump();
5279        let some_pc = self.current_pc();
5280        self.patch_jump_target(j_some, some_pc)?;
5281        self.emit(Op::CallBuiltin {
5282            dst: payload,
5283            builtin: BuiltinId::EnvValue,
5284            args_start: key,
5285            arg_count: 1,
5286        });
5287        let some = self.add_const(Constant::Text("Some".to_string()))?;
5288        self.emit(Op::NewInductive {
5289            dst,
5290            type_name: option,
5291            ctor: some,
5292            args_start: payload,
5293            count: 1,
5294        });
5295        let end_pc = self.current_pc();
5296        self.patch_jump_target(j_end, end_pc)?;
5297        Ok(())
5298    }
5299
5300    /// Compile `and`/`or` — logical truthiness with short-circuit, Bool result,
5301    /// pure control flow (JumpIfTrue/False are `is_truthy`-based, so containers,
5302    /// floats and Text all follow the one truthiness definition). The right
5303    /// operand is compiled ONCE and only evaluated when the left doesn't decide.
5304    ///
5305    /// ```text
5306    ///   rL = eval(left)
5307    ///   JumpIfTrue  rL → eval  (and)  ; or: JumpIfFalse rL → eval
5308    ///   dst = false            (and)  ; or: dst = true   — short-circuit
5309    ///   Jump → end
5310    /// eval:
5311    ///   rR = eval(right)
5312    ///   JumpIfTrue  rR → t
5313    ///   dst = false
5314    ///   Jump → end
5315    /// t:
5316    ///   dst = true
5317    /// end:
5318    /// ```
5319    fn compile_short_circuit(
5320        &mut self,
5321        is_and: bool,
5322        left: &Expr,
5323        right: &Expr,
5324        dst: Reg,
5325    ) -> Result<(), Refusal> {
5326        let l = self.compile_expr(left)?;
5327
5328        let j_eval = self.current_pc();
5329        if is_and {
5330            self.emit(Op::JumpIfTrue {
5331                cond: l,
5332                target: usize::MAX,
5333            });
5334        } else {
5335            self.emit(Op::JumpIfFalse {
5336                cond: l,
5337                target: usize::MAX,
5338            });
5339        }
5340
5341        // Short-circuit result: `and` → false, `or` → true.
5342        let idx_false = self.add_const(Constant::Bool(false))?;
5343        let idx_true = self.add_const(Constant::Bool(true))?;
5344        self.emit(Op::LoadConst {
5345            dst,
5346            idx: if is_and { idx_false } else { idx_true },
5347        });
5348        let j_end = self.emit_placeholder_jump();
5349
5350        let eval_pc = self.current_pc();
5351        self.patch_jump_target(j_eval, eval_pc)?;
5352        let r = self.compile_expr(right)?;
5353        let j_true = self.current_pc();
5354        self.emit(Op::JumpIfTrue {
5355            cond: r,
5356            target: usize::MAX,
5357        });
5358        self.emit(Op::LoadConst {
5359            dst,
5360            idx: idx_false,
5361        });
5362        let j_end2 = self.emit_placeholder_jump();
5363        let t_pc = self.current_pc();
5364        self.patch_jump_target(j_true, t_pc)?;
5365        self.emit(Op::LoadConst { dst, idx: idx_true });
5366        self.patch_jump_target(j_end, self.current_pc())?;
5367        self.patch_jump_target(j_end2, self.current_pc())?;
5368        Ok(())
5369    }
5370
5371    /// Compile a call, writing the result to `dst`. Dispatch order mirrors the
5372    /// tree-walker exactly: `show` → kernel builtins → user functions →
5373    /// runtime "Unknown function". Arity errors fire at RUNTIME, BEFORE the
5374    /// arguments are evaluated.
5375    /// Compile `Launch a task to f with args` (and the handle-binding variant).
5376    /// Mirrors [`Self::compile_call`]'s function resolution + contiguous arg
5377    /// window, then emits `Spawn`/`SpawnHandle`.
5378    fn compile_spawn(
5379        &mut self,
5380        function: Symbol,
5381        args: &[&Expr],
5382        handle: Option<Symbol>,
5383    ) -> Result<(), Refusal> {
5384        let func = match self.fn_index.get(&function) {
5385            Some(&f) => f,
5386            None => {
5387                return self.emit_fail(&format!(
5388                    "Unknown task function: {}",
5389                    self.interner.resolve(function)
5390                ))
5391            }
5392        };
5393        let arg_count =
5394            u16::try_from(args.len()).map_err(|_| "vm: too many task arguments".to_string())?;
5395        let args_start = self.reserve_regs(arg_count)?;
5396        for (i, arg) in args.iter().enumerate() {
5397            self.compile_expr_into(arg, args_start + i as Reg)?;
5398        }
5399        match handle {
5400            Some(h) => {
5401                let dst = self.let_reg(h)?;
5402                self.emit(Op::SpawnHandle {
5403                    dst,
5404                    func,
5405                    args_start,
5406                    arg_count,
5407                });
5408            }
5409            None => self.emit(Op::Spawn {
5410                func,
5411                args_start,
5412                arg_count,
5413            }),
5414        }
5415        Ok(())
5416    }
5417
5418    fn place_key_count(expr: &Expr) -> Option<usize> {
5419        match expr {
5420            Expr::Identifier(_) => Some(0),
5421            Expr::FieldAccess { object, .. } => Self::place_key_count(object),
5422            Expr::Index { collection, .. } => Self::place_key_count(collection).map(|n| n + 1),
5423            _ => None,
5424        }
5425    }
5426
5427    /// Resolve the keys of a mutable argument once, in source order. The value
5428    /// at that place is taken before later arguments run and restored after the
5429    /// call using these same keys.
5430    fn compile_lent_place(
5431        &mut self,
5432        expr: &Expr,
5433        next_key: &mut Reg,
5434    ) -> Result<Option<LentPlace>, Refusal> {
5435        match expr {
5436            Expr::Identifier(root) => Ok(Some(LentPlace {
5437                root: *root,
5438                steps: Vec::new(),
5439            })),
5440            Expr::FieldAccess { object, field } => {
5441                let Some(mut place) = self.compile_lent_place(object, next_key)? else {
5442                    return Ok(None);
5443                };
5444                let name = self.interner.resolve(*field).to_string();
5445                place
5446                    .steps
5447                    .push(LentStep::Field(self.add_const(Constant::Text(name))?));
5448                Ok(Some(place))
5449            }
5450            Expr::Index { collection, index } => {
5451                let Some(mut place) = self.compile_lent_place(collection, next_key)? else {
5452                    return Ok(None);
5453                };
5454                let key = *next_key;
5455                *next_key += 1;
5456                self.compile_expr_into(index, key)?;
5457                place.steps.push(LentStep::Item(key));
5458                Ok(Some(place))
5459            }
5460            _ => Ok(None),
5461        }
5462    }
5463
5464    /// Write a previously resolved place. Each ancestor is made independent of
5465    /// other bindings before its child is extracted, then rebuilt immediately;
5466    /// no ancestor remains empty while another argument or the callee runs.
5467    fn mutate_lent_place(
5468        &mut self,
5469        place: &LentPlace,
5470        mutate: &mut dyn FnMut(&mut Self, Reg) -> Result<(), Refusal>,
5471    ) -> Result<bool, Refusal> {
5472        fn descend<'c>(
5473            c: &mut Compiler<'c>,
5474            parent: Reg,
5475            steps: &[LentStep],
5476            mutate: &mut dyn FnMut(&mut Compiler<'c>, Reg) -> Result<(), Refusal>,
5477        ) -> Result<(), Refusal> {
5478            let Some((step, rest)) = steps.split_first() else {
5479                return mutate(c, parent);
5480            };
5481            c.emit(Op::EnsureOwned { reg: parent });
5482            let child = c.alloc_reg()?;
5483            let key = match step {
5484                LentStep::Field(field) => {
5485                    let key = c.alloc_reg()?;
5486                    c.emit(Op::LoadConst {
5487                        dst: key,
5488                        idx: *field,
5489                    });
5490                    c.emit(Op::GetField {
5491                        dst: child,
5492                        obj: parent,
5493                        field: *field,
5494                    });
5495                    key
5496                }
5497                LentStep::Item(index) => {
5498                    c.emit(Op::Index {
5499                        dst: child,
5500                        collection: parent,
5501                        index: *index,
5502                    });
5503                    *index
5504                }
5505            };
5506            let empty = c.alloc_reg()?;
5507            let nothing = c.add_const(Constant::Nothing)?;
5508            c.emit(Op::LoadConst {
5509                dst: empty,
5510                idx: nothing,
5511            });
5512            c.emit(Op::SetIndex {
5513                collection: parent,
5514                index: key,
5515                value: empty,
5516            });
5517            descend(c, child, rest, mutate)?;
5518            c.emit(Op::SetIndex {
5519                collection: parent,
5520                index: key,
5521                value: child,
5522            });
5523            Ok(())
5524        }
5525        self.compile_place_mutation(&Expr::Identifier(place.root), &mut |c, root| {
5526            descend(c, root, &place.steps, mutate)
5527        })
5528    }
5529
5530    /// Call a function the program defines: arity check, the call-site COW barrier for
5531    /// mutable-borrow parameters, then `Op::Call`.
5532    fn compile_user_call(
5533        &mut self,
5534        function: Symbol,
5535        args: &[&Expr],
5536        dst: Reg,
5537    ) -> Result<(), Refusal> {
5538        let func = self.fn_index[&function];
5539        let name = self.interner.resolve(function);
5540        let param_count = self.functions[func as usize].param_count as usize;
5541        if args.len() != param_count {
5542            let msg = format!(
5543                "Function {} expects {} arguments, got {}",
5544                name,
5545                param_count,
5546                args.len()
5547            );
5548            let idx = self.add_const(Constant::Text(msg))?;
5549            self.emit(Op::FailWith { msg: idx });
5550            return Ok(());
5551        }
5552        let arg_count =
5553            u16::try_from(args.len()).map_err(|_| "vm: too many arguments".to_string())?;
5554        let inout = self
5555            .inout_params
5556            .get(&function)
5557            .cloned()
5558            .unwrap_or_default();
5559        let keys: usize = args
5560            .iter()
5561            .enumerate()
5562            .filter(|(i, _)| inout.contains(i))
5563            .map(|(_, arg)| Self::place_key_count(arg).unwrap_or(0))
5564            .sum();
5565        let keys =
5566            u16::try_from(keys).map_err(|_| "vm: too many mutable argument keys".to_string())?;
5567        // Callee registers overlay the caller from args_start onward. Keys used
5568        // after return belong below that window, even when their evaluation runs
5569        // later, at the mutable argument's position in source order.
5570        let mut next_key = self.reserve_regs(keys)?;
5571        let args_start = self.reserve_regs(arg_count)?;
5572        // Call-site COW barrier: before an identifier argument is passed to a
5573        // mutable-borrow parameter, isolate its buffer if shared (see
5574        // [`Op::EnsureOwned`]) so the callee's in-place writes stay value-semantic
5575        // for any aliasing caller. Emitted BEFORE materialization, while the
5576        // source register still holds the caller's handle. A no-op for the common
5577        // uniquely-owned `Set x to f(x, …)` consume-reassign.
5578        // An in-out argument that names a local: the binding's own value is isolated before it is
5579        // passed, so the callee's in-place writes reach no other copy of it.
5580        for &i in &inout {
5581            if let Some(Expr::Identifier(x)) = args.get(i) {
5582                if let NameRef::Local(x_reg) = self.resolve_name(*x) {
5583                    self.emit(Op::EnsureOwned { reg: x_reg });
5584                }
5585            }
5586        }
5587        if let Some(mb_idxs) = self.mut_borrow_params.get(&function).cloned() {
5588            for (i, arg) in args.iter().enumerate() {
5589                if mb_idxs.contains(&i) && !inout.contains(&i) {
5590                    if let Expr::Identifier(x) = arg {
5591                        // Skip an argument that is itself a COW-exempt local of the
5592                        // CURRENT function (a self-recursive `f(result, …)` where
5593                        // `result` aliases our own mutable-borrow param). It has no
5594                        // external alias — the mutable-borrow analysis proved that —
5595                        // so the barrier is a runtime no-op; omitting it keeps the
5596                        // op out of a hot, tier-able function body.
5597                        if self.current_exempt_syms.contains(x) {
5598                            continue;
5599                        }
5600                        if let NameRef::Local(x_reg) = self.resolve_name(*x) {
5601                            self.emit(Op::EnsureOwned { reg: x_reg });
5602                        }
5603                    }
5604                }
5605            }
5606        }
5607        let mut lent = Vec::new();
5608        for (i, arg) in args.iter().enumerate() {
5609            let argument = args_start + i as Reg;
5610            if inout.contains(&i) {
5611                if let Some(place) = self.compile_lent_place(arg, &mut next_key)? {
5612                    let nothing = self.add_const(Constant::Nothing)?;
5613                    self.mutate_lent_place(&place, &mut |c, slot| {
5614                        c.emit(Op::Move {
5615                            dst: argument,
5616                            src: slot,
5617                        });
5618                        c.emit(Op::LoadConst {
5619                            dst: slot,
5620                            idx: nothing,
5621                        });
5622                        Ok(())
5623                    })?;
5624                    self.emit(Op::EnsureOwned { reg: argument });
5625                    lent.push((i, place));
5626                    continue;
5627                }
5628            }
5629            self.compile_expr_into(arg, argument)?;
5630        }
5631        self.emit(Op::Call {
5632            dst,
5633            func,
5634            args_start,
5635            arg_count,
5636        });
5637        // The call leaves each mutable parameter's final value in its argument
5638        // register. Return it through the original place, with the original keys.
5639        for (i, place) in lent {
5640            let src = args_start + i as Reg;
5641            self.mutate_lent_place(&place, &mut |c, slot| {
5642                c.emit(Op::Move { dst: slot, src });
5643                Ok(())
5644            })?;
5645        }
5646        Ok(())
5647    }
5648
5649    fn compile_call(&mut self, function: Symbol, args: &[&Expr], dst: Reg) -> Result<(), Refusal> {
5650        use crate::semantics::builtins::{builtin_from_name, check_arity, BuiltinId};
5651
5652        // "Declarer wins": a function the program defines with a body is ITS function, whatever
5653        // builtin or intercepted native shares the name. Only a native declaration (`## To native
5654        // args`) defers to the engine's implementation.
5655        if self.fn_index.contains_key(&function) && !self.native_fns.contains_key(&function) {
5656            return self.compile_user_call(function, args, dst);
5657        }
5658        let name = self.interner.resolve(function);
5659        if name == "show" {
5660            // show(a, b, …) emits each argument; result is Nothing.
5661            for arg in args {
5662                let src = self.compile_expr(arg)?;
5663                self.emit(Op::Show { src });
5664            }
5665            let idx = self.add_const(Constant::Nothing)?;
5666            self.emit(Op::LoadConst { dst, idx });
5667            return Ok(());
5668        }
5669
5670        // `args()` is the program-argument system native (declared `## To
5671        // native args ()`); it resolves to the VM's stored argv, like the
5672        // compiled binary's `env::args()`. Intercepted by name BEFORE the
5673        // empty native-decl body would be reached, mirroring `show`.
5674        if name == "args" {
5675            self.emit(Op::Args { dst });
5676            return Ok(());
5677        }
5678
5679        // `loaded()` is the DATA-SEGMENT weight blob a chip receives separately from the kernel (like an
5680        // accelerator's HBM/SRAM): the SoC's UART loader preloads it into the heap as a `Seq of Int` at
5681        // pointer 0 (`dmem[0]=len, dmem[1..]=weights`) and seeds the bump allocator past it, so `loaded()`
5682        // is simply that pointer. Declared `## To native loaded () -> Seq of Int` for the type; intercepted
5683        // here by name (mirroring `args`) to a constant-0 pointer, so `item k of loaded()` reuses the
5684        // existing `Index` op (`dmem[0+k]`, bounds-checked by the preloaded length) — no new opcode.
5685        if name == "loaded" {
5686            let idx = self.add_const(Constant::Int(0))?;
5687            self.emit(Op::LoadConst { dst, idx });
5688            return Ok(());
5689        }
5690
5691        // `{k: v, …}` / `{a, b, …}` literals lower to `mapOf`/`setOf`; the VM
5692        // expands them into ops it already has (NewEmptyMap + SetIndex /
5693        // NewEmptySet + SetAdd) so every downstream tier — JIT, direct-WASM,
5694        // the PE dialects — sees only cataloged ops, no new CallBuiltin arm.
5695        if matches!(name, "mapOf" | "setOf") {
5696            let id = builtin_from_name(name).expect("mapOf/setOf are registered builtins");
5697            if let Err(msg) = check_arity(id, args.len()) {
5698                let idx = self.add_const(Constant::Text(msg))?;
5699                self.emit(Op::FailWith { msg: idx });
5700                return Ok(());
5701            }
5702            if id == BuiltinId::MapOf {
5703                self.emit(Op::NewEmptyMap { dst });
5704                for pair in args.chunks(2) {
5705                    let k = self.compile_expr_before(pair[0], &[pair[1]])?;
5706                    let v = self.compile_expr(pair[1])?;
5707                    self.emit(Op::SetIndex {
5708                        collection: dst,
5709                        index: k,
5710                        value: v,
5711                    });
5712                }
5713            } else {
5714                self.emit(Op::NewEmptySet { dst });
5715                for arg in args {
5716                    let v = self.compile_expr(arg)?;
5717                    self.emit(Op::SetAdd { set: dst, value: v });
5718                }
5719            }
5720            return Ok(());
5721        }
5722
5723        if let Some(id) = builtin_from_name(name) {
5724            if let Err(msg) = check_arity(id, args.len()) {
5725                let idx = self.add_const(Constant::Text(msg))?;
5726                self.emit(Op::FailWith { msg: idx });
5727                return Ok(());
5728            }
5729            // `format` evaluates only its first argument (tree-walker laziness).
5730            let used: &[&Expr] = if id == BuiltinId::Format && !args.is_empty() {
5731                &args[..1]
5732            } else {
5733                args
5734            };
5735            let arg_count =
5736                u16::try_from(used.len()).map_err(|_| "vm: too many arguments".to_string())?;
5737            let args_start = self.reserve_regs(arg_count)?;
5738            for (i, arg) in used.iter().enumerate() {
5739                self.compile_expr_into(arg, args_start + i as Reg)?;
5740            }
5741            self.emit(Op::CallBuiltin {
5742                dst,
5743                builtin: id,
5744                args_start,
5745                arg_count,
5746            });
5747            return Ok(());
5748        }
5749
5750        // System natives declared in the stdlib (`## To native …`, EMPTY bodies) —
5751        // compile to the SAME shared implementations the tree-walker calls, so the
5752        // tiers cannot drift. Guarded on membership in `native_fns`: a
5753        // user-defined function with a real body is not in the map and compiles as
5754        // an ordinary call below (declarer-wins).
5755        if let Some(&rust_path) = self.native_fns.get(&function) {
5756            // file.lg / random.lg / env.lg / time.lg → the shared `CallBuiltin` seam.
5757            if let Some(id) = crate::semantics::builtins::system_native(name, args.len()) {
5758                if id == BuiltinId::EnvGet {
5759                    return self.compile_env_get(args[0], dst);
5760                }
5761                let arg_count =
5762                    u16::try_from(args.len()).map_err(|_| "vm: too many arguments".to_string())?;
5763                let args_start = self.reserve_regs(arg_count)?;
5764                for (i, arg) in args.iter().enumerate() {
5765                    self.compile_expr_into(arg, args_start + i as Reg)?;
5766                }
5767                self.emit(Op::CallBuiltin {
5768                    dst,
5769                    builtin: id,
5770                    args_start,
5771                    arg_count,
5772                });
5773                return Ok(());
5774            }
5775            // crypto.lg's native kernels → `CallBuiltin(NativeKernel)` with the kernel's code as
5776            // argument 0 — the same `NativeKernel::call` the tree-walker runs.
5777            if let Some(kernel) = crate::semantics::native_kernels::NativeKernel::from_name(name)
5778                .filter(|k| k.arity() == args.len())
5779            {
5780                let arg_count = u16::try_from(args.len() + 1)
5781                    .map_err(|_| "vm: too many arguments".to_string())?;
5782                let args_start = self.reserve_regs(arg_count)?;
5783                let code = self.add_const(Constant::Int(kernel.code()))?;
5784                self.emit(Op::LoadConst {
5785                    dst: args_start,
5786                    idx: code,
5787                });
5788                for (i, arg) in args.iter().enumerate() {
5789                    self.compile_expr_into(arg, args_start + 1 + i as Reg)?;
5790                }
5791                self.emit(Op::CallBuiltin {
5792                    dst,
5793                    builtin: BuiltinId::NativeKernel,
5794                    args_start,
5795                    arg_count,
5796                });
5797                return Ok(());
5798            }
5799            // tcp.lg → `Op::Tcp` (suspends; the async io driver runs the SAME
5800            // `TcpRegistry::exec_values` the tree-walker calls).
5801            if let Some(op) = crate::concurrency::tcp_registry::TcpOp::from_name(name, args.len()) {
5802                let arg_count =
5803                    u16::try_from(args.len()).map_err(|_| "vm: too many arguments".to_string())?;
5804                let args_start = self.reserve_regs(arg_count)?;
5805                for (i, arg) in args.iter().enumerate() {
5806                    self.compile_expr_into(arg, args_start + i as Reg)?;
5807                }
5808                self.emit(Op::Tcp {
5809                    dst,
5810                    kind: op.code(),
5811                    args_start,
5812                    arg_count,
5813                });
5814                return Ok(());
5815            }
5816            // time.lg's `sleep(ms)` is the `Sleep ms.` statement, answering nothing.
5817            if name == "sleep" && args.len() == 1 {
5818                let duration = self.compile_expr(args[0])?;
5819                self.emit(Op::Sleep { duration });
5820                let idx = self.add_const(Constant::Nothing)?;
5821                self.emit(Op::LoadConst { dst, idx });
5822                return Ok(());
5823            }
5824            let refusal = crate::semantics::builtins::unimplemented_native(
5825                name,
5826                rust_path.map(|p| self.interner.resolve(p)),
5827            );
5828            let idx = self.add_const(Constant::Text(refusal))?;
5829            self.emit(Op::FailWith { msg: idx });
5830            return Ok(());
5831        }
5832
5833        if self.fn_index.contains_key(&function) {
5834            return self.compile_user_call(function, args, dst);
5835        }
5836
5837        // A variable holding a closure: call it by name. A bound non-Function
5838        // value errors "Unknown function: {name}" at runtime — the
5839        // tree-walker's by-name fallback.
5840        if !matches!(self.resolve_name(function), NameRef::Unbound) {
5841            let callee = self.compile_expr_before(&Expr::Identifier(function), args)?;
5842            let arg_count =
5843                u16::try_from(args.len()).map_err(|_| "vm: too many arguments".to_string())?;
5844            let args_start = self.reserve_regs(arg_count)?;
5845            for (i, arg) in args.iter().enumerate() {
5846                self.compile_expr_into(arg, args_start + i as Reg)?;
5847            }
5848            let name_idx = self.add_const(Constant::Text(name.to_string()))?;
5849            self.emit(Op::CallValue {
5850                dst,
5851                callee,
5852                args_start,
5853                arg_count,
5854                name_for_err: name_idx,
5855            });
5856            return Ok(());
5857        }
5858
5859        let msg = format!("Unknown function: {}", name);
5860        let idx = self.add_const(Constant::Text(msg))?;
5861        self.emit(Op::FailWith { msg: idx });
5862        Ok(())
5863    }
5864
5865    /// Compile `Show x to f` / `Give x to f` — the value goes to a FUNCTION
5866    /// recipient via the tree-walker's `call_function_with_values` dispatch,
5867    /// which knows only `show`, user functions, and closures (NOT the other
5868    /// builtins).
5869    fn compile_recipient_call(&mut self, recipient: Symbol, object: &Expr) -> Result<(), Refusal> {
5870        let name = self.interner.resolve(recipient);
5871        if name == "show" {
5872            let src = self.compile_expr(object)?;
5873            self.emit(Op::Show { src });
5874            return Ok(());
5875        }
5876        if let Some(&func) = self.fn_index.get(&recipient) {
5877            let param_count = self.functions[func as usize].param_count as usize;
5878            let args_start = self.reserve_regs(1)?;
5879            self.compile_expr_into(object, args_start)?;
5880            if param_count != 1 {
5881                let msg = format!("Function {} expects {} arguments, got 1", name, param_count);
5882                let idx = self.add_const(Constant::Text(msg))?;
5883                self.emit(Op::FailWith { msg: idx });
5884                return Ok(());
5885            }
5886            let dst = self.alloc_reg()?;
5887            self.emit(Op::Call {
5888                dst,
5889                func,
5890                args_start,
5891                arg_count: 1,
5892            });
5893            return Ok(());
5894        }
5895        // A variable holding a closure (the with_values closure fallback).
5896        if !matches!(self.resolve_name(recipient), NameRef::Unbound) {
5897            let args_start = self.reserve_regs(1)?;
5898            self.compile_expr_into(object, args_start)?;
5899            let callee = self.compile_expr(&Expr::Identifier(recipient))?;
5900            let dst = self.alloc_reg()?;
5901            let name_idx = self.add_const(Constant::Text(name.to_string()))?;
5902            self.emit(Op::CallValue {
5903                dst,
5904                callee,
5905                args_start,
5906                arg_count: 1,
5907                name_for_err: name_idx,
5908            });
5909            return Ok(());
5910        }
5911        // The object's side effects happen before the dispatch failure.
5912        let scratch = self.alloc_reg()?;
5913        self.compile_expr_into(object, scratch)?;
5914        let msg = format!("Unknown function: {}", name);
5915        let idx = self.add_const(Constant::Text(msg))?;
5916        self.emit(Op::FailWith { msg: idx });
5917        Ok(())
5918    }
5919
5920    /// Compile an interpolated string: parts accumulate into a Text register
5921    /// via Concat (Text+Text concatenation — identical to the tree-walker's
5922    /// push_str building).
5923    fn compile_interpolation(
5924        &mut self,
5925        parts: &[crate::ast::stmt::StringPart],
5926        dst: Reg,
5927    ) -> Result<(), Refusal> {
5928        use crate::ast::stmt::StringPart;
5929
5930        let empty = self.add_const(Constant::Text(String::new()))?;
5931        self.emit(Op::LoadConst { dst, idx: empty });
5932        for part in parts {
5933            match part {
5934                StringPart::Literal(sym) => {
5935                    let idx =
5936                        self.add_const(Constant::Text(self.interner.resolve(*sym).to_string()))?;
5937                    let lit = self.alloc_reg()?;
5938                    self.emit(Op::LoadConst { dst: lit, idx });
5939                    self.emit(Op::Concat {
5940                        dst,
5941                        lhs: dst,
5942                        rhs: lit,
5943                    });
5944                }
5945                StringPart::Expr {
5946                    value,
5947                    format_spec,
5948                    debug,
5949                } => {
5950                    let v = self.compile_expr(value)?;
5951                    let needs_format = format_spec.is_some() || *debug;
5952                    let piece = if needs_format {
5953                        let spec = match format_spec {
5954                            Some(sym) => self.add_const(Constant::Text(
5955                                self.interner.resolve(*sym).to_string(),
5956                            ))?,
5957                            None => u32::MAX,
5958                        };
5959                        let debug_prefix = if *debug {
5960                            let prefix = match value {
5961                                Expr::Identifier(sym) => self.interner.resolve(*sym).to_string(),
5962                                _ => "expr".to_string(),
5963                            };
5964                            self.add_const(Constant::Text(prefix))?
5965                        } else {
5966                            u32::MAX
5967                        };
5968                        let formatted = self.alloc_reg()?;
5969                        self.emit(Op::FormatValue {
5970                            dst: formatted,
5971                            src: v,
5972                            spec,
5973                            debug_prefix,
5974                        });
5975                        formatted
5976                    } else {
5977                        v
5978                    };
5979                    self.emit(Op::Concat {
5980                        dst,
5981                        lhs: dst,
5982                        rhs: piece,
5983                    });
5984                }
5985            }
5986        }
5987        Ok(())
5988    }
5989
5990    /// Compile a closure literal: the body becomes an anonymous function
5991    /// emitted INLINE (jumped over at the creation site); local captures are
5992    /// snapshotted from a register window, global captures from the globals
5993    /// table at creation time. Frame layout:
5994    /// `[params…, capture values…, capture-present flags…]`.
5995    fn compile_closure(
5996        &mut self,
5997        params: &[(Symbol, &crate::ast::stmt::TypeExpr)],
5998        body: &crate::ast::stmt::ClosureBody,
5999        dst: Reg,
6000    ) -> Result<(), Refusal> {
6001        use crate::ast::stmt::ClosureBody;
6002        use crate::interpreter::Interpreter;
6003
6004        let free = Interpreter::free_vars_in_closure(params, body);
6005        let mut captures: Vec<(Symbol, Option<u16>)> = Vec::new();
6006        let mut local_sources: Vec<Reg> = Vec::new();
6007        for sym in free {
6008            match self.resolve_name(sym) {
6009                NameRef::Local(r) => {
6010                    captures.push((sym, None));
6011                    local_sources.push(r);
6012                }
6013                NameRef::CaptureOrGlobal { value, global, .. } => {
6014                    // Closure-in-closure over a promoted capture: snapshot the
6015                    // capture slot (the live-global fall-through nests with
6016                    // the outer flag at creation time only).
6017                    let _ = global;
6018                    captures.push((sym, None));
6019                    local_sources.push(value);
6020                }
6021                NameRef::Global(g) => captures.push((sym, Some(g))),
6022                NameRef::Unbound => {}
6023            }
6024        }
6025
6026        // Move local capture sources into a contiguous window for MakeClosure.
6027        let local_count =
6028            u16::try_from(local_sources.len()).map_err(|_| "vm: too many captures".to_string())?;
6029        let locals_start = self.reserve_regs(local_count)?;
6030        for (i, src) in local_sources.iter().enumerate() {
6031            let w = locals_start + i as Reg;
6032            if *src != w {
6033                self.emit(Op::Move { dst: w, src: *src });
6034            }
6035        }
6036
6037        // Register the body as a function and compile it inline, jumped over.
6038        let func_idx = u16::try_from(self.functions.len())
6039            .map_err(|_| "vm: too many functions".to_string())?;
6040        let param_count =
6041            u16::try_from(params.len()).map_err(|_| "vm: too many parameters".to_string())?;
6042        let jover = self.emit_placeholder_jump();
6043        self.functions.push(CompiledFunction {
6044            name: Symbol::default(),
6045            entry_pc: self.code.len(),
6046            param_count,
6047            register_count: 0,
6048            captures: captures.clone(),
6049            named_regs: Vec::new(),
6050            // Closures carry no declarations — all-Int is the historical
6051            // entry-guard contract (kept for the VM/JIT tiering path).
6052            param_kinds: vec![
6053                Some(super::native_tier::ParamKind::Scalar(
6054                    super::native_tier::SlotKind::Int
6055                ));
6056                param_count as usize
6057            ],
6058            ret_kind: None,
6059            // The closure's DECLARED parameter types — a `(n: Float)` closure must type its param as
6060            // Float, not the all-Int entry-guard default, or a static backend (the WASM AOT) mis-sizes
6061            // its signature (f64 arg vs i64 param). Additive: only the AOT reads `param_types` (the VM/
6062            // JIT use `param_kinds`, left untouched). Scalars resolve with an empty user-type map; a
6063            // struct/enum closure parameter resolves via the compiler's `user_types` map.
6064            param_types: params
6065                .iter()
6066                .map(|(_, ty)| boundary_of_type_expr(ty, &self.user_types, self.interner))
6067                .collect(),
6068            return_type: None,
6069            // Closures carry no `mutable` declarations.
6070            mutable_param_regs: Vec::new(),
6071            cow_exempt_regs: Vec::new(),
6072        });
6073
6074        // Shelve the enclosing frame's compilation state.
6075        let saved_scopes = std::mem::replace(&mut self.scopes, vec![HashMap::new()]);
6076        let saved_next = self.next_reg;
6077        let saved_max = self.max_reg;
6078        let saved_flow = std::mem::take(&mut self.flow_stack);
6079        let saved_in_fn = self.in_function;
6080        let saved_ctx = self.closure_ctx.take();
6081        let saved_named = std::mem::take(&mut self.named);
6082
6083        self.in_function = true;
6084        let p = param_count;
6085        let cap_n = captures.len() as Reg;
6086        for (i, (psym, _)) in params.iter().enumerate() {
6087            self.scopes.last_mut().unwrap().insert(*psym, i as Reg);
6088            self.mark_named(i as Reg);
6089        }
6090        let mut ctx: HashMap<Symbol, (Reg, Reg)> = HashMap::new();
6091        for (k, (sym, global)) in captures.iter().enumerate() {
6092            let value = p + k as Reg;
6093            self.scopes.last_mut().unwrap().insert(*sym, value);
6094            self.mark_named(value);
6095            if global.is_some() {
6096                ctx.insert(*sym, (value, p + cap_n + k as Reg));
6097            }
6098        }
6099        self.next_reg = p + 2 * cap_n;
6100        self.max_reg = self.next_reg;
6101        self.closure_ctx = Some(ctx);
6102
6103        let body_result = (|| -> Result<(), Refusal> {
6104            match body {
6105                ClosureBody::Expression(e) => {
6106                    let r = self.compile_expr(e)?;
6107                    self.emit(Op::Return { src: r });
6108                }
6109                ClosureBody::Block(block) => {
6110                    for st in block.iter() {
6111                        self.compile_stmt(st)?;
6112                    }
6113                    self.emit(Op::ReturnNothing);
6114                }
6115            }
6116            Ok(())
6117        })();
6118        self.functions[func_idx as usize].register_count = self.max_reg as usize;
6119        let mut cnamed = std::mem::replace(&mut self.named, saved_named);
6120        cnamed.resize(self.functions[func_idx as usize].register_count, false);
6121        self.functions[func_idx as usize].named_regs = cnamed;
6122
6123        // Restore the enclosing frame's state (even when the body failed).
6124        self.scopes = saved_scopes;
6125        self.next_reg = saved_next;
6126        self.max_reg = saved_max.max(self.next_reg);
6127        self.flow_stack = saved_flow;
6128        self.in_function = saved_in_fn;
6129        self.closure_ctx = saved_ctx;
6130        body_result?;
6131
6132        self.patch_jump_target(jover, self.current_pc())?;
6133        self.emit(Op::MakeClosure {
6134            dst,
6135            func: func_idx,
6136            locals_start,
6137        });
6138        Ok(())
6139    }
6140}
6141
6142/// The SENTENCE a `UiStmt` was written as, for a refusal that points at the author's own words.
6143///
6144/// Spelled as the verb reads in a page rather than as the variant is spelled in Rust: somebody
6145/// reading the message is looking at `Set the title to …`, not at `SetTitle`.
6146fn ui_verb_phrase(u: &crate::ast::stmt::UiStmt<'_>) -> &'static str {
6147    use crate::ast::stmt::UiStmt as U;
6148    match u {
6149        U::RaiseWindowEvent { .. } => "Raise",
6150        U::Focus { .. } => "Focus",
6151        U::Blur { .. } => "Blur",
6152        U::Hover { .. } => "Hover",
6153        U::ScrollTo { .. } => "Scroll to",
6154        U::AddClass { .. } => "Add class … to",
6155        U::RemoveClass { .. } => "Remove class … from",
6156        U::SelectText { .. } => "Select the text in",
6157        U::CopyToClipboard { .. } => "Copy … to the clipboard",
6158        U::Download { .. } => "Download … as",
6159        U::Navigate { .. } => "Navigate to",
6160        U::ReplaceUrl { .. } => "Replace the URL with",
6161        U::GoBack => "Go back",
6162        U::SetTitle { .. } => "Set the title to",
6163        U::Save { .. } => "Save … as",
6164        U::Load { .. } => "Load … into",
6165        U::Forget { .. } => "Forget",
6166        U::Reload => "Reload the page",
6167        U::Notify { .. } => "Notify",
6168        U::Publish { .. } => "Publish … on",
6169        U::Toggle { .. } => "Toggle",
6170        U::StopTimer { .. } => "Stop the timer",
6171        U::StartTimer { .. } => "Start the timer",
6172        U::CallStore { .. } => "Call … 's action",
6173        U::Click { .. } => "Click",
6174        U::Submit { .. } => "Submit",
6175        U::Choose { .. } => "Choose",
6176        U::Press { .. } => "Press",
6177        U::TypeInto { .. } => "Type … into",
6178        U::Mount { .. } => "Mount",
6179    }
6180}
6181
6182/// An operand of a driving verb's failure message: known at compile time (a literal — every
6183/// selector and key a test actually writes), or held in a register until run time — see
6184/// [`Compiler::keep_operand`].
6185enum DriveOperand {
6186    Known(String),
6187    Held(Reg),
6188}
6189
6190/// One piece of a failure text: words, or a register whose text is spliced in at run time.
6191#[derive(Clone)]
6192enum DrivePiece {
6193    Text(String),
6194    Plain(Reg),
6195}
6196
6197/// A `semantics::drive` failure message as the compiler emits it: `drive` spells every word, and
6198/// an operand only known at run time is spliced into the place `drive` put it.
6199struct DriveText {
6200    pieces: Vec<DrivePiece>,
6201}
6202
6203impl DriveText {
6204    /// Render `message(selector, key)` — a `semantics::drive` function — with each run-time
6205    /// operand replaced by a marker, then cut at the markers. `drive` quotes a selector as `{:?}`
6206    /// does, and a key either bare (`a Enter press`) or quoted the same way (the value a `Type`
6207    /// enters); a run-time operand is spliced where its marker stood — between the same quote marks
6208    /// for a quoted one, which is that rendering for any text without a `"`, a `\` or a control
6209    /// character.
6210    fn render(
6211        message: impl Fn(&str, Option<&str>) -> String,
6212        selector: &DriveOperand,
6213        key: Option<&DriveOperand>,
6214    ) -> DriveText {
6215        const SELECTOR_MARK: &str = "\u{1}selector\u{1}";
6216        const KEY_MARK: &str = "\u{1}key\u{1}";
6217        let selector_text = match selector {
6218            DriveOperand::Known(s) => s.as_str(),
6219            DriveOperand::Held(_) => SELECTOR_MARK,
6220        };
6221        let key_text = key.map(|k| match k {
6222            DriveOperand::Known(s) => s.as_str(),
6223            DriveOperand::Held(_) => KEY_MARK,
6224        });
6225        let text = message(selector_text, key_text);
6226        let quoted = |r: Reg| {
6227            vec![
6228                DrivePiece::Text("\"".to_string()),
6229                DrivePiece::Plain(r),
6230                DrivePiece::Text("\"".to_string()),
6231            ]
6232        };
6233        // Each marker a run-time operand left: its text in the message, and what stands for it.
6234        let mut marks: Vec<(String, Vec<DrivePiece>)> = Vec::new();
6235        if let DriveOperand::Held(r) = *selector {
6236            marks.push((format!("{SELECTOR_MARK:?}"), quoted(r)));
6237        }
6238        if let Some(DriveOperand::Held(r)) = key {
6239            marks.push((format!("{KEY_MARK:?}"), quoted(*r)));
6240            marks.push((KEY_MARK.to_string(), vec![DrivePiece::Plain(*r)]));
6241        }
6242        let mut pieces = Vec::new();
6243        let mut rest = text.as_str();
6244        while let Some((at, i)) = marks
6245            .iter()
6246            .enumerate()
6247            .filter_map(|(i, (m, _))| rest.find(m.as_str()).map(|at| (at, i)))
6248            .min()
6249        {
6250            if at > 0 {
6251                pieces.push(DrivePiece::Text(rest[..at].to_string()));
6252            }
6253            let (mark, piece) = &marks[i];
6254            pieces.extend(piece.iter().cloned());
6255            rest = &rest[at + mark.len()..];
6256        }
6257        if !rest.is_empty() || pieces.is_empty() {
6258            pieces.push(DrivePiece::Text(rest.to_string()));
6259        }
6260        // Adjacent words fold into one constant.
6261        let mut folded: Vec<DrivePiece> = Vec::with_capacity(pieces.len());
6262        for piece in pieces {
6263            match (folded.last_mut(), piece) {
6264                (Some(DrivePiece::Text(prev)), DrivePiece::Text(t)) => prev.push_str(&t),
6265                (_, piece) => folded.push(piece),
6266            }
6267        }
6268        DriveText { pieces: folded }
6269    }
6270}
6271
6272/// How an LGX construct is named in a refusal: by the header its author wrote.
6273///
6274/// A page's component is interned under a lowered name (`__page__about`) that appears nowhere in
6275/// the file, so a page is named by its `## Page` header, an error page by its status, and a
6276/// component by its declaration.
6277fn construct_heading(def: &crate::ast::component::ComponentDef<'_>, interner: &Interner) -> String {
6278    use crate::ast::component::ComponentKind;
6279    match &def.kind {
6280        ComponentKind::Page { path, .. } => format!("## Page {}", interner.resolve(*path)),
6281        ComponentKind::ErrorPage { status } => format!("## Error page {status}"),
6282        ComponentKind::Store { .. } => format!("## Store {}", interner.resolve(def.name)),
6283        ComponentKind::Component => format!("## Component {}", interner.resolve(def.name)),
6284    }
6285}
6286
6287/// The refusal a `Mount` of each component in `stmts` raises, by component: worded around the
6288/// reason `lowerable` gives and located at the construct it refused.
6289fn mount_refusals(
6290    stmts: &[Stmt],
6291    interner: &Interner,
6292    types: Option<&crate::analysis::TypeRegistry>,
6293) -> HashMap<Symbol, Refusal> {
6294    use logicaffeine_language::parser::lgx_lower::lowerable;
6295    let defs: Vec<_> = stmts
6296        .iter()
6297        .filter_map(|s| match s {
6298            Stmt::ComponentDef(d) => Some((**d).clone()),
6299            _ => None,
6300        })
6301        .collect();
6302    let mut out = HashMap::new();
6303    for def in &defs {
6304        let Err(why) = lowerable(def, &defs, types, interner) else {
6305            continue;
6306        };
6307        // `Trigger::undeliverable` is the one table every tier reads for the sentences NO tier
6308        // delivers; a component waiting on one is refused for that, not for a gap in this tier.
6309        let tail = if def
6310            .events
6311            .iter()
6312            .any(|e| e.trigger.undeliverable().is_some())
6313        {
6314            "No tier delivers that yet, so the page is refused whole rather than rendered with a \
6315             sentence in it that would never fire."
6316        } else {
6317            "The page is refused whole rather than rendered with a piece missing."
6318        };
6319        let heading = construct_heading(def, interner);
6320        out.insert(
6321            def.name,
6322            Refusal::at(
6323                why.span,
6324                format!(
6325                    "`{heading}` cannot run on this tier: {}. {tail}",
6326                    why.message
6327                ),
6328            ),
6329        );
6330    }
6331    out
6332}
6333
6334/// The refusal each `## Route` this program cannot lower raises, keyed by `(method, path)`.
6335///
6336/// Decided once from the WHOLE program by `lgx_lower::route_refusals`, because a `-> View`
6337/// route's lowerability depends on the components beside it, and located at the node it refused —
6338/// a `-> View` route's own `NotLowerable` already carries that node's span; a parameter or
6339/// answer-type refusal carries the route's own header, having nothing more specific to point at.
6340fn route_refusal_map(
6341    stmts: &[Stmt],
6342    interner: &Interner,
6343    is_record: &dyn Fn(Symbol) -> bool,
6344) -> HashMap<(Symbol, Symbol), Refusal> {
6345    logicaffeine_language::parser::lgx_lower::route_refusals(stmts, interner, is_record)
6346        .into_iter()
6347        .map(|(method, path, why)| {
6348            let heading =
6349                logicaffeine_language::parser::lgx_lower::route_heading(method, path, interner);
6350            (
6351                (method, path),
6352                Refusal::at(
6353                    why.span,
6354                    format!("`{heading}` cannot run on this tier yet: {}.", why.message),
6355                ),
6356            )
6357        })
6358        .collect()
6359}
6360
6361/// The refusal an `## Error page` raises when the server-side walk cannot render its template —
6362/// located at the node the walk refused.
6363fn error_page_refusal(
6364    def: &crate::ast::component::ComponentDef<'_>,
6365    interner: &Interner,
6366) -> Option<Refusal> {
6367    use crate::ast::component::ComponentKind;
6368    let ComponentKind::ErrorPage { .. } = def.kind else {
6369        return None;
6370    };
6371    let heading = construct_heading(def, interner);
6372    let why = match def.view.as_ref() {
6373        Some(v) => {
6374            logicaffeine_language::parser::lgx_lower::view_html_lowerable(&v.nodes, interner)
6375                .err()?
6376        }
6377        None => {
6378            return Some(Refusal::at(
6379                def.span,
6380                format!(
6381                    "`{heading}` cannot be rendered on this tier yet: it has no `View:` to render."
6382                ),
6383            ))
6384        }
6385    };
6386    Some(Refusal::at(
6387        why.span,
6388        format!(
6389            "`{heading}` cannot be rendered on this tier yet: {}.",
6390            why.message
6391        ),
6392    ))
6393}
6394
6395/// The names of every record type the program declares — a `## A … has:` or one the discovery
6396/// pass registered — which is what a route's answer type is checked against.
6397fn record_names(
6398    stmts: &[Stmt],
6399    types: Option<&crate::analysis::TypeRegistry>,
6400) -> std::collections::HashSet<Symbol> {
6401    let mut names: std::collections::HashSet<Symbol> = stmts
6402        .iter()
6403        .filter_map(|s| match s {
6404            Stmt::StructDef { name, .. } => Some(*name),
6405            _ => None,
6406        })
6407        .collect();
6408    if let Some(registry) = types {
6409        names.extend(registry.iter_types().filter_map(|(name, def)| {
6410            matches!(def, crate::analysis::registry::TypeDef::Struct { .. }).then_some(*name)
6411        }));
6412    }
6413    names
6414}
6415
6416/// Every refusal this tier raises for an LGX construct in `stmts` — a mounted component or page it
6417/// cannot lower, a `## Route`, an `## Error page` — each located at the construct its author
6418/// wrote, in the order a compile meets them.
6419///
6420/// A compile stops at the first; an editor shows them all. Both read the refusals the compiler's
6421/// own arms raise, so the two cannot disagree about what is refused, what it is called, or where.
6422pub fn lgx_refusals(
6423    stmts: &[Stmt],
6424    interner: &Interner,
6425    types: Option<&crate::analysis::TypeRegistry>,
6426) -> Vec<Refusal> {
6427    let mounts = mount_refusals(stmts, interner, types);
6428    let records = record_names(stmts, types);
6429    let routes = route_refusal_map(stmts, interner, &|sym| records.contains(&sym));
6430
6431    fn visit(
6432        s: &Stmt,
6433        interner: &Interner,
6434        mounts: &HashMap<Symbol, Refusal>,
6435        routes: &HashMap<(Symbol, Symbol), Refusal>,
6436        out: &mut Vec<Refusal>,
6437    ) {
6438        let found = match s {
6439            Stmt::ComponentDef(def) => error_page_refusal(def, interner),
6440            Stmt::Ui(crate::ast::stmt::UiStmt::Mount { component, .. }) => {
6441                mounts.get(component).cloned()
6442            }
6443            Stmt::RouteDef { method, path, .. } => routes.get(&(*method, *path)).cloned(),
6444            _ => None,
6445        };
6446        if let Some(r) = found {
6447            if !out.contains(&r) {
6448                out.push(r);
6449            }
6450        }
6451        if let Stmt::FunctionDef { body, .. } = s {
6452            for st in body.iter() {
6453                visit(st, interner, mounts, routes, out);
6454            }
6455        }
6456        visit_stmt_exprs(s, &mut |e| {
6457            if let Expr::Closure {
6458                body: crate::ast::stmt::ClosureBody::Block(block),
6459                ..
6460            } = e
6461            {
6462                for st in block.iter() {
6463                    visit(st, interner, mounts, routes, out);
6464                }
6465            }
6466        });
6467        for_each_child_block(s, &mut |block| {
6468            for st in block {
6469                visit(st, interner, mounts, routes, out);
6470            }
6471        });
6472    }
6473
6474    let mut out = Vec::new();
6475    // Main's statements compile before any function body, so their refusals come first.
6476    for s in stmts
6477        .iter()
6478        .filter(|s| !matches!(s, Stmt::FunctionDef { .. }))
6479    {
6480        visit(s, interner, &mounts, &routes, &mut out);
6481    }
6482    for s in stmts
6483        .iter()
6484        .filter(|s| matches!(s, Stmt::FunctionDef { .. }))
6485    {
6486        visit(s, interner, &mounts, &routes, &mut out);
6487    }
6488    out
6489}
6490
6491/// Collect identifiers that appear inside function or closure bodies — the
6492/// names that, when bound at Main top level, must live in the globals table.
6493/// `at_main` is true while walking Main-level statements (whose own
6494/// identifiers are frame-local); inside a FunctionDef body or a Closure body
6495/// every identifier counts.
6496fn collect_nonlocal_idents_stmt(
6497    s: &Stmt,
6498    at_main: bool,
6499    out: &mut std::collections::HashSet<Symbol>,
6500) {
6501    use crate::ast::stmt::ClosureBody;
6502    use crate::interpreter::Interpreter;
6503
6504    if let Stmt::FunctionDef { params, body, .. } = s {
6505        // Everything free in a function body is a nonlocal reference.
6506        let free = Interpreter::free_vars_in_closure(params, &ClosureBody::Block(body));
6507        out.extend(free);
6508        return;
6509    }
6510    // Walk this statement's expressions for Closure literals (whose free vars
6511    // are nonlocal) and recurse into nested statements.
6512    visit_stmt_exprs(s, &mut |e| {
6513        if let Expr::Closure { params, body, .. } = e {
6514            let free = Interpreter::free_vars_in_closure(params, body);
6515            out.extend(free);
6516        }
6517    });
6518    for_each_child_block(s, &mut |block| {
6519        for st in block {
6520            collect_nonlocal_idents_stmt(st, at_main, out);
6521        }
6522    });
6523}
6524
6525/// Apply `f` to every expression directly held by `s` (and, via the walker in
6526/// `f` itself when needed, their subexpressions are reached by the free-vars
6527/// collector — Closure bodies included).
6528fn visit_stmt_exprs(s: &Stmt, f: &mut dyn FnMut(&Expr)) {
6529    // Iterative walk: expressions can be arbitrarily deep (degenerate inputs),
6530    // so no native recursion here.
6531    fn walk_expr<'a>(root: &'a Expr<'a>, f: &mut dyn FnMut(&Expr)) {
6532        let mut stack: Vec<&Expr> = vec![root];
6533        while let Some(e) = stack.pop() {
6534            f(e);
6535            match e {
6536                Expr::BinaryOp { left, right, .. } => {
6537                    stack.push(left);
6538                    stack.push(right);
6539                }
6540                Expr::Not { operand } => stack.push(operand),
6541                Expr::Call { args, .. } => stack.extend(args.iter().copied()),
6542                Expr::CallExpr { callee, args } => {
6543                    stack.push(callee);
6544                    stack.extend(args.iter().copied());
6545                }
6546                Expr::Index { collection, index } => {
6547                    stack.push(collection);
6548                    stack.push(index);
6549                }
6550                Expr::Slice {
6551                    collection,
6552                    start,
6553                    end,
6554                } => {
6555                    stack.push(collection);
6556                    stack.push(start);
6557                    stack.push(end);
6558                }
6559                Expr::Copy { expr } => stack.push(expr),
6560                Expr::Give { value } => stack.push(value),
6561                Expr::Length { collection } => stack.push(collection),
6562                Expr::Contains { collection, value } => {
6563                    stack.push(collection);
6564                    stack.push(value);
6565                }
6566                Expr::Union { left, right } | Expr::Intersection { left, right } => {
6567                    stack.push(left);
6568                    stack.push(right);
6569                }
6570                Expr::List(items) | Expr::Tuple(items) => stack.extend(items.iter().copied()),
6571                Expr::Range { start, end } => {
6572                    stack.push(start);
6573                    stack.push(end);
6574                }
6575                Expr::FieldAccess { object, .. } => stack.push(object),
6576                Expr::New { init_fields, .. } => {
6577                    stack.extend(init_fields.iter().map(|(_, fe)| *fe));
6578                }
6579                Expr::NewVariant { fields, .. } => {
6580                    stack.extend(fields.iter().map(|(_, fe)| *fe));
6581                }
6582                Expr::OptionSome { value } => stack.push(value),
6583                Expr::WithCapacity { value, .. } => stack.push(value),
6584                _ => {}
6585            }
6586        }
6587    }
6588
6589    use crate::ast::stmt::ReadSource;
6590    match s {
6591        Stmt::Let { value, .. } | Stmt::Set { value, .. } => walk_expr(value, f),
6592        Stmt::Return { value: Some(e) } => walk_expr(e, f),
6593        Stmt::Call { args, .. } => {
6594            for a in args {
6595                walk_expr(a, f);
6596            }
6597        }
6598        Stmt::If { cond, .. } | Stmt::While { cond, .. } => walk_expr(cond, f),
6599        Stmt::Repeat { iterable, .. } => walk_expr(iterable, f),
6600        Stmt::Show { object, .. } | Stmt::Give { object, .. } => walk_expr(object, f),
6601        Stmt::Push { value, collection }
6602        | Stmt::Add { value, collection }
6603        | Stmt::Remove { value, collection } => {
6604            walk_expr(value, f);
6605            walk_expr(collection, f);
6606        }
6607        Stmt::SetIndex {
6608            collection,
6609            index,
6610            value,
6611        } => {
6612            walk_expr(collection, f);
6613            walk_expr(index, f);
6614            walk_expr(value, f);
6615        }
6616        Stmt::SetField { object, value, .. } => {
6617            walk_expr(object, f);
6618            walk_expr(value, f);
6619        }
6620        Stmt::Inspect { target, .. } => walk_expr(target, f),
6621        Stmt::RuntimeAssert {
6622            condition, reason, ..
6623        } => {
6624            walk_expr(condition, f);
6625            if let Some(r) = reason {
6626                walk_expr(r, f);
6627            }
6628        }
6629        Stmt::Fail { reason } => walk_expr(reason, f),
6630        Stmt::Sleep { milliseconds } => walk_expr(milliseconds, f),
6631        Stmt::IncreaseCrdt { amount, .. } | Stmt::DecreaseCrdt { amount, .. } => {
6632            walk_expr(amount, f)
6633        }
6634        Stmt::MergeCrdt { source, .. } | Stmt::JoinCrdt { source, .. } => walk_expr(source, f),
6635        Stmt::WriteFile { content, path } => {
6636            walk_expr(content, f);
6637            walk_expr(path, f);
6638        }
6639        Stmt::ReadFrom {
6640            source: ReadSource::File(p),
6641            ..
6642        } => walk_expr(p, f),
6643        _ => {}
6644    }
6645}
6646
6647/// Apply `f` to every nested statement block of `s`.
6648fn for_each_child_block<'a>(s: &Stmt<'a>, f: &mut dyn FnMut(&[Stmt<'a>])) {
6649    match s {
6650        Stmt::If {
6651            then_block,
6652            else_block,
6653            ..
6654        } => {
6655            f(then_block);
6656            if let Some(eb) = else_block {
6657                f(eb);
6658            }
6659        }
6660        Stmt::While { body, .. }
6661        | Stmt::Repeat { body, .. }
6662        | Stmt::Zone { body, .. }
6663        | Stmt::Reversibly { body } => f(body),
6664        Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => f(tasks),
6665        Stmt::Inspect { arms, .. } => {
6666            for arm in arms {
6667                f(arm.body);
6668            }
6669        }
6670        _ => {}
6671    }
6672}
6673
6674/// Rewrite the placeholder target of the jump at `idx`. Total: a non-jump op or
6675/// an out-of-bounds index is a compiler-internal bug surfaced as `Err`.
6676pub(super) fn patch_jump(code: &mut [Op], idx: usize, target: usize) -> Result<(), String> {
6677    match code.get_mut(idx) {
6678        Some(Op::Jump { target: t })
6679        | Some(Op::JumpIfFalse { target: t, .. })
6680        | Some(Op::JumpIfTrue { target: t, .. })
6681        | Some(Op::IterNext { exit: t, .. }) => {
6682            *t = target;
6683            Ok(())
6684        }
6685        Some(other) => Err(format!("vm: patch_jump on non-jump op {:?}", other)),
6686        None => Err(format!("vm: patch_jump index {} out of bounds", idx)),
6687    }
6688}
6689
6690fn literal_const(lit: &Literal) -> Result<Constant, String> {
6691    match lit {
6692        Literal::Number(n) => Ok(Constant::Int(*n)),
6693        Literal::Float(f) => Ok(Constant::Float(*f)),
6694        Literal::Boolean(b) => Ok(Constant::Bool(*b)),
6695        Literal::Nothing => Ok(Constant::Nothing),
6696        Literal::Char(c) => Ok(Constant::Char(*c)),
6697        Literal::Duration(nanos) => Ok(Constant::Duration(*nanos)),
6698        Literal::Date(days) => Ok(Constant::Date(*days)),
6699        Literal::Moment(nanos) => Ok(Constant::Moment(*nanos)),
6700        Literal::Span { months, days } => Ok(Constant::Span {
6701            months: *months,
6702            days: *days,
6703        }),
6704        Literal::Time(nanos) => Ok(Constant::Time(*nanos)),
6705        Literal::Text(_) => unreachable!("Text literals are interned and handled by the caller"),
6706    }
6707}
6708
6709/// Match `value` as the left-spine `target + e1 + … + ek` (k ≥ 1), the
6710/// accumulate shape `Set x to x + …` lowers to an [`Op::AddAssign`] chain —
6711/// the exact left-fold the expression denotes: same kernel calls, same
6712/// evaluation order, same error points, but folding into the target register
6713/// at each step so a sole-owner Text can extend in place.
6714///
6715/// Soundness: the first term evaluates before any fold touches the register,
6716/// so it may mention the target freely. Every LATER term runs after a fold —
6717/// it must provably never observe the target ([`expr_avoids`]), or the chain
6718/// would read a partially-folded value the original expression never exposes.
6719fn add_assign_chain<'a>(target: Symbol, value: &'a Expr<'a>) -> Option<Vec<&'a Expr<'a>>> {
6720    let mut terms: Vec<&Expr> = Vec::new();
6721    let mut cur = value;
6722    loop {
6723        match cur {
6724            Expr::BinaryOp {
6725                op: BinaryOpKind::Add,
6726                left,
6727                right,
6728            } => {
6729                terms.push(right);
6730                cur = left;
6731            }
6732            Expr::Identifier(sym) if *sym == target => break,
6733            _ => return None,
6734        }
6735    }
6736    if terms.is_empty() {
6737        return None;
6738    }
6739    terms.reverse();
6740    if terms[1..].iter().all(|t| expr_avoids(t, target)) {
6741        Some(terms)
6742    } else {
6743        None
6744    }
6745}
6746
6747/// True when `e` provably never observes `sym`: every node comes from a
6748/// closed set of value-only forms with no `Identifier(sym)` anywhere.
6749/// Closures are conservatively "may observe" — they snapshot captures at
6750/// evaluation, and under the AddAssign rewrite that snapshot would see the
6751/// partially-folded register. Named calls cannot read the caller's locals
6752/// (and the rewrite only fires for locals), so only their argument
6753/// expressions need scanning. Anything unrecognized fails closed.
6754fn expr_avoids(e: &Expr, sym: Symbol) -> bool {
6755    use crate::ast::stmt::StringPart;
6756    let mut stack: Vec<&Expr> = vec![e];
6757    while let Some(e) = stack.pop() {
6758        match e {
6759            Expr::Identifier(s) => {
6760                if *s == sym {
6761                    return false;
6762                }
6763            }
6764            Expr::Literal(_) | Expr::OptionNone => {}
6765            Expr::BinaryOp { left, right, .. }
6766            | Expr::Union { left, right }
6767            | Expr::Intersection { left, right }
6768            | Expr::Range {
6769                start: left,
6770                end: right,
6771            } => {
6772                stack.push(left);
6773                stack.push(right);
6774            }
6775            Expr::Not { operand } => stack.push(operand),
6776            Expr::Call { args, .. } => stack.extend(args.iter().copied()),
6777            Expr::CallExpr { callee, args } => {
6778                stack.push(callee);
6779                stack.extend(args.iter().copied());
6780            }
6781            Expr::Index { collection, index } => {
6782                stack.push(collection);
6783                stack.push(index);
6784            }
6785            Expr::Slice {
6786                collection,
6787                start,
6788                end,
6789            } => {
6790                stack.push(collection);
6791                stack.push(start);
6792                stack.push(end);
6793            }
6794            Expr::Copy { expr } => stack.push(expr),
6795            Expr::Length { collection } => stack.push(collection),
6796            Expr::Contains { collection, value } => {
6797                stack.push(collection);
6798                stack.push(value);
6799            }
6800            Expr::List(items) | Expr::Tuple(items) => stack.extend(items.iter().copied()),
6801            Expr::FieldAccess { object, .. } => stack.push(object),
6802            Expr::New { init_fields, .. } => {
6803                stack.extend(init_fields.iter().map(|(_, fe)| *fe));
6804            }
6805            Expr::NewVariant { fields, .. } => {
6806                stack.extend(fields.iter().map(|(_, fe)| *fe));
6807            }
6808            Expr::OptionSome { value } => stack.push(value),
6809            Expr::WithCapacity { value, capacity } => {
6810                stack.push(value);
6811                stack.push(capacity);
6812            }
6813            Expr::InterpolatedString(parts) => {
6814                for p in parts {
6815                    if let StringPart::Expr { value, .. } = p {
6816                        stack.push(value);
6817                    }
6818                }
6819            }
6820            _ => return false,
6821        }
6822    }
6823    true
6824}
6825
6826fn binop_op(op: BinaryOpKind, dst: Reg, lhs: Reg, rhs: Reg) -> Result<Op, String> {
6827    use BinaryOpKind::*;
6828    Ok(match op {
6829        Add => Op::Add { dst, lhs, rhs },
6830        Subtract => Op::Sub { dst, lhs, rhs },
6831        Multiply => Op::Mul { dst, lhs, rhs },
6832        Divide => Op::Div { dst, lhs, rhs },
6833        ExactDivide => Op::ExactDiv { dst, lhs, rhs },
6834        FloorDivide => Op::FloorDiv { dst, lhs, rhs },
6835        Modulo => Op::Mod { dst, lhs, rhs },
6836        Lt => Op::Lt { dst, lhs, rhs },
6837        Gt => Op::Gt { dst, lhs, rhs },
6838        LtEq => Op::LtEq { dst, lhs, rhs },
6839        GtEq => Op::GtEq { dst, lhs, rhs },
6840        Eq => Op::Eq { dst, lhs, rhs },
6841        ApproxEq => Op::ApproxEq { dst, lhs, rhs },
6842        NotEq => Op::NotEq { dst, lhs, rhs },
6843        Concat => Op::Concat { dst, lhs, rhs },
6844        SeqConcat => Op::SeqConcat { dst, lhs, rhs },
6845        Pow => Op::Pow { dst, lhs, rhs },
6846        BitXor => Op::BitXor { dst, lhs, rhs },
6847        BitAnd => Op::BitAnd { dst, lhs, rhs },
6848        BitOr => Op::BitOr { dst, lhs, rhs },
6849        Shl => Op::Shl { dst, lhs, rhs },
6850        Shr => Op::Shr { dst, lhs, rhs },
6851        // And/Or are compiled by `compile_short_circuit`, never through here.
6852        And | Or => return Err("vm: internal — And/Or must use compile_short_circuit".to_string()),
6853    })
6854}