Skip to main content

logicaffeine_compile/vm/wasm/
module.rs

1//! The direct AOT backend: a whole [`CompiledProgram`] → one self-contained `.wasm` module,
2//! with no rustc/cargo/wasm-bindgen.
3//!
4//! The module exports `main` (the synthesized top-level body) and one wasm function per user
5//! function, and imports only the host's `env.print_*` output sinks. Function index space is
6//! `[imports 0..K][main = K][functions[i] = K+1+i]`, so `Op::Call { func }` lowers to a plain
7//! `call (K+1+func)`. The per-function body reuses the shared dispatch-loop lowering
8//! ([`super::cfg`]); types come from [`super::kind`] (the bytecode's arithmetic/`Show` are
9//! runtime-polymorphic, so the AOT path infers them statically).
10//!
11//! Everything outside the supported scalar fragment is rejected with [`WasmLowerError`] — the
12//! backend is total on what it accepts and never miscompiles; the corpus lock turns each
13//! refusal into a tracked, shrinking gap rather than a silent skip.
14
15use super::cfg::{assemble_dispatch_loop, goto_block, set_next_block, Blocks};
16use super::encode::*;
17use super::kind::{self, FieldLayout, FieldNested, Kind, KindTable, ParamShape};
18use super::regsplit;
19use super::WasmLowerError;
20use crate::semantics::builtins::BuiltinId;
21use crate::vm::instruction::{
22    BoundaryType, CompiledFunction, CompiledProgram, Constant, EnumTypeDef, Op, StructTypeDef,
23};
24use crate::vm::reach::{CodeLayout, HostEntries};
25use crate::Interner;
26use logicaffeine_language::analysis::{PolicyCondition, PolicyRegistry};
27
28mod absence;
29mod display;
30mod exact;
31mod roots;
32mod tower;
33
34type R<T> = std::result::Result<T, WasmLowerError>;
35
36/// Initial linear-memory size, in 64 KiB pages, for a heap-using module (4 MiB). The bump allocator
37/// never frees, so this is the working-set ceiling; 4 MiB comfortably holds the build-then-scan
38/// programs (n-element arrays, `+`-built strings, per-index Text cuts) at realistic sizes.
39const HEAP_PAGES: u32 = 64;
40
41/// ★ THE HEAP GIVES BLOCKS BACK NOW. The self-contained allocator was a pure bump — "8-aligned, no
42/// free" — so nothing leaked (every page's per-turn cost is FLAT) and yet a page's lifetime was
43/// simply `heap ÷ bytes-per-turn`: measured at ~4,850 turns for a page whose list is rewritten and
44/// ~37,000 for a counter, after which it dies with "out of bounds memory access". Every shipping
45/// path — the release bundler and the dev server both — is this allocator, so that was what real
46/// pages ran on.
47///
48/// A free block holds the next free pointer in its OWN first word, so the list costs no side table:
49/// only one head pointer per size class, in a table at a fixed low address. Linear memory is zeroed
50/// at instantiation, so every head starts empty with no init code at all.
51const FREE_TABLE_BASE: i32 = 16;
52
53/// ★ CLASSES ARE EXACT, NOT POWERS OF TWO, AND THAT IS THE WHOLE TRICK. The textbook scheme rounds
54/// a request up to the next power of two, which would have made every page BIGGER before a single
55/// free ever fired — a 3-element Int buffer is 24 bytes and would have become 32. Allocations here
56/// are already 8-aligned, so an exact 8-byte-granular class is exactly the size the bump consumed
57/// anyway: reuse becomes possible at a cost of precisely zero bytes.
58///
59/// 128 classes covers every block up to 1 KiB, which is everything a MODEST turn allocates — the
60/// whole per-turn budget of the worst-shaped page measured is 864 bytes. A `Set`/`Map` that grows
61/// past that (a big cache, an instance store keyed by many components) needs a class too, though:
62/// its buffer doubles from 4 elements up, so its byte size past 1 KiB is already an exact power of
63/// two (2048, 4096, …) and rounding a one-off large allocation UP to the next one costs nothing this
64/// scheme does not already accept for the exact tier below it.
65const FREE_CLASSES: i32 = 128;
66
67/// Power-of-two classes for blocks over 1 KiB: class `i` holds blocks of exactly `2^(POWER_MIN + i)`
68/// bytes. `POWER_MIN` is the first power at or above the exact tier's ceiling (`FREE_CLASSES * 8`
69/// bytes = 1024 = 2^10, so the first power class starts at 2^11 — a block of exactly 1024 bytes is
70/// still served by the exact tier). 20 classes reaches 2^30 bytes (1 GiB), far past anything a page
71/// allocates in one block; a request bigger than that bumps and is not reclaimed, same as before.
72const POWER_CLASSES: i32 = 20;
73const POWER_MIN: i32 = 11;
74
75/// Every text literal the module mentions, laid out ONCE in a data section.
76///
77/// ★ A STATIC STRING USED TO ALLOCATE ON EVERY EVALUATION. `lower_text_literal` built "a fresh Text
78/// object in linear memory" each time it ran — two allocations (a 16-byte header and an 8-aligned
79/// buffer) plus an `i64.const`/`i64.store` pair per 8 bytes — so `<li>x</li>` minted a new Text for
80/// `"x"` on every paint, and the bytes of every literal were re-emitted as CODE. Measured at 24
81/// bytes of heap per static text child per row per turn.
82///
83/// A literal cannot change, so it is written into the module's data section at build time and its
84/// handle is a CONSTANT. That is two wins at once: the allocation disappears, and the store pairs
85/// collapse to one `i32.const` while the bytes move to a section that holds them once.
86///
87/// Sound because this tier already treats Text as immutable — `cow_clonable` excludes it, so
88/// nothing clones a Text and nothing retains one, which means no code path writes into one.
89///
90/// Self-contained modules only. In LINKER MODE the memory is imported and the heap is seeded from a
91/// runtime slab, so a fixed address here would name someone else's bytes.
92#[derive(Default)]
93struct TextPool {
94    by_bytes: std::collections::HashMap<Vec<u8>, i32>,
95    /// The static region's image, laid out from [`STATIC_BASE`].
96    image: Vec<u8>,
97}
98
99impl TextPool {
100    /// The address of this literal's header, laying it out on first sight.
101    fn intern(&mut self, bytes: &[u8]) -> i32 {
102        if let Some(a) = self.by_bytes.get(bytes) {
103            return *a;
104        }
105        let addr = STATIC_BASE + self.image.len() as i32;
106        let len = bytes.len() as i32;
107        // `[len][cap][data_ptr][refcount]`, matching what the runtime builder wrote — cap is the
108        // length (not the padded size), exactly as before, and the refcount starts at zero.
109        self.image.extend_from_slice(&len.to_le_bytes());
110        self.image.extend_from_slice(&len.to_le_bytes());
111        self.image.extend_from_slice(&(addr + 16).to_le_bytes());
112        self.image.extend_from_slice(&0i32.to_le_bytes());
113        self.image.extend_from_slice(bytes);
114        // Pad so the NEXT header stays 8-aligned, as every heap block is.
115        while self.image.len() % 8 != 0 {
116            self.image.push(0);
117        }
118        self.by_bytes.insert(bytes.to_vec(), addr);
119        addr
120    }
121}
122
123/// Where the static text region starts: after the free-list class table (the exact tier, then the
124/// power-of-two tier).
125const STATIC_BASE: i32 = FREE_TABLE_BASE + (FREE_CLASSES + POWER_CLASSES) * 4;
126
127/// Where the bump region starts: after the class table. (It was 16 — "the low 16 bytes stay
128/// reserved/null" — and the table now sits in the space above that.)
129const HEAP_START: i32 = STATIC_BASE;
130
131/// Reserved linear-memory slot (an `i32`) holding the offline net-inbox FIFO handle — lives in the
132/// null-reserved low-16 region (bytes 0..16 are never bump-allocated), so it never collides with the
133/// heap. `Listen` writes the handle here; `Send`/`Stream`/`Await` read it (see the net-op lowerings).
134const NET_INBOX_ADDR: i32 = 8;
135
136/// ★ ONE ROW PER HOST IMPORT — the enum, the canonical order, the field name, and the
137/// signature, from one place.
138///
139/// THERE WERE FOUR OF THESE, side by side, 199 entries each: the `HostFn` enum, the
140/// `HOST_FNS` order that fixes import indices, `field()` naming each one for the host, and
141/// `params()`/`results()` giving its signature. Adding one DOM operation meant editing all
142/// four, and forgetting one of them did not fail to compile — the module simply failed to
143/// INSTANTIATE at runtime, in the browser, with no diagnostic pointing anywhere near here.
144///
145/// The declaration order and `HOST_FNS` order had already drifted apart (they agreed for 16
146/// entries and then did not), which cost nothing only because `HostFn` derives neither `Ord`
147/// nor `Hash` and the emitter re-sorts into `HOST_FNS` order before emitting. That is a
148/// property nobody was holding on purpose.
149///
150/// Now a row is the unit: name it once, and it is in the enum, in the order, named, and
151/// typed. A row that is missing is a row that does not exist.
152macro_rules! host_fns {
153    ($( $(#[$attr:meta])* $variant:ident = $field:literal, ($($p:ident),*) -> ($($r:ident),*); )*) => {
154        /// A host function the emitted module imports (under the `env` namespace).
155        #[derive(Clone, Copy, PartialEq, Eq)]
156        enum HostFn { $( $(#[$attr])* $variant, )* }
157
158        /// The canonical order of every host import, which fixes their indices in an emitted
159        /// module. Derived from the table, so it can no longer disagree with the enum, and no
160        /// length is written down: this was `[HostFn; 188]` and the literal drifted from the
161        /// list it sat above, breaking a teammate's whole test pass with "expected an array
162        /// with a size of 188, found one with a size of 189" — true, and teaching nothing.
163        const HOST_FNS: &[HostFn] = &[ $( HostFn::$variant, )* ];
164
165        impl HostFn {
166            fn field(self) -> &'static str {
167                match self { $( HostFn::$variant => $field, )* }
168            }
169            fn params(self) -> Vec<u8> {
170                match self { $( HostFn::$variant => vec![$($p),*], )* }
171            }
172            fn results(self) -> Vec<u8> {
173                match self { $( HostFn::$variant => vec![$($r),*], )* }
174            }
175            /// The positions of the parameters the host KEEPS after the call returns — a
176            /// `CALLBACK` it will re-enter through, or a `KEPT` handle it stores. Read off the row's
177            /// own parameter spelling, so a new import that keeps a handle says so where it is
178            /// declared.
179            fn retained_params(self) -> Vec<usize> {
180                let spelled: &[&str] = match self { $( HostFn::$variant => &[$(stringify!($p)),*], )* };
181                spelled
182                    .iter()
183                    .enumerate()
184                    .filter(|(_, p)| **p == "CALLBACK" || **p == "KEPT")
185                    .map(|(i, _)| i)
186                    .collect()
187            }
188            /// Whether the host re-enters the module through a closure handed to this import.
189            fn registers_callback(self) -> bool {
190                let spelled: &[&str] = match self { $( HostFn::$variant => &[$(stringify!($p)),*], )* };
191                spelled.contains(&"CALLBACK")
192            }
193            /// Whether this import answers with a Text the host allocates in the module's heap
194            /// through `__logos_text_new` — read off the row's own result spelling.
195            fn returns_host_text(self) -> bool {
196                let spelled: &[&str] = match self { $( HostFn::$variant => &[$(stringify!($r)),*], )* };
197                spelled.contains(&"HOST_TEXT")
198            }
199            /// Whether this import answers with a sequence the host builds in the module's heap
200            /// through `__logos_seq_new` — read off the row's own result spelling.
201            fn returns_host_seq(self) -> bool {
202                let spelled: &[&str] = match self { $( HostFn::$variant => &[$(stringify!($r)),*], )* };
203                spelled.contains(&"HOST_SEQ")
204            }
205        }
206    };
207}
208
209/// A closure handle the host keeps and later calls back through `__logos_call_closure`. An `i32`
210/// on the wire; spelled apart in the table so the host's holds are part of the ABI.
211const CALLBACK: u8 = I32;
212
213/// A Text the HOST writes into the module's heap through `__logos_text_new` and hands over — an
214/// element's text, a response body, the route. An `i32` handle on the wire; spelled apart in the
215/// table so a module that takes one carries the allocator the host writes it through.
216const HOST_TEXT: u8 = I32;
217
218/// A sequence the HOST builds in the module's heap through `__logos_seq_new` and hands over — a
219/// dropped file's bytes. An `i32` handle on the wire, one ordinary `Seq` header over 8-byte slots;
220/// spelled apart in the table so a module that takes one carries the allocator the host fills it
221/// through. The element kind is the importing builtin's declared result kind, never the host's.
222const HOST_SEQ: u8 = I32;
223
224host_fns! {
225    PrintI64 = "print_i64", (I64) -> ();
226    PrintBool = "print_bool", (I32) -> ();
227    /// `print_char(code: i64)` — display one Unicode scalar. The host reconstructs `char` from the
228    /// code point and emits its UTF-8 bytes (a `RuntimeValue::Char` displays as the character
229    /// itself), so `Show \`a\`` prints `a`, not the numeric code point.
230    PrintChar = "print_char", (I64) -> ();
231    PrintF64 = "print_f64", (F64) -> ();
232    /// `print_date(days: i32)` / `print_moment(nanos: i64)` — display a temporal value (the host
233    /// formats via `RuntimeValue::Date`/`Moment`'s `to_display_string`, so no reimplementation).
234    PrintDate = "print_date", (I32) -> ();
235    PrintMoment = "print_moment", (I64) -> ();
236    /// `print_duration(nanos: i64)` / `print_time(nanos: i64)` — display a `RuntimeValue::Duration`
237    /// (magnitude-bucketed `5s`/`3h`/…) / `Time` (`HH:MM:SS[.frac]`), host-formatted like the VM.
238    PrintDuration = "print_duration", (I64) -> ();
239    PrintTime = "print_time", (I64) -> ();
240    /// `pow_ff(base: f64, exp: f64) -> f64` — `f64::powf`, for a Float exponent.
241    PowFf = "pow_ff", (F64,F64) -> (F64);
242    /// `pow_fi(base: f64, exp: i64) -> f64` — `f64::powi`, for an Int exponent (exact repeated
243    /// multiplication, NOT `powf` — the two differ in the last bit).
244    PowFi = "pow_fi", (F64,I64) -> (F64);
245    /// `today() -> i32` (days since epoch) / `now() -> i64` (nanos since epoch) — the clock,
246    /// honoring the test fixed-clock so tw==vm==wasm.
247    Today = "today", () -> (I32);
248    Now = "now", () -> (I64);
249    /// `random_int(lo: i64, hi: i64) -> i64` — `randomInt(lo, hi)`: a uniform draw from `lo..=hi`.
250    /// Randomness is the host's to supply (a browser's `crypto.getRandomValues`, a test host's seeded
251    /// generator); the bounds are the program's.
252    RandomInt = "random_int", (I64,I64) -> (I64);
253    /// `print_seq_i64(handle: i32)` / `print_seq_f64(handle: i32)` — display a whole sequence. The
254    /// host reads the stable header `[len][cap][data_ptr]` + the element buffer out of the
255    /// exported linear memory and formats `[e0, e1, …]` exactly as `RuntimeValue::List`'s
256    /// `to_display_string` (each element by its scalar display), so no format reimplementation.
257    PrintSeqI64 = "print_seq_i64", (I32) -> ();
258    /// `print_seq_bool(handle: i32)` — like [`PrintSeqI64`] but each i64-0/1 element renders as
259    /// `true`/`false` (a `Seq of Bool` = `RuntimeValue::List` of `ListRepr::Bools`), so the whole
260    /// sequence displays `[true, false, …]` rather than `[1, 0, …]`.
261    PrintSeqBool = "print_seq_bool", (I32) -> ();
262    /// `print_seq_word32(handle: i32)` / `print_seq_word64(handle: i32)` — display a whole `Seq of
263    /// Word32`/`Word64` (a crypto state array) as `[u0, u1, …]` with each element its UNSIGNED decimal
264    /// (`4294967295`, not `-1`). Word32 elements ride the low word of their 8-byte slot; Word64 the full
265    /// slot — matching `RuntimeValue::List` of `Word`.
266    PrintSeqWord32 = "print_seq_word32", (I32) -> ();
267    PrintSeqWord64 = "print_seq_word64", (I32) -> ();
268    PrintSeqF64 = "print_seq_f64", (I32) -> ();
269    /// `print_text(handle: i32)` — display a UTF-8 string. The host reads the header `[len][cap]
270    /// [data_ptr]` + the `len` bytes at `data_ptr` and emits them verbatim (a `RuntimeValue::Text`
271    /// displays as its raw contents), so no formatting reimplementation.
272    PrintText = "print_text", (I32) -> ();
273    /// `print_seq_text(handle: i32)` — display a whole sequence of Text. The host reads the seq
274    /// header + each element (a Text handle) and formats `[s0, s1, …]` (the elements unquoted,
275    /// comma-space separated), matching `RuntimeValue::List`'s `to_display_string` for Text elements.
276    PrintSeqText = "print_seq_text", (I32) -> ();
277    /// `print_set_i64(handle: i32)` — display a whole `Set of Int` as `{e0, e1, …}`. The VM's `Set`
278    /// is an insertion-ordered `Vec` (NOT a hashset), and the AOT set stores elements in that same
279    /// order, so the display is deterministic and byte-identical. (A whole `Map` displays the same way
280    /// via `lower_show_map`: the VM's `MapStorage` is an insertion-ordered `IndexMap`, matching the
281    /// AOT's append order, so `{k: v, …}` is byte-identical too.)
282    PrintSetI64 = "print_set_i64", (I32) -> ();
283    /// `fmt_i64_into(buf: i32, val: i64) -> i32` — write the decimal of `val`
284    /// (`RuntimeValue::Int(val).to_display_string()`) into `buf` and return the byte length. Used
285    /// to stringify an Int operand of a `Concat` (string interpolation `"… {n} …"`). `buf` is a
286    /// module-allocated 24-byte scratch (an i64 decimal is ≤ 20 chars + sign).
287    FmtI64Into = "fmt_i64_into", (I32,I64) -> (I32);
288    /// `fmt_f64_into(buf: i32, val: f64) -> i32` — like [`FmtI64Into`] for a Float operand (the
289    /// shared shortest-round-trip display, `logicaffeine_data::fmt::fmt_f64`); `buf` is a 340-byte
290    /// scratch (the widest possible output, the smallest subnormal, is ~326 bytes — spec-locked
291    /// by `fmt::tests::worst_case_width_fits_wasm_scratch`).
292    FmtF64Into = "fmt_f64_into", (I32,F64) -> (I32);
293    /// `fmt_bool_into(buf: i32, val: i32) -> i32` — writes `"true"`/`"false"`; `buf` is 8 bytes.
294    FmtBoolInto = "fmt_bool_into", (I32,I64) -> (I32);
295    /// `fmt_f64_prec_into(buf: i32, val: f64, prec: i32) -> i32` — write `format!("{:.prec}", val)`
296    /// (the interpolation `.N` precision spec `"{x:.9}"` → `apply_format_spec`) and return the length.
297    /// `buf` is a `340 + prec`-byte scratch (worst-case `f64` integer width + the decimals).
298    FmtF64PrecInto = "fmt_f64_prec_into", (I32,F64,I32) -> (I32);
299    /// `fmt_align_into(buf: i32, text: i32, width: i32, align: i32) -> i32` — pad the `Text` `text`'s
300    /// display to `width` (space fill, char-counted) into `buf`, returning the byte length. `align`
301    /// selects `format!("{:>w$}", …)` (0, right — also the bare-width `{x:6}`), `{:<w$}` (1, left), or
302    /// `{:^w$}` (2, center) — the SAME Rust `format!` `apply_format_spec` runs, so bit-identical. `buf`
303    /// is sized `text_len + width` (padding adds at most `width` single-byte spaces).
304    FmtAlignInto = "fmt_align_into", (I32,I32,I32,I32) -> (I32);
305    /// `args() -> i32` — the command-line arguments as a `Seq of Text` handle (the host builds the
306    /// argv sequence in the module's linear memory and returns its handle), so a program reading its
307    /// problem size from argv (`parseInt(item 2 of args())`) compiles to standalone wasm.
308    Args = "args", () -> (I32);
309    /// `read_reals(path: i32) -> i32` — `readReals(path)`: the file's little-endian binary64 values as a
310    /// `Seq of Real` handle the host builds in a page it grows, refused as `logicaffeine_system::file::read_reals`
311    /// refuses (a file it cannot read, one that is not a whole number of values).
312    ReadReals = "read_reals", (I32) -> (I32);
313    /// `parse_int(handle: i32) -> i64` — parse a `Text` (UTF-8 in linear memory) to an Int, exactly as
314    /// the VM's `BuiltinId::ParseInt` (`str::parse::<i64>`), trapping on a non-numeric string.
315    ParseInt = "parse_int", (I32) -> (I64);
316    /// `text_contains(haystack: i32, needle: i32) -> i32` — 1 iff the `needle` Text is a substring of
317    /// the `haystack` Text, exactly as the VM's `BuiltinId::Contains` (`str::contains`).
318    TextContains = "text_contains", (I32,I32) -> (I64);
319    /// `fmt_seq_i64_into(buf: i32, handle: i32) -> i32` — write a whole `Seq of Int`'s display
320    /// `[e0, e1, …]` (`RuntimeValue::List::to_display_string`) into `buf` and return the byte length.
321    /// Used to stringify a SEQUENCE operand of a `+`/`format` (`"Positives: " + positives`). `buf` is
322    /// sized `len*24 + 8` (each i64 ≤ 20 digits + sign + `", "`, plus the brackets).
323    FmtSeqI64Into = "fmt_seq_i64_into", (I32,I32) -> (I32);
324    /// `fmt_seq_bool_into(buf: i32, handle: i32) -> i32` — like [`FmtSeqI64Into`] for a `Seq of Bool`,
325    /// rendering each i64-0/1 element as `true`/`false` (`buf` sized `len*7 + 8` — `"false"` + `", "`).
326    /// Used to stringify a whole bool sequence operand of a `+`/`format`.
327    FmtSeqBoolInto = "fmt_seq_bool_into", (I32,I32) -> (I32);
328    /// `fmt_set_i64_into(buf: i32, handle: i32) -> i32` — like [`FmtSeqI64Into`] for a `Set of Int`,
329    /// whose display is `{e0, e1, …}` (insertion order, matching the VM's `Vec`-backed Set).
330    FmtSetI64Into = "fmt_set_i64_into", (I32,I32) -> (I32);
331    /// `print_set_text(handle: i32)` — display a whole `Set of Text` as `{s0, s1, …}` (elements
332    /// unquoted, insertion order). Like [`PrintSetI64`] but each slot's low word is a `Text` handle
333    /// the host reads out of memory — matching `RuntimeValue::Set::to_display_string` for Text.
334    PrintSetText = "print_set_text", (I32) -> ();
335    /// `print_rational(num: i64, den: i64)` — display an exact `Rational` as `num/den`, or just `num`
336    /// when `den == 1` (matching the VM, whose `from_rational` downsizes a whole quotient to an `Int`).
337    PrintRational = "print_rational", (I64,I64) -> ();
338    /// `print_nothing()` — display the Optional null value as "nothing" (matching the tree-walker's
339    /// `RuntimeValue::Nothing` display). The `Some` arm of an `Optional` `Show` uses the inner scalar's
340    /// own sink instead; this covers the null-handle arm.
341    PrintNothing = "print_nothing", () -> ();
342    /// `parse_float(handle: i32) -> f64` — parse a `Text` to a Float, exactly as the VM's
343    /// `BuiltinId::ParseFloat` (`str::trim().parse::<f64>`), trapping on a non-numeric string.
344    ParseFloat = "parse_float", (I32) -> (F64);
345    /// `parse_timestamp(handle: i32) -> i64` — parse an RFC-3339 `Text` to a `Moment` (nanoseconds
346    /// since the epoch) via `temporal::parse_rfc3339`, trapping on a malformed timestamp.
347    ParseTimestamp = "parse_timestamp", (I32) -> (I64);
348    /// `temporal_component(nanos: i64, which: i32) -> i64` — one calendar/clock component of a `Moment`
349    /// (`which`: 0 year, 1 month, 2 day, 3 hour, 4 minute, 5 second, 6 weekday, 7 iso-week, 8 quarter),
350    /// computed by the SAME `temporal::civil_from_unix_nanos`/`weekday_from_days`/`iso_week_from_days`
351    /// the VM uses — so `the year of m` is bit-identical across tiers.
352    TemporalComponent = "temporal_component", (I64,I32) -> (I64);
353    /// `temporal_component_date(days: i32, which: i32) -> i64` — the calendar component of a `Date`
354    /// (days since the epoch), `which` in {0 year, 1 month, 2 day, 6 weekday, 7 iso-week, 8 quarter}.
355    /// Computed straight from `temporal::civil_from_days`/`weekday_from_days`/`iso_week_from_days` (the
356    /// VM's exact Date path) over the full `i32` day range — no `Moment` nanos round-trip (which would
357    /// overflow `i64` past ~year 2262). Clock components (hour/minute/second) don't apply to a `Date`
358    /// and are refused at lowering, matching the VM's runtime error.
359    TemporalComponentDate = "temporal_component_date", (I32,I32) -> (I64);
360    /// `print_word(v: i64)` — display a Word as its UNSIGNED decimal (`(v as u64).to_string()`, matching
361    /// `WordVal`'s Display). A `Word32` is zero-extended to `i64` (`i64.extend_i32_u`) before the call,
362    /// so its top 32 bits are zero and the `u64` reading is exactly the `u32` value.
363    PrintWord = "print_word", (I64) -> ();
364    /// `logos_rt_bigint_from_i64(x: i64) -> i32` — the linked `logicaffeine_base::BigInt` runtime: box a
365    /// scalar into a BigInt handle. LINKER MODE ONLY: an undefined symbol `rust-lld` resolves against the
366    /// prebuilt base runtime object (there is no `env` host behind it), so it never appears in a
367    /// standalone module. The three `Bigint*` sinks together lower an overflowing integer `Op::Pow`.
368    BigintFromI64 = "logos_rt_bigint_from_i64", (I64) -> (I32);
369    /// `logos_rt_bigint_pow(base: i32, exp: i64) -> i32` — raise a BigInt handle to an integer power,
370    /// returning a fresh handle (the exact big integer, no overflow). Linker mode only.
371    BigintPow = "logos_rt_bigint_pow", (I32,I64) -> (I32);
372    /// `logos_rt_bigint_to_text(h: i32) -> i32` — render a BigInt handle to a `Text` handle laid out in
373    /// the emitter's `[len][cap][data_ptr][refcount]` ABI in the shared linear memory, so a `Show` reads
374    /// it through the ordinary `print_text` path. Linker mode only.
375    BigintToText = "logos_rt_bigint_to_text", (I32) -> (I32);
376    /// `logos_rt_bigint_mul(a: i32, b: i32) -> i32` — exact big-integer multiply of two BigInt handles,
377    /// returning a fresh handle. Lets `(2^100) * (3^50)` keep computing on real BigInts. Linker only.
378    BigintMul = "logos_rt_bigint_mul", (I32,I32) -> (I32);
379    /// `logos_rt_bigint_add(a: i32, b: i32) -> i32` — exact big-integer addition of two handles. Linker only.
380    BigintAdd = "logos_rt_bigint_add", (I32,I32) -> (I32);
381    /// `logos_rt_bigint_sub(a: i32, b: i32) -> i32` — exact big-integer subtraction (may be negative;
382    /// `to_text` renders the sign). Linker only.
383    BigintSub = "logos_rt_bigint_sub", (I32,I32) -> (I32);
384    /// `logos_rt_bigint_div(a: i32, b: i32) -> i32` — exact big-integer quotient (`div_rem().0`, the SAME
385    /// truncating division the VM uses), traps on a zero divisor. Linker only.
386    BigintDiv = "logos_rt_bigint_div", (I32,I32) -> (I32);
387    /// `logos_rt_bigint_mod(a: i32, b: i32) -> i32` — exact big-integer remainder (`div_rem().1`, matching
388    /// the VM's `the remainder of a and b`), traps on a zero divisor. Linker only.
389    BigintMod = "logos_rt_bigint_mod", (I32,I32) -> (I32);
390    /// `logos_rt_complex_from_i64(re: i64, im: i64) -> i32` — build an EXACT `Complex` (Rational
391    /// components) from two integer parts, returning an i32 handle. `logos_rt_complex_{add,sub,mul}(a,
392    /// b) -> i32` do exact complex arithmetic; `logos_rt_complex_to_text(h) -> i32` renders it (`re±imi`)
393    /// to a Text handle. Linker mode only (the exact Rational-backed runtime, mirroring the BigInt ABI).
394    ComplexFromI64 = "logos_rt_complex_from_i64", (I64,I64) -> (I32);
395    ComplexAdd = "logos_rt_complex_add", (I32,I32) -> (I32);
396    ComplexSub = "logos_rt_complex_sub", (I32,I32) -> (I32);
397    ComplexMul = "logos_rt_complex_mul", (I32,I32) -> (I32);
398    ComplexToText = "logos_rt_complex_to_text", (I32) -> (I32);
399    /// `logos_rt_complex_abs(h: i32) -> f64` — the `f64` modulus `|z|`. The one complex op returning a
400    /// Float rather than an i32 handle.
401    ComplexAbs = "logos_rt_complex_abs", (I32) -> (F64);
402    /// The FLOAT-complex tier (`complex(realExpr, realExpr)` → a `ComplexF`): `logos_rt_complex_from_f64(
403    /// re: f64, im: f64) -> i32` builds the handle (parts as exact dyadic Rationals), and
404    /// `logos_rt_complex_re_f64`/`_im_f64(h: i32) -> f64` extract the parts for `re`/`im`.
405    ComplexFromF64 = "logos_rt_complex_from_f64", (F64,F64) -> (I32);
406    ComplexReF64 = "logos_rt_complex_re_f64", (I32) -> (F64);
407    ComplexImF64 = "logos_rt_complex_im_f64", (I32) -> (F64);
408    /// `logos_rt_modular_from_i64(v: i64, n: i64) -> i32` / `_add`/`_sub`/`_mul`/`_to_text` — the ℤ/nℤ
409    /// analog of the Complex ABI over `logicaffeine_base::Modular` (i32 handle). Linker mode only.
410    ModularFromI64 = "logos_rt_modular_from_i64", (I64,I64) -> (I32);
411    ModularAdd = "logos_rt_modular_add", (I32,I32) -> (I32);
412    ModularSub = "logos_rt_modular_sub", (I32,I32) -> (I32);
413    ModularMul = "logos_rt_modular_mul", (I32,I32) -> (I32);
414    ModularDiv = "logos_rt_modular_div", (I32,I32) -> (I32);
415    ModularPow = "logos_rt_modular_pow", (I32,I64) -> (I32);
416    ModularToText = "logos_rt_modular_to_text", (I32) -> (I32);
417    /// `logos_rt_decimal_from_text(h)` parses a Text handle → exact Decimal; `_from_i64(x)` promotes an
418    /// Int; `_add`/`_sub`/`_mul`/`_to_text` are the exact base-10 ABI over `base::Decimal`. Linker only.
419    DecimalFromText = "logos_rt_decimal_from_text", (I32) -> (I32);
420    DecimalFromI64 = "logos_rt_decimal_from_i64", (I64) -> (I32);
421    DecimalAdd = "logos_rt_decimal_add", (I32,I32) -> (I32);
422    DecimalSub = "logos_rt_decimal_sub", (I32,I32) -> (I32);
423    DecimalMul = "logos_rt_decimal_mul", (I32,I32) -> (I32);
424    DecimalToText = "logos_rt_decimal_to_text", (I32) -> (I32);
425    /// `logos_rt_money_from_decimal(dec, cur)` / `_from_i64(v, cur)` build a Money (currency Text read
426    /// from shared memory); `_add`/`_sub` require matching currency; `_to_text` renders it. Linker only.
427    MoneyFromDecimal = "logos_rt_money_from_decimal", (I32,I32) -> (I32);
428    MoneyFromI64 = "logos_rt_money_from_i64", (I64,I32) -> (I32);
429    MoneyAdd = "logos_rt_money_add", (I32,I32) -> (I32);
430    MoneySub = "logos_rt_money_sub", (I32,I32) -> (I32);
431    MoneyToText = "logos_rt_money_to_text", (I32) -> (I32);
432    QuantityOfI64 = "logos_rt_quantity_of_i64", (I64,I32) -> (I32);
433    QuantityConvert = "logos_rt_quantity_convert", (I32,I32) -> (I32);
434    QuantityAdd = "logos_rt_quantity_add", (I32,I32) -> (I32);
435    QuantitySub = "logos_rt_quantity_sub", (I32,I32) -> (I32);
436    QuantityMul = "logos_rt_quantity_mul", (I32,I32) -> (I32);
437    QuantityDiv = "logos_rt_quantity_div", (I32,I32) -> (I32);
438    QuantityToText = "logos_rt_quantity_to_text", (I32) -> (I32);
439    RationalFromI64 = "logos_rt_rational_from_i64", (I64) -> (I32);
440    RationalFromBigint = "logos_rt_rational_from_bigint", (I32) -> (I32);
441    RationalAdd = "logos_rt_rational_add", (I32,I32) -> (I32);
442    RationalSub = "logos_rt_rational_sub", (I32,I32) -> (I32);
443    RationalMul = "logos_rt_rational_mul", (I32,I32) -> (I32);
444    RationalDiv = "logos_rt_rational_div", (I32,I32) -> (I32);
445    RationalToText = "logos_rt_rational_to_text", (I32) -> (I32);
446    RationalFloor = "logos_rt_rational_floor", (I32) -> (I32);
447    RationalCeil = "logos_rt_rational_ceil", (I32) -> (I32);
448    RationalRound = "logos_rt_rational_round", (I32) -> (I32);
449    RationalAbs = "logos_rt_rational_abs", (I32) -> (I32);
450    UuidParse = "logos_rt_uuid_parse", (I32) -> (I32);
451    UuidNil = "logos_rt_uuid_nil", () -> (I32);
452    UuidMax = "logos_rt_uuid_max", () -> (I32);
453    UuidDns = "logos_rt_uuid_dns", () -> (I32);
454    UuidUrl = "logos_rt_uuid_url", () -> (I32);
455    UuidOid = "logos_rt_uuid_oid", () -> (I32);
456    UuidX500 = "logos_rt_uuid_x500", () -> (I32);
457    UuidVersion = "logos_rt_uuid_version", (I32) -> (I64);
458    UuidEq = "logos_rt_uuid_eq", (I32,I32) -> (I32);
459    UuidToText = "logos_rt_uuid_to_text", (I32) -> (I32);
460    UuidFromPtr = "logos_rt_uuid_from_ptr", (I32) -> (I32);
461    PrintSpan = "print_span", (I64) -> ();
462    MomentAddSpan = "logos_rt_moment_add_span", (I64,I32,I32) -> (I64);
463    DateAddSpan = "logos_rt_date_add_span", (I32,I32,I32) -> (I32);
464    FormatTimestampRt = "logos_rt_format_timestamp", (I64) -> (I32);
465    MonthsBetweenRt = "logos_rt_months_between", (I64,I64) -> (I64);
466    YearsBetweenRt = "logos_rt_years_between", (I64,I64) -> (I64);
467    MakeDateRt = "logos_rt_make_date", (I64,I64,I64) -> (I32);
468    MakeMomentRt = "logos_rt_make_moment", (I64,I64,I64,I64,I64,I64) -> (I64);
469    InZoneRt = "logos_rt_in_zone", (I64,I32) -> (I32);
470    LocalInstantRt = "logos_rt_local_instant", (I64,I32) -> (I64);
471    Lanes16FromBytes = "logos_rt_lanes16_from_bytes", (I32) -> (I32);
472    Lanes8FromWords = "logos_rt_lanes8_from_words", (I32) -> (I32);
473    Lanes4W64FromWords = "logos_rt_lanes4w64_from_words", (I32) -> (I32);
474    LanesSplat16 = "logos_rt_lanes_splat16", (I64) -> (I32);
475    LanesSplat8 = "logos_rt_lanes_splat8", (I64) -> (I32);
476    LanesToSeq = "logos_rt_lanes_to_seq", (I32) -> (I32);
477    LanesShuffle = "logos_rt_lanes_shuffle", (I32,I32) -> (I32);
478    LanesInterleaveLo = "logos_rt_lanes_interleave_lo", (I32,I32) -> (I32);
479    LanesInterleaveHi = "logos_rt_lanes_interleave_hi", (I32,I32) -> (I32);
480    LanesByteAdd = "logos_rt_lanes_byte_add", (I32,I32) -> (I32);
481    LanesMaddubs = "logos_rt_lanes_maddubs", (I32,I32) -> (I32);
482    LanesPackus = "logos_rt_lanes_packus", (I32,I32) -> (I32);
483    LanesShrBytes = "logos_rt_lanes_shr_bytes", (I32,I64) -> (I32);
484    DecimalToRational = "logos_rt_decimal_to_rational", (I32) -> (I32);
485    MoneySetRate = "logos_rt_set_rate", (I32,I32) -> (I32);
486    MoneyToCurrency = "logos_rt_to_currency", (I32,I32) -> (I32);
487    MoneySetRatesInt = "logos_rt_set_rates_int", (I32) -> (I32);
488    MoneySetRatesRational = "logos_rt_set_rates_rational", (I32) -> (I32);
489    MoneySetRatesDecimal = "logos_rt_set_rates_decimal", (I32) -> (I32);
490    WriteWireResidual = "write_wire_residual", (I32,I32) -> (I64);
491    /// `logos_rt_fail(text) -> ()` — the message of a runtime failure, handed to the host
492    /// immediately before the `unreachable` that ends the program. The trap is the contract
493    /// (`wasm_traps_where_treewalker_errors`); this only stops the host having to guess WHY.
494    LogosRtFail = "logos_rt_fail", (I32) -> ();
495    /// `logos_rt_fail_at(code: i32, value: i64) -> ()` — an INLINE check failing (a bounds
496    /// test, a division guard). Its message needs a value that only exists at run time, so
497    /// there is no constant to hand over: the module reports the code and the value, and the
498    /// host renders the sentence through `semantics::failcode::message`.
499    LogosRtFailAt = "logos_rt_fail_at", (I32,I64) -> ();
500    WireBytesInt = "logos_rt_wire_bytes_int", (I64) -> (I32);
501    WireBytesBool = "logos_rt_wire_bytes_bool", (I64) -> (I32);
502    WireBytesFloat = "logos_rt_wire_bytes_float", (F64) -> (I32);
503    WireBytesText = "logos_rt_wire_bytes_text", (I32) -> (I32);
504    ReadWireFrame = "read_wire_frame", (I32,I32) -> (I32);
505    ReadWireProgramRt = "logos_rt_read_wire_program", (I32,I32) -> (I32);
506    DynamicToText = "logos_rt_dynamic_to_text", (I32) -> (I32);
507    RunAccepted = "logos_rt_run_accepted", (I32,I64,I64,I64) -> (I64);
508    Sha1Rnds4 = "logos_rt_sha1rnds4", (I32,I32,I64) -> (I32);
509    Sha1Msg1 = "logos_rt_sha1msg1", (I32,I32) -> (I32);
510    Sha1Msg2 = "logos_rt_sha1msg2", (I32,I32) -> (I32);
511    Sha1Nexte = "logos_rt_sha1nexte", (I32,I32) -> (I32);
512    Lanes4Add = "logos_rt_lanes4_add", (I32,I32) -> (I32);
513    Lanes4Xor = "logos_rt_lanes4_xor", (I32,I32) -> (I32);
514    /// `logos_rt_alloc(size: i32) -> i32` — a raw 8-aligned block from the runtime's allocator. Linker
515    /// mode seeds the emitter's bump allocator (`__heap_ptr`) from ONE such SLAB at a `main` prologue, so
516    /// the emitter's heap and the runtime's `dlmalloc` never overlap in the shared linear memory.
517    RtAlloc = "logos_rt_alloc", (I32) -> (I32);
518    /// `obs(site_id: i32)` — emit the observation recorded at `site_id` (Wave 13,
519    /// OBSERVED profile only). The host resolves the category / message / span kind
520    /// from the module's `observation_sites` table (it compiled the program), so
521    /// only the site index crosses the boundary — the browser-tracing analog of
522    /// the VM's `Op::Obs`. (Payload VALUES are a follow-up: they need linear-memory
523    /// marshaling; the event STREAM — categories, messages, balanced spans —
524    /// emits here.)
525    Obs = "obs", (I32,I64,I64,I64) -> ();
526    // --- DOM (the browser tier). Element/Event handles are i64; Text args are i32
527    // handles into linear memory. A `MockDom` provides these in tests; the real
528    // browser DOM in production. ---
529    /// `dom_body() -> i64` — the document body handle.
530    DomBody = "dom_body", () -> (I64);
531    /// `dom_create_element(tag: i32 Text) -> i64` — `document.createElement`.
532    DomCreateElement = "dom_create_element", (I32) -> (I64);
533    /// `dom_create_text_node(text: i32 Text) -> i64` — `document.createTextNode`.
534    DomCreateTextNode = "dom_create_text_node", (I32) -> (I64);
535    /// `dom_set_text(el: i64, text: i32 Text)` — set `textContent`.
536    DomSetText = "dom_set_text", (I64,I32) -> ();
537    /// `dom_set_html(el: i64, html: i32 Text)` — set `innerHTML` (raw markup).
538    DomSetHtml = "dom_set_html", (I64,I32) -> ();
539    /// `dom_clear_children(el: i64)` — remove every child (re-render primitive).
540    DomClearChildren = "dom_clear_children", (I64) -> ();
541    /// `dom_on_message(topic: i32, handler: i32)` — subscribe to a relay topic.
542    ///
543    /// The last trigger with no tier. The relay itself was already built and shared between the
544    /// native node and the browser (`logicaffeine_system::relay`), so this carries a topic and a
545    /// closure and nothing else: which topic, and what a message means, are compiled LOGOS.
546    DomOnMessage = "dom_on_message", (I32, CALLBACK) -> ();
547    /// `dom_set_attribute(el: i64, name: i32 Text, value: i32 Text)` — `setAttribute`.
548    DomSetAttribute = "dom_set_attribute", (I64,I32,I32) -> ();
549    /// `dom_set_bool_attribute(el: i64, name: i32 Text, on: i64)` — an HTML boolean attribute
550    /// (`disabled`/`checked`/`required`/…, see `lgx/html.rs::is_boolean_attribute`) is a PRESENCE,
551    /// not a string: `setAttribute(name, "")` when `on`, `removeAttribute(name)` otherwise (writing
552    /// `"false"` through the string-valued `dom_set_attribute` renders `disabled="false"`, which
553    /// every browser reads as disabled — the exact bug this import exists to avoid). `lgx_lower.rs`
554    /// deliberately hands a boolean attribute's raw Bool value to the SAME `setAttribute` builtin
555    /// call (see its own comment there); this backend reads the argument's KIND at the call site
556    /// (`Op::CallBuiltin`'s used-import scan and `lower_dom_call`'s dispatch both switch on it) and
557    /// routes a Bool-valued one here instead of `DomSetAttribute`, since a `Bool` is an `i64` in
558    /// this backend's value model and `dom_set_attribute`'s own ABI is fixed at `i32 Text`.
559    DomSetBoolAttribute = "dom_set_bool_attribute", (I64,I32,I64) -> ();
560    /// `dom_append_child(parent: i64, child: i64)` — `appendChild`.
561    DomAppendChild = "dom_append_child", (I64,I64) -> ();
562    /// `dom_get_text(el: i64) -> i32 Text` — read `textContent`.
563    DomGetText = "dom_get_text", (I64) -> (HOST_TEXT);
564    /// `dom_get_value(el: i64) -> i32 Text` — read a form input's `value`.
565    DomGetValue = "dom_get_value", (I64) -> (HOST_TEXT);
566    /// `dom_set_value(el: i64, value: i32 Text)` — set a form input's `value`.
567    DomSetValue = "dom_set_value", (I64,I32) -> ();
568    /// `dom_set_checked(el, on)` — a checkbox's or radio's live CHECKED state.
569    ///
570    /// Not `dom_set_attribute(el, "checked", …)`: the attribute is `defaultChecked`, so the host
571    /// must write the PROPERTY or the box a visitor sees never changes. `on` is a Bool, which is
572    /// an `i64` in the value model.
573    DomSetChecked = "dom_set_checked", (I64,I64) -> ();
574    DomPreventDefault = "dom_prevent_default", (I64,I32) -> ();
575    /// `storage_set(area, key, value)` / `storage_get(area, key)` / `storage_remove(area, key)` —
576    /// browser storage. WITHOUT THESE A PAGE CANNOT PERSIST ANYTHING: a `## Store … persisted as`
577    /// kept its state in the module's own memory, which dies with the page, while the sentence
578    /// said otherwise. `storage_get` answers the i32 Text handle, or `0` for a key that is not
579    /// there — an absence a caller must be able to tell from a stored empty string.
580    StorageSet = "storage_set", (I32,I32,I32) -> ();
581    StorageGet = "storage_get", (I32,I32) -> (HOST_TEXT);
582    StorageRemove = "storage_remove", (I32,I32) -> ();
583    /// `dom_apply(patches)` — apply a whole DOM patch stream in ONE call.
584    ///
585    /// The bulk form the browser host is built around: the module hands over a buffer of
586    /// operations and the host walks it, deciding nothing. `patches` is the handle of a
587    /// `Seq of Int` whose elements are bytes — the same seq layout `dom_fetch_send` already
588    /// reads its headers through, so the host needs no new way to see into memory.
589    DomApply = "dom_apply", (I32) -> ();
590    /// `dom_apply_words(words: i32 Seq of Int, word_count: i64, strings: i32 Seq of Text,
591    /// string_count: i64) -> i64` — the word-format (wire v2) twin of `dom_apply`: the first
592    /// `word_count` words, whose text operands index the first `string_count` strings, applied by
593    /// the node ids they name. Answers how many adopted nodes did not match.
594    DomApplyWords = "dom_apply_words", (I32,I64,I32,I64) -> (I64);
595    /// `dom_query_selector(sel: i32 Text) -> i64` — first match (`-1` if none).
596    DomQuerySelector = "dom_query_selector", (I32) -> (I64);
597    /// `dom_add_event_listener(el: i64, event: i32 Text, handler: i32 closure)` —
598    /// register the closure handle; the host fires it via `__logos_call_closure`.
599    DomAddEventListener = "dom_add_event_listener", (I64,I32,CALLBACK) -> ();
600    /// `dom_listen_flags(el: i64, event: i32 Text, flags: i64)` — how the browser attaches `el`'s
601    /// listener for `event`: the modifier bits `semantics::dom::LISTEN_*` name (prevent 1, stop 2,
602    /// once 4, capture 8, passive 16), replacing earlier flags. A browser can only choose the
603    /// phase and passivity at `addEventListener` time, so the bits cross as data and the host
604    /// applies them; which modifiers a handler carries is decided in compiled LOGOS.
605    DomListenFlags = "dom_listen_flags", (I64,I32,I64) -> ();
606    /// `dom_event_value(event: i64) -> i32 Text` — the dispatching input's value.
607    DomEventValue = "dom_event_value", (I64) -> (HOST_TEXT);
608    /// `dom_event_key(event: i64) -> i32 Text` — the key of a keyboard event, `""` otherwise.
609    DomEventKey = "dom_event_key", (I64) -> (HOST_TEXT);
610    /// `dom_event_target(event: i64) -> i64` — the dispatching element.
611    DomEventTarget = "dom_event_target", (I64) -> (I64);
612    /// `dom_fetch_start(url: i32 Text, handler: i32 closure)` — fetch `url`; on
613    /// resolve the host fires `handler` via `__logos_call_closure`.
614    DomFetchStart = "dom_fetch_start", (I32,CALLBACK) -> ();
615    /// `dom_response_text() -> i32 Text` — the body of the delivering fetch.
616    DomResponseText = "dom_response_text", () -> (HOST_TEXT);
617    // --- The correlated fetch contract (append-only tail — import indices are
618    // positional). `dom_fetch_send` mints the request id every accessor is keyed
619    // by; the host delivers per-request, so concurrent fetches never collide. ---
620    /// `dom_fetch_send(method: i32 Text, url: i32 Text, body: i32 Text,
621    /// headers: i32 Seq-of-Text (alternating name,value), handler: i32 closure)
622    /// -> i64` — start a request; the host later fires `handler(reqId)` via
623    /// `__logos_call_closure`.
624    DomFetchSend = "dom_fetch_send", (I32,I32,I32,I32,CALLBACK) -> (I64);
625    /// `dom_response_status(req: i64) -> i64` — HTTP status (0 pending/failed).
626    DomResponseStatus = "dom_response_status", (I64) -> (I64);
627    /// `dom_response_body(req: i64) -> i32 Text` — the delivered body.
628    DomResponseBody = "dom_response_body", (I64) -> (HOST_TEXT);
629    /// `dom_response_header(req: i64, name: i32 Text) -> i32 Text` — a response
630    /// header, case-insensitive ("" absent).
631    DomResponseHeader = "dom_response_header", (I64,I32) -> (HOST_TEXT);
632    /// `dom_response_error(req: i64) -> i32 Text` — "" | "timeout" | "abort" |
633    /// "toolarge" | "network: <detail>".
634    DomResponseError = "dom_response_error", (I64) -> (HOST_TEXT);
635    /// `dom_fetch_abort(req: i64)` — final "abort"; late responses never deliver.
636    DomFetchAbort = "dom_fetch_abort", (I64) -> ();
637    /// `dom_fetch_set_timeout(req: i64, millis: i64)` — arm (>0) / clear (0).
638    DomFetchSetTimeout = "dom_fetch_set_timeout", (I64,I64) -> ();
639    // --- The history/location router (append-only tail — import indices are
640    // positional). `dom_route_path`/`dom_route_query` read `window.location`;
641    // `dom_navigate`/`dom_replace_route` are history.pushState/replaceState; the host
642    // fires the popstate handler registered by `dom_on_route` via the closure
643    // trampoline (the browser popstate listener; a MockDom `deliver_pop` in tests). ---
644    /// `dom_route_path() -> i32 Text` — the current location pathname.
645    DomRoutePath = "dom_route_path", () -> (HOST_TEXT);
646    /// `dom_route_query(name: i32 Text) -> i32 Text` — a query param ("" absent).
647    DomRouteQuery = "dom_route_query", (I32) -> (HOST_TEXT);
648    /// `dom_navigate(path: i32 Text)` — history.pushState + fire the router.
649    DomNavigate = "dom_navigate", (I32) -> ();
650    /// `dom_assign_location(url: i32 Text)` — `location.assign(url)`: load another document. What
651    /// `Navigate to` a path outside this module's own routes lowers to; the page that asked is gone.
652    DomAssignLocation = "dom_assign_location", (I32) -> ();
653    /// `dom_replace_route(path: i32 Text)` — history.replaceState.
654    DomReplaceRoute = "dom_replace_route", (I32) -> ();
655    /// `dom_on_route(handler: i32 closure)` — register the popstate handler; the host
656    /// later fires `handler(pathText)` via `__logos_call_closure`.
657    DomOnRoute = "dom_on_route", (CALLBACK) -> ();
658    // --- Page-level commands (append-only tail — import indices are positional). A page sets its
659    // own title; the browser's `document.title` is the only place that can hold it, and there is
660    // no decision here for the host to take. ---
661    /// `dom_set_title(title: i32 Text)` — `document.title = title`.
662    DomSetTitle = "dom_set_title", (I32) -> ();
663    /// `dom_set_head_html(fragment: i32 Text)` — a `Head:` block's rendered `<title>`/`<meta>`/
664    /// `<link>`/`<base>` markup, merged into `document.head` over whatever is already there (a tag
665    /// replaces the existing tag of the same identity — see `runtime.js`'s `head_identity`, ported
666    /// from `web_host.rs`'s SSR merge of the same name; everything else is added).
667    DomSetHeadHtml = "dom_set_head_html", (I32) -> ();
668    /// `dom_reload()` — `location.reload()`. The page starts over; nothing survives it.
669    DomReload = "dom_reload", () -> ();
670    /// `dom_go_back()` — `history.back()`. The browser fires popstate, which the router already
671    /// listens for, so nothing here has to re-deliver it.
672    DomGoBack = "dom_go_back", () -> ();
673    /// `dom_get_attribute(el: i64, name: i32 Text) -> i32 Text` — the READ half of the attribute
674    /// pair (`""` when absent). One import instead of `dom_add_class`/`dom_remove_class`, so
675    /// which class words survive stays in compiled LOGOS where every tier runs the same rule.
676    DomGetAttribute = "dom_get_attribute", (I64,I32) -> (HOST_TEXT);
677    /// `dom_on_window_event(event: i32 Text, handler: i32 closure)` — `window.addEventListener`.
678    /// One import for every event that happens to the PAGE rather than to an element: `offline`,
679    /// `online`, `resize`. They fire on `window` and do not bubble, so a listener on `body` would
680    /// be registered and never called.
681    DomOnWindowEvent = "dom_on_window_event", (I32,CALLBACK) -> ();
682    /// `dom_scroll_gap(el: i64) -> i64` — pixels of `el`'s content below the visible area; node 0
683    /// means the page. A reading of three numbers only a browser holds; whether the gap counts as
684    /// "the bottom" is decided in compiled LOGOS.
685    DomScrollGap = "dom_scroll_gap", (I64) -> (I64);
686    /// `dom_set_interval(ms: i64, handler: i32 closure)` — ONE repeating callback for the page.
687    /// Not one per timer: which of the page's timers a tick makes due is compiled LOGOS.
688    DomSetInterval = "dom_set_interval", (I64,CALLBACK) -> ();
689    /// `dom_event_file_name(ev: i64) -> i32 Text` — the name of the first file a `drop` carried.
690    /// A READ: what the page does about the file is compiled LOGOS.
691    DomEventFileName = "dom_event_file_name", (I64) -> (HOST_TEXT);
692    /// `dom_event_file_size(ev: i64) -> i64` — the byte size of the first file a `drop` carried,
693    /// the `size` of the `File` record the page binds it to. A READ, like its name beside it.
694    DomEventFileSize = "dom_event_file_size", (I64) -> (I64);
695    /// `dom_event_file_type(ev: i64) -> i32 Text` — the first file's MIME type (`""` when the
696    /// browser names none), the `type` of the same `File` record.
697    DomEventFileType = "dom_event_file_type", (I64) -> (HOST_TEXT);
698    /// `dom_event_file_bytes(ev: i64) -> i32 Seq of Int` — the first file's content, one byte per
699    /// slot, the `bytes` of the same `File` record. The host reads the file before it raises the
700    /// drop, so the turn runs with the bytes already in hand.
701    DomEventFileBytes = "dom_event_file_bytes", (I64) -> (HOST_SEQ);
702    /// `dom_element_command(el: i64, command: i32 Text)` — one named operation on one element:
703    /// `focus`, `blur`, `hover`, `scrollto`, `selecttext`. One import for the family, because they
704    /// differ only in which single DOM call is made and none of them decides anything.
705    DomElementCommand = "dom_element_command", (I64,I32) -> ();
706    /// `dom_clipboard_write(text: i32 Text)` — `navigator.clipboard.writeText`.
707    DomClipboardWrite = "dom_clipboard_write", (I32) -> ();
708    /// `dom_download_file(content: i32 Text, name: i32 Text)` — offer a file to the viewer.
709    DomDownloadFile = "dom_download_file", (I32,I32) -> ();
710    /// `dom_notify(message: i32 Text, tone: i32 Text)` — raise a notification.
711    DomNotify = "dom_notify", (I32,I32) -> ();
712    /// `dom_publish(topic: i32 Text, message: i32 Text)` — send a frame on a relay topic.
713    ///
714    /// The outbound twin of `dom_on_message`, and the half that construct shipped without: a page
715    /// could subscribe and had no way to SEND, so it could hear a server and never answer it, and
716    /// two tabs of one app could not talk. The relay had the other side complete the whole time
717    /// (`RelayFrame::Publish` fans out to every local subscriber and gossips on to native nodes).
718    ///
719    /// It carries ONLY the leg that leaves the page. A publish also reaches this page's own
720    /// subscribers, and that delivery is compiled LOGOS — dispatched through the same table
721    /// `Raise` drives — so who hears a publish, and when, is decided in the module. The relay
722    /// excludes the originating connection, so the two legs never deliver the same frame twice.
723    DomPublish = "dom_publish", (I32,I32) -> ();
724    /// `dom_note_turn(name: i32 Text, key: i32 Text, changes: i32 Seq of Text, failure: i32 Text)` —
725    /// the current turn's journal entry: the action's name, the instance key it ran on, the state it
726    /// changed as flattened `[field, before, after]` display strings, and the failure it stopped
727    /// with (`""` for none). A browser keeps nothing; a recording host reads all four.
728    DomNoteTurn = "dom_note_turn", (I32,I32,I32,I32) -> ();
729    /// `dom_journal_detail() -> i64 Bool` — whether this host records the journal's detail (each
730    /// turn's before/after state), so a lowered turn captures it only where someone reads it: a
731    /// recording host answers true, a shipped browser page false.
732    DomJournalDetail = "dom_journal_detail", () -> (I64);
733    /// `dom_wake_after(ms: i64)` — call the page's `__lgx_tick` with the time that passed once `ms`
734    /// more milliseconds have gone by, replacing any earlier request; a negative `ms` cancels it.
735    DomWakeAfter = "dom_wake_after", (I64) -> ();
736    /// `dom_enter_value(verb: i32 Text, selector: i32 Text, value: i32 Text) -> i64 Bool` — a
737    /// program's own `Type`/`Choose` (`"type"`/`"choose"`): the browser's default action of entering
738    /// `value` into the control `selector` names, answering whether the control took it (a text
739    /// field a visitor can reach, a `<select>` offering the option).
740    DomEnterValue = "dom_enter_value", (I32, I32, I32) -> (I64);
741    /// `dom_page_entry(node: i64, event: i32 Text, value: i32 Text) -> i64 Bool` — a driving
742    /// verb the program runs on its own page: the host enters the page's `__lgx_dispatch_node`
743    /// as an entry of its own, so a turn that fails there is contained to it and heard through the
744    /// page's failure door, and the program runs on. Answers whether the page heard the event; a
745    /// failed turn was heard.
746    DomPageEntry = "dom_page_entry", (I64, I32, I32) -> (I64);
747    // --- Exact integers (append-only tail — import indices are positional). An `Int` the program can
748    // make outgrow a machine word rides a TAGGED WORD: an even `i64` `w` is the integer `w >> 1`; an odd
749    // one, `(h << 1) | 1`, names integer `h` the host holds. The host always answers with the small form
750    // for an integer from -2^62 up to 2^62 and holds every other, and a held integer is OWNED: every
751    // answer is a handle of its own, given back through `exact_drop`. The arithmetic is the reference
752    // tier's (`semantics::arith`), each import called only where the module's inline path cannot answer. ---
753    /// `exact_box(v: i64) -> i64` — the tagged word of `v`, an `i64` too wide to sit beside the tag.
754    ExactBox = "exact_box", (I64) -> (I64);
755    /// `exact_narrow(t: i64) -> i64` — the `i64` a held integer is, or `0` when it is past one (a held
756    /// integer is never zero, so the answer is unambiguous).
757    ExactNarrow = "exact_narrow", (I64) -> (I64);
758    /// `exact_add`/`exact_sub`/`exact_mul(a: i64, b: i64) -> i64` — the tagged sum, difference, product.
759    ExactAdd = "exact_add", (I64, I64) -> (I64);
760    ExactSub = "exact_sub", (I64, I64) -> (I64);
761    ExactMul = "exact_mul", (I64, I64) -> (I64);
762    /// `exact_div`/`exact_mod`/`exact_floordiv(a: i64, b: i64) -> i64` — the truncated quotient, the
763    /// remainder with the dividend's sign, the floored quotient. The module has already refused a zero divisor.
764    ExactDiv = "exact_div", (I64, I64) -> (I64);
765    ExactMod = "exact_mod", (I64, I64) -> (I64);
766    ExactFloorDiv = "exact_floordiv", (I64, I64) -> (I64);
767    /// `exact_pow(base: i64, exp: i64) -> i64` — `base` (tagged) to the power `exp`, a machine word the
768    /// module has already bounded to `0..=u32::MAX`.
769    ExactPow = "exact_pow", (I64, I64) -> (I64);
770    /// `exact_cmp(a: i64, b: i64) -> i32` — `-1`, `0` or `1` as `a` is below, equal to or above `b`.
771    ExactCmp = "exact_cmp", (I64, I64) -> (I32);
772    /// `exact_f64(t: i64) -> f64` — the binary64 nearest the integer, ties to even, as an `Int` widens.
773    ExactF64 = "exact_f64", (I64) -> (F64);
774    /// `exact_clone(t: i64) -> i64` — a held integer's handle of its own.
775    ExactClone = "exact_clone", (I64) -> (I64);
776    /// `exact_drop(t: i64)` — give a held integer's handle back.
777    ExactDrop = "exact_drop", (I64) -> ();
778    /// `print_exact(t: i64)` — display the integer, as `Show` does.
779    PrintExact = "print_exact", (I64) -> ();
780    /// `exact_text(t: i64) -> i32 Text` — the integer's decimal as a Text, for an interpolation.
781    ExactText = "exact_text", (I64) -> (HOST_TEXT);
782    /// `env_len(name: i32 Text) -> i32` — the byte length of the variable's text in the program's
783    /// environment, `-1` when it is unset: env.lg's `get(name)`, which the VM expands into whether the
784    /// variable is set, its text and an ordinary `Option`. A browser has no environment, so there every
785    /// name is unset.
786    EnvLen = "env_len", (I32) -> (I32);
787    /// `env_into(buf: i32, name: i32 Text) -> i32` — the variable's text written into `buf`, a buffer
788    /// the module sized by [`HostFn::EnvLen`]; answers the bytes written (`0` when it is unset). The
789    /// module allocates and the host only writes, so a linked module needs no allocator export.
790    EnvInto = "env_into", (I32, I32) -> (I32);
791    /// `time_now() -> i64` — time.lg's `now()`: the Unix time in milliseconds from the real clock, not
792    /// the test-fixed moment [`HostFn::Now`] answers.
793    TimeNow = "time_now", () -> (I64);
794    /// The exact extension's value runtime (`logicaffeine_data::abi`, the C ABI the C backends link), linked into
795    /// the module: an i32 handle per value ([`kind::Kind::Tower`]). A constructor answers a fresh handle; an
796    /// operation borrows its operands and answers a fresh handle, null when it has no answer, which
797    /// [`HostFn::ValueChecked`] turns into the runtime's sentence and a trap.
798    ValueInt = "logos_rt_value_int", (I64) -> (I32);
799    ValueFloat = "logos_rt_value_float", (F64) -> (I32);
800    ValueBool = "logos_rt_value_bool", (I32) -> (I32);
801    ValueNothing = "logos_rt_value_nothing", () -> (I32);
802    ValueDate = "logos_rt_value_date", (I32) -> (I32);
803    ValueMoment = "logos_rt_value_moment", (I64) -> (I32);
804    ValueTime = "logos_rt_value_time", (I64) -> (I32);
805    ValueSpan = "logos_rt_value_span", (I32, I32) -> (I32);
806    ValueList = "logos_rt_value_list", (I32, I32) -> (I32);
807    ValueClone = "logos_rt_value_clone", (I32) -> (I32);
808    /// `logos_rt_value_push(list, v) -> status` — and `set_item`'s: `1`, or `0` with the sentence kept.
809    ValuePush = "logos_rt_value_push", (I32, I32) -> (I32);
810    ValueSetItem = "logos_rt_value_set_item", (I32, I32, I32) -> (I32);
811    ValuePop = "logos_rt_value_pop", (I32) -> (I32);
812    ValueItems = "logos_rt_value_items", (I32) -> (I32);
813    ValueItemAt = "logos_rt_value_item_at", (I32, I64) -> (I32);
814    ValueSlice = "logos_rt_value_slice", (I32, I32, I32) -> (I32);
815    ValueAdd = "logos_rt_value_add", (I32, I32) -> (I32);
816    ValueSub = "logos_rt_value_sub", (I32, I32) -> (I32);
817    ValueMul = "logos_rt_value_mul", (I32, I32) -> (I32);
818    ValueDiv = "logos_rt_value_div", (I32, I32) -> (I32);
819    ValueExactDiv = "logos_rt_value_exact_div", (I32, I32) -> (I32);
820    ValueFloorDiv = "logos_rt_value_floor_div", (I32, I32) -> (I32);
821    ValueRem = "logos_rt_value_rem", (I32, I32) -> (I32);
822    ValuePow = "logos_rt_value_pow", (I32, I32) -> (I32);
823    ValueApproxEq = "logos_rt_value_approx_eq", (I32, I32) -> (I32);
824    ValueSeqConcat = "logos_rt_value_seq_concat", (I32, I32) -> (I32);
825    ValueBitAnd = "logos_rt_value_bit_and", (I32, I32) -> (I32);
826    ValueBitOr = "logos_rt_value_bit_or", (I32, I32) -> (I32);
827    ValueBitXor = "logos_rt_value_bit_xor", (I32, I32) -> (I32);
828    ValueShl = "logos_rt_value_shl", (I32, I32) -> (I32);
829    ValueShr = "logos_rt_value_shr", (I32, I32) -> (I32);
830    ValueMin = "logos_rt_value_min", (I32, I32) -> (I32);
831    ValueMax = "logos_rt_value_max", (I32, I32) -> (I32);
832    ValuePower = "logos_rt_value_power", (I32, I32) -> (I32);
833    ValueItem = "logos_rt_value_item", (I32, I32) -> (I32);
834    ValueEq = "logos_rt_value_eq", (I32, I32) -> (I32);
835    ValueNe = "logos_rt_value_ne", (I32, I32) -> (I32);
836    ValueLt = "logos_rt_value_lt", (I32, I32) -> (I32);
837    ValueGt = "logos_rt_value_gt", (I32, I32) -> (I32);
838    ValueLe = "logos_rt_value_le", (I32, I32) -> (I32);
839    ValueGe = "logos_rt_value_ge", (I32, I32) -> (I32);
840    ValueNot = "logos_rt_value_not", (I32) -> (I32);
841    ValueAbs = "logos_rt_value_abs", (I32) -> (I32);
842    ValueSqrt = "logos_rt_value_sqrt", (I32) -> (I32);
843    ValueFloor = "logos_rt_value_floor", (I32) -> (I32);
844    ValueCeil = "logos_rt_value_ceil", (I32) -> (I32);
845    ValueRound = "logos_rt_value_round", (I32) -> (I32);
846    /// The value of a number this runtime holds in Rust (a big integer, a rational, a decimal); a tuple of a list's
847    /// items; and `apply(index, args)`, the builtin of the extension at `index` of `extension::Builtin::ALL`
848    /// applied to the items of the list `args`.
849    ValueOfBigint = "logos_rt_value_of_bigint", (I32) -> (I32);
850    ValueOfRational = "logos_rt_value_of_rational", (I32) -> (I32);
851    ValueOfDecimal = "logos_rt_value_of_decimal", (I32) -> (I32);
852    ValueTupleOf = "logos_rt_value_tuple_of", (I32) -> (I32);
853    ValueApply = "logos_rt_value_apply", (I32, I32) -> (I32);
854    /// `define(kind, base, name, body) -> handle` — the real number the closure body `body` defines by its digits
855    /// in `base` or its approximations (`kind`, `name` Texts): the runtime reads it back through the module's
856    /// `logos_program_defines(body, n)`.
857    ValueDefine = "logos_rt_value_define", (I32, I64, I32, I32) -> (I32);
858    /// The linked runtime's adapters of that ABI to the module's (`link.rs`): `checked(h)` answers `h`, or stops
859    /// the program with the runtime's sentence when `h` is null (a status of `0` likewise).
860    ValueChecked = "logos_rt_value_checked", (I32) -> (I32);
861    /// `to_text(v) -> Text` — how the value prints, as a Text the runtime lays out.
862    ValueToText = "logos_rt_value_to_text", (I32) -> (I32);
863    ValueOfText = "logos_rt_value_of_text", (I32) -> (I32);
864    ValueLengthI64 = "logos_rt_value_length_i64", (I32) -> (I64);
865    /// `truth_i32(v)` — the truth a condition reads from the value, refused for an undecided answer.
866    ValueTruthI32 = "logos_rt_value_truth_i32", (I32) -> (I32);
867    ValueContainsI64 = "logos_rt_value_contains_i64", (I32, I32) -> (I64);
868    /// `to_i64(v)` — the `Int` the value is, where a machine-integer key is read; refused for any other value.
869    ValueToI64 = "logos_rt_value_to_i64", (I32) -> (I64);
870    /// `integer_at(v, place)` — the `Int` the value is where a machine integer is read at `place` (an
871    /// `IntegerPlace::code`); an integer past i64 or a fraction refused in the VM's words there.
872    ValueIntegerAt = "logos_rt_value_integer_at", (I32, I32) -> (I64);
873    /// `logos_rt_rational_cmp(a, b) -> i32` — `-1`, `0` or `1` as the rational `a` is below, equal to or above `b`.
874    RationalCmp = "logos_rt_rational_cmp", (I32, I32) -> (I32);
875    /// `logos_rt_rational_quotient(a, b)` — `a / b` under the VM's rules: two whole numbers as integers, truncating.
876    RationalQuotient = "logos_rt_rational_quotient", (I32, I32) -> (I32);
877    /// `logos_rt_rational_floor_quotient(a, b)` — `a // b`, the floor of the exact quotient.
878    RationalFloorQuotient = "logos_rt_rational_floor_quotient", (I32, I32) -> (I32);
879    /// `logos_rt_rational_remainder(a, b)` — `a % b`: two whole numbers' integer remainder; a fraction refused.
880    RationalRemainder = "logos_rt_rational_remainder", (I32, I32) -> (I32);
881    /// `logos_rt_rational_power(a, b)` — `a ** b`: a whole base takes the integer's power.
882    RationalPower = "logos_rt_rational_power", (I32, I32) -> (I32);
883    /// `logos_rt_rational_bitwise(a, b, op) -> i64` — `& | ^ << >>` (op 0..=4) of two whole numbers.
884    RationalBitwise = "logos_rt_rational_bitwise", (I32, I32, I32) -> (I64);
885    /// `logos_rt_rational_cmp_f64(a, f) -> i32` — the rational's order against the real's exact value, 2 for a NaN.
886    RationalCmpF64 = "logos_rt_rational_cmp_f64", (I32, F64) -> (I32);
887    /// `logos_rt_rational_to_f64(a) -> f64` — the double the VM computes with when a rational meets a real.
888    RationalToF64 = "logos_rt_rational_to_f64", (I32) -> (F64);
889    /// `as_i64(a, place)` — the machine integer a whole rational within i64 is where one is read at `place` (an
890    /// `IntegerPlace::code`); else the VM's refusal there.
891    RationalAsI64 = "logos_rt_rational_as_i64", (I32, I32) -> (I64);
892}
893
894/// Stable order — also the order host functions take their wasm import indices.
895/// A `set_rates(map)`'s VALUE kind — the kind of a `SetIndex` value written into the map, resolved by
896/// following `Move` aliases of `target` (the call arg is a Move-copy of the built map register) to any
897/// register a `SetIndex` populated. `None` if no populating `SetIndex` is statically visible.
898fn set_rates_value_kind(ops: &[Op], target: u16, kinds: &KindTable) -> Option<Kind> {
899    let mut aliases = std::collections::HashSet::new();
900    aliases.insert(target);
901    let mut changed = true;
902    while changed {
903        changed = false;
904        for op in ops {
905            if let Op::Move { dst, src } = op {
906                if aliases.contains(dst) && aliases.insert(*src) {
907                    changed = true;
908                }
909                if aliases.contains(src) && aliases.insert(*dst) {
910                    changed = true;
911                }
912            }
913        }
914    }
915    ops.iter().find_map(|op| match op {
916        Op::SetIndex {
917            collection, value, ..
918        } if aliases.contains(collection) => kinds.get(*value as usize),
919        _ => None,
920    })
921}
922
923/// The `logos_rt_wire_bytes_*` runtime host for `wireBytes(value)` (linker mode) by the ARGUMENT'S kind
924/// — each reconstructs the corresponding `RuntimeValue` and marshals it via the REAL codec. `None` for a
925/// kind not yet reconstructed (a composite: soundly refused). Shared by the import scan and the lowering.
926fn wire_bytes_host_fn(arg_kind: Option<Kind>) -> Option<HostFn> {
927    match arg_kind {
928        Some(Kind::Int) => Some(HostFn::WireBytesInt),
929        Some(Kind::Bool) => Some(HostFn::WireBytesBool),
930        Some(Kind::Float) => Some(HostFn::WireBytesFloat),
931        Some(Kind::Text) => Some(HostFn::WireBytesText),
932        _ => None,
933    }
934}
935
936/// The host import a DOM, storage or journal builtin lowers to — one import per builtin, whatever its
937/// arguments' kinds — or `None`. `setAttribute` picks its import by the value's kind and is not here.
938/// The import scan notes what this names, and [`pure_read_operands`] reads which of the builtin's
939/// arguments the host keeps off the same row ([`HostFn::retained_params`]).
940fn dom_import_of(b: BuiltinId) -> Option<HostFn> {
941    Some(match b {
942        BuiltinId::DomBody => HostFn::DomBody,
943        BuiltinId::DomCreateElement => HostFn::DomCreateElement,
944        BuiltinId::DomCreateTextNode => HostFn::DomCreateTextNode,
945        BuiltinId::DomSetText => HostFn::DomSetText,
946        BuiltinId::DomSetHtml => HostFn::DomSetHtml,
947        BuiltinId::DomClearChildren => HostFn::DomClearChildren,
948        BuiltinId::DomOnMessage => HostFn::DomOnMessage,
949        BuiltinId::DomAppendChild => HostFn::DomAppendChild,
950        BuiltinId::DomGetText => HostFn::DomGetText,
951        BuiltinId::DomGetValue => HostFn::DomGetValue,
952        BuiltinId::DomSetValue => HostFn::DomSetValue,
953        BuiltinId::DomSetChecked => HostFn::DomSetChecked,
954        BuiltinId::DomPreventDefault => HostFn::DomPreventDefault,
955        BuiltinId::StorageSet => HostFn::StorageSet,
956        BuiltinId::StorageGet => HostFn::StorageGet,
957        BuiltinId::StorageGetOr => HostFn::StorageGet,
958        BuiltinId::StorageRemove => HostFn::StorageRemove,
959        BuiltinId::DomApplyPatches => HostFn::DomApply,
960        BuiltinId::DomApplyWords => HostFn::DomApplyWords,
961        BuiltinId::DomQuerySelector => HostFn::DomQuerySelector,
962        BuiltinId::DomAddEventListener => HostFn::DomAddEventListener,
963        BuiltinId::DomListenFlags => HostFn::DomListenFlags,
964        BuiltinId::DomEnterValue => HostFn::DomEnterValue,
965        BuiltinId::DomDispatchEntry => HostFn::DomPageEntry,
966        BuiltinId::DomEventValue => HostFn::DomEventValue,
967        BuiltinId::DomEventKey => HostFn::DomEventKey,
968        BuiltinId::DomEventTarget => HostFn::DomEventTarget,
969        BuiltinId::DomFetchText => HostFn::DomFetchStart,
970        BuiltinId::DomResponseText => HostFn::DomResponseText,
971        BuiltinId::DomFetchSend => HostFn::DomFetchSend,
972        BuiltinId::DomResponseStatus => HostFn::DomResponseStatus,
973        BuiltinId::DomResponseBody => HostFn::DomResponseBody,
974        BuiltinId::DomResponseHeader => HostFn::DomResponseHeader,
975        BuiltinId::DomResponseError => HostFn::DomResponseError,
976        BuiltinId::DomFetchAbort => HostFn::DomFetchAbort,
977        BuiltinId::DomFetchSetTimeout => HostFn::DomFetchSetTimeout,
978        BuiltinId::DomRoutePath => HostFn::DomRoutePath,
979        BuiltinId::DomRouteQuery => HostFn::DomRouteQuery,
980        BuiltinId::DomNavigate => HostFn::DomNavigate,
981        BuiltinId::DomAssignLocation => HostFn::DomAssignLocation,
982        BuiltinId::DomSetTitle => HostFn::DomSetTitle,
983        BuiltinId::DomSetHeadHtml => HostFn::DomSetHeadHtml,
984        BuiltinId::DomReload => HostFn::DomReload,
985        BuiltinId::DomGoBack => HostFn::DomGoBack,
986        BuiltinId::DomGetAttribute => HostFn::DomGetAttribute,
987        BuiltinId::DomOnWindowEvent => HostFn::DomOnWindowEvent,
988        BuiltinId::DomScrollGap => HostFn::DomScrollGap,
989        BuiltinId::DomSetInterval => HostFn::DomSetInterval,
990        BuiltinId::DomEventFileName => HostFn::DomEventFileName,
991        BuiltinId::DomEventFileSize => HostFn::DomEventFileSize,
992        BuiltinId::DomEventFileType => HostFn::DomEventFileType,
993        BuiltinId::DomEventFileBytes => HostFn::DomEventFileBytes,
994        BuiltinId::DomElementCommand => HostFn::DomElementCommand,
995        BuiltinId::DomClipboardWrite => HostFn::DomClipboardWrite,
996        BuiltinId::DomDownloadFile => HostFn::DomDownloadFile,
997        BuiltinId::DomNotify => HostFn::DomNotify,
998        BuiltinId::DomPublish => HostFn::DomPublish,
999        BuiltinId::NoteTurn => HostFn::DomNoteTurn,
1000        BuiltinId::DomJournalDetail => HostFn::DomJournalDetail,
1001        BuiltinId::DomWakeAfter => HostFn::DomWakeAfter,
1002        BuiltinId::DomReplaceRoute => HostFn::DomReplaceRoute,
1003        BuiltinId::DomOnRoute => HostFn::DomOnRoute,
1004        _ => return None,
1005    })
1006}
1007
1008/// The `logos_rt_lanes_*` runtime host for a general-`LanesVal` SIMD builtin (linker mode), or `None`
1009/// if `b` is not one of them. Shared by the import scan and the lowering so both agree on the op→host
1010/// map. Distinct from the SHA-1 `Kind::Lanes` (inline `Lanes4Word32`) ops, which are their own hosts.
1011fn lanes_v_host_fn(b: BuiltinId) -> Option<HostFn> {
1012    Some(match b {
1013        BuiltinId::Lanes16Word8Make => HostFn::Lanes16FromBytes,
1014        BuiltinId::Lanes8Word32 => HostFn::Lanes8FromWords,
1015        BuiltinId::Lanes4Word64 => HostFn::Lanes4W64FromWords,
1016        BuiltinId::Splat16Word8 => HostFn::LanesSplat16,
1017        BuiltinId::Splat8Word32 => HostFn::LanesSplat8,
1018        BuiltinId::SeqOfLanes16W8 | BuiltinId::SeqOfLanes8 => HostFn::LanesToSeq,
1019        BuiltinId::Shuffle16 => HostFn::LanesShuffle,
1020        BuiltinId::InterleaveLo16 => HostFn::LanesInterleaveLo,
1021        BuiltinId::InterleaveHi16 => HostFn::LanesInterleaveHi,
1022        BuiltinId::ByteAdd16 => HostFn::LanesByteAdd,
1023        BuiltinId::Maddubs16 => HostFn::LanesMaddubs,
1024        BuiltinId::Packus16 => HostFn::LanesPackus,
1025        BuiltinId::ShrBytes16 => HostFn::LanesShrBytes,
1026        _ => return None,
1027    })
1028}
1029
1030/// Every host import the emitted modules can name, in catalog order — the whole LOGOS↔host
1031/// boundary as text.
1032///
1033/// This surface is the framework's contract with the browser, and it is the thing that must NOT
1034/// quietly grow: LOGOS runs the page as WebAssembly, so an import is the platform forcing our
1035/// hand (wasm cannot touch the DOM), while framework LOGIC belongs in compiled LOGOS where every
1036/// tier can run it. Exposing the list is what lets a lock hold that line.
1037pub fn host_import_names() -> Vec<&'static str> {
1038    HOST_FNS.iter().map(|h| h.field()).collect()
1039}
1040
1041/// Every name an emitted module exports that is the module's own rather than a lowered
1042/// `lgx_lower::LGX_ENTRIES` entry: `main`, the memory and heap pointer, the closure trampoline, the
1043/// immediate-mode `render`, and each runtime function a host calls.
1044pub fn runtime_export_names() -> Vec<&'static str> {
1045    // Exhaustive, so a new runtime function is placed here or answered `None` by its `export`.
1046    fn listed(f: RuntimeFn) -> RuntimeFn {
1047        match f {
1048            RuntimeFn::Alloc
1049            | RuntimeFn::Free
1050            | RuntimeFn::HeapAllocated
1051            | RuntimeFn::HeapUsed
1052            | RuntimeFn::IterUnwind
1053            | RuntimeFn::TextNew
1054            | RuntimeFn::SeqNew
1055            | RuntimeFn::SeqSlot
1056            | RuntimeFn::SeqPushSlot
1057            | RuntimeFn::SeqClone
1058            | RuntimeFn::SeqOwn
1059            | RuntimeFn::TextEq
1060            | RuntimeFn::TextConcat
1061            | RuntimeFn::MapClone
1062            | RuntimeFn::MapOwn
1063            | RuntimeFn::MapPut
1064            | RuntimeFn::MapFind
1065            | RuntimeFn::MapAt
1066            | RuntimeFn::AddChecked
1067            | RuntimeFn::SubChecked
1068            | RuntimeFn::MulChecked
1069            | RuntimeFn::ExactAdd
1070            | RuntimeFn::ExactSub
1071            | RuntimeFn::ExactMul
1072            | RuntimeFn::ExactAddW
1073            | RuntimeFn::ExactSubW
1074            | RuntimeFn::ExactMulW
1075            | RuntimeFn::ExactTag
1076            | RuntimeFn::ExactRelease
1077            | RuntimeFn::ExactNarrow
1078            | RuntimeFn::ExactClone
1079            | RuntimeFn::ExactSeqPromote
1080            | RuntimeFn::ExactCell
1081            | RuntimeFn::ExactCompare
1082            | RuntimeFn::ExactSeqAt
1083            | RuntimeFn::ExactSeqStore
1084            | RuntimeFn::ExactMapPromoteKey
1085            | RuntimeFn::ExactMapPromoteValue
1086            | RuntimeFn::NewHeader
1087            | RuntimeFn::Share
1088            | RuntimeFn::TurnRetain
1089            | RuntimeFn::Retain
1090            | RuntimeFn::RetainChildren
1091            | RuntimeFn::Release
1092            | RuntimeFn::Safepoint
1093            | RuntimeFn::FreeObject
1094            | RuntimeFn::Census
1095            | RuntimeFn::CensusVisit
1096            | RuntimeFn::ClosureRetain
1097            | RuntimeFn::ClosureRelease => f,
1098        }
1099    }
1100    let runtime = [
1101        RuntimeFn::Alloc,
1102        RuntimeFn::Free,
1103        RuntimeFn::HeapAllocated,
1104        RuntimeFn::HeapUsed,
1105        RuntimeFn::IterUnwind,
1106        RuntimeFn::TextNew,
1107        RuntimeFn::SeqNew,
1108        RuntimeFn::SeqSlot,
1109        RuntimeFn::SeqPushSlot,
1110        RuntimeFn::SeqClone,
1111        RuntimeFn::SeqOwn,
1112        RuntimeFn::TextEq,
1113        RuntimeFn::TextConcat,
1114        RuntimeFn::MapClone,
1115        RuntimeFn::MapOwn,
1116        RuntimeFn::MapPut,
1117        RuntimeFn::MapFind,
1118        RuntimeFn::MapAt,
1119        RuntimeFn::AddChecked,
1120        RuntimeFn::SubChecked,
1121        RuntimeFn::MulChecked,
1122        RuntimeFn::ExactAdd,
1123        RuntimeFn::ExactSub,
1124        RuntimeFn::ExactMul,
1125        RuntimeFn::ExactAddW,
1126        RuntimeFn::ExactSubW,
1127        RuntimeFn::ExactMulW,
1128        RuntimeFn::ExactTag,
1129        RuntimeFn::ExactRelease,
1130        RuntimeFn::ExactNarrow,
1131        RuntimeFn::ExactClone,
1132        RuntimeFn::ExactSeqPromote,
1133        RuntimeFn::ExactCell,
1134        RuntimeFn::ExactCompare,
1135        RuntimeFn::ExactSeqAt,
1136        RuntimeFn::ExactSeqStore,
1137        RuntimeFn::ExactMapPromoteKey,
1138        RuntimeFn::ExactMapPromoteValue,
1139        RuntimeFn::NewHeader,
1140        RuntimeFn::Share,
1141        RuntimeFn::TurnRetain,
1142        RuntimeFn::Retain,
1143        RuntimeFn::RetainChildren,
1144        RuntimeFn::Release,
1145        RuntimeFn::Safepoint,
1146        RuntimeFn::FreeObject,
1147        RuntimeFn::Census,
1148        RuntimeFn::CensusVisit,
1149        RuntimeFn::ClosureRetain,
1150        RuntimeFn::ClosureRelease,
1151    ];
1152    [
1153        "main",
1154        "memory",
1155        "__heap_ptr",
1156        "__logos_call_closure",
1157        "__logos_render",
1158    ]
1159    .into_iter()
1160    .chain(runtime.into_iter().filter_map(|f| listed(f).export()))
1161    .collect()
1162}
1163
1164/// Every host import that answers with a Text the host writes into the module's heap through
1165/// `__logos_text_new`, in catalog order — the imports that make a module carry that allocator.
1166pub fn host_text_import_names() -> Vec<&'static str> {
1167    HOST_FNS
1168        .iter()
1169        .filter(|h| h.returns_host_text())
1170        .map(|h| h.field())
1171        .collect()
1172}
1173
1174/// Every host import that answers with a sequence the host builds in the module's heap through
1175/// `__logos_seq_new`, in catalog order — the imports that make a module carry that allocator.
1176pub fn host_seq_import_names() -> Vec<&'static str> {
1177    HOST_FNS
1178        .iter()
1179        .filter(|h| h.returns_host_seq())
1180        .map(|h| h.field())
1181        .collect()
1182}
1183
1184/// Every host import as `(name, params, results)`, in canonical order — the SHAPE of the ABI,
1185/// not just its spelling.
1186///
1187/// `host_import_names` froze the names, and a name is the half that a rename breaks loudly.
1188/// The other half — how many arguments an import takes and what it gives back — was written
1189/// down three times in two crates and read by no test at all, so changing one host's arity
1190/// left the emitted module and its hand-written JS host disagreeing, and the module simply
1191/// failed to instantiate with nothing to point at.
1192pub fn host_import_signatures() -> Vec<(&'static str, Vec<u8>, Vec<u8>)> {
1193    HOST_FNS
1194        .iter()
1195        .map(|h| (h.field(), h.params(), h.results()))
1196        .collect()
1197}
1198
1199impl HostFn {
1200    /// The sink that displays a value of kind `k` — matching the tree-walker's
1201    /// `to_display_string` for that scalar kind. `None` for a kind without a scalar sink yet
1202    /// (e.g. a sequence, whose formatted display lands with the heap value model).
1203    fn for_show(k: Kind) -> Option<HostFn> {
1204        Some(match k {
1205            Kind::Nothing => HostFn::PrintNothing,
1206            Kind::Int => HostFn::PrintI64,
1207            Kind::Bool => HostFn::PrintBool,
1208            Kind::Char => HostFn::PrintChar,
1209            Kind::Float => HostFn::PrintF64,
1210            Kind::Date => HostFn::PrintDate,
1211            Kind::Moment => HostFn::PrintMoment,
1212            Kind::Duration => HostFn::PrintDuration,
1213            Kind::Time => HostFn::PrintTime,
1214            Kind::Span => HostFn::PrintSpan,
1215            Kind::SeqInt => HostFn::PrintSeqI64,
1216            Kind::SeqBool => HostFn::PrintSeqBool,
1217            Kind::SeqWord32 => HostFn::PrintSeqWord32,
1218            Kind::SeqWord64 => HostFn::PrintSeqWord64,
1219            Kind::SeqFloat => HostFn::PrintSeqF64,
1220            Kind::SeqText => HostFn::PrintSeqText,
1221            // A never-refined empty sequence formats as `[]`; the i64 sink reads zero elements.
1222            Kind::SeqAny => HostFn::PrintSeqI64,
1223            // A sequence of boxed elements has no single scalar sink, for the same reason a whole
1224            // `Seq of <record>` does not: displaying it means walking the elements and displaying
1225            // each, which is the heap value model rather than one host call.
1226            Kind::SeqHandle => return None,
1227            Kind::Text => HostFn::PrintText,
1228            // A whole struct's `TypeName { field: val, … }` display is assembled by `lower_show_struct`
1229            // (fields in DETERMINISTIC alphabetical order, matching the VM's now-sorted `HashMap`
1230            // display) — handled by the `Op::Show` dispatch, not this per-kind scalar-sink table.
1231            Kind::Struct => return None,
1232            // A whole `Set of Int` is insertion-ordered in both the VM (a `Vec`) and the AOT backend,
1233            // so it displays deterministically: `{e0, e1, …}`.
1234            Kind::Set => HostFn::PrintSetI64,
1235            Kind::SetText | Kind::CrdtSetText => HostFn::PrintSetText,
1236            // A `ConvergentCount`/`Tally` counter object is never `Show`n as an object: `Show obj's
1237            // field` projects it to its Int TOTAL at `GetField` (`lower_get_counter_total`), so this
1238            // per-kind sink never sees the raw counter — it has no direct display form.
1239            Kind::CrdtCounter => return None,
1240            // A whole Map's `{k: v, …}` display is assembled by `lower_show_map` (a runtime entry loop
1241            // in insertion order, matching the VM's `IndexMap`), not a single scalar sink — so the
1242            // `Op::Show` dispatch handles it directly, not this per-kind host table.
1243            Kind::Map => return None,
1244            // Showing an enum value (`Ctor` / `Ctor(args)`) lands with the argument payload model.
1245            Kind::Enum => return None,
1246            // A closure has no display form.
1247            Kind::Closure => return None,
1248            // A `BigInt` `Show` is a TWO-step lowering (`logos_rt_bigint_to_text` → `print_text`), not a
1249            // single sink, so it is handled directly by `lower_show` / the import scan — not here.
1250            Kind::BigInt => return None,
1251            // A `Complex` `Show` likewise renders via `logos_rt_complex_to_text` → `print_text` (dispatch).
1252            Kind::Complex => return None,
1253            // A `Modular` `Show` renders via `logos_rt_modular_to_text` → `print_text` (dispatch).
1254            Kind::Modular => return None,
1255            // A `Decimal` `Show` renders via `logos_rt_decimal_to_text` → `print_text` (dispatch).
1256            Kind::Decimal => return None,
1257            // A `Money` `Show` renders via `logos_rt_money_to_text` → `print_text` (dispatch).
1258            Kind::Money => return None,
1259            Kind::Quantity => return None,
1260            Kind::Uuid => return None,
1261            Kind::Lanes => return None,
1262            // A SIMD lane vector is not `Show`n directly (it is unpacked back to a `Seq` first).
1263            Kind::LanesV => return None,
1264            // A value of the exact extension prints through the runtime's text ([`tower`]).
1265            Kind::Tower => return None,
1266            // A dynamic (wire-decoded) value `Show`s via a two-step `logos_rt_dynamic_to_text` → `print_text`
1267            // dispatch (like the numeric `to_text` handles), NOT a single scalar sink.
1268            Kind::Dynamic => return None,
1269            // A whole heterogeneous tuple's display (mixed element formats) is deferred; element
1270            // access (`item N of t`) at each position's kind works.
1271            Kind::Tuple => return None,
1272            // A whole sequence of structs would need each struct's display, which is non-
1273            // deterministic (struct field order); element access (`item N of xs`) works.
1274            Kind::SeqStruct => return None,
1275            // A whole sequence of enums (each `Ctor`/`Ctor(args)`) is deferred; iteration +
1276            // `Inspect`/`TestArm` on each element works.
1277            Kind::SeqEnum => return None,
1278            // A whole nested sequence's display is deferred (needs a per-row formatter); row access
1279            // (`item N of m` → a `SeqInt`) and element access work.
1280            Kind::SeqSeqInt => return None,
1281            // A `Rational` is Shown via a dedicated two-arg (`num`, `den`) path in `Op::Show`, not this
1282            // single-value sink — so it never reaches here.
1283            Kind::Rational => return None,
1284            // An `Optional` is Shown via a dedicated null-check path in `Op::Show` (null → "nothing",
1285            // else the boxed inner) — so it never reaches this single-value sink.
1286            Kind::Optional => return None,
1287            // A `Word32`/`Word64` Shows as its UNSIGNED value via a dedicated `print_word` path in
1288            // `Op::Show` (Word32 zero-extends to i64 first) — never this signed single-value sink.
1289            Kind::Word32 | Kind::Word64 => return None,
1290        })
1291    }
1292}
1293
1294/// Interns `(params, results)` value-type signatures into a deduped Type section.
1295#[derive(Default)]
1296struct TypeTable {
1297    sigs: Vec<(Vec<u8>, Vec<u8>)>,
1298}
1299
1300impl TypeTable {
1301    fn intern(&mut self, params: Vec<u8>, results: Vec<u8>) -> u32 {
1302        if let Some(i) = self
1303            .sigs
1304            .iter()
1305            .position(|(p, r)| *p == params && *r == results)
1306        {
1307            return i as u32;
1308        }
1309        self.sigs.push((params, results));
1310        (self.sigs.len() - 1) as u32
1311    }
1312
1313    fn encode(&self) -> Vec<u8> {
1314        let mut out = Vec::new();
1315        leb_u32(&mut out, self.sigs.len() as u32);
1316        for (params, results) in &self.sigs {
1317            out.push(0x60); // func type
1318            leb_u32(&mut out, params.len() as u32);
1319            out.extend_from_slice(params);
1320            leb_u32(&mut out, results.len() as u32);
1321            out.extend_from_slice(results);
1322        }
1323        out
1324    }
1325}
1326
1327/// One function the assembler will emit: its rebased ops, inferred register kinds, parameter
1328/// count, register frame size, result kind (`None` = returns nothing / void), and which basic
1329/// blocks are statically reachable (dead blocks — e.g. the monomorphized-out branch of an
1330/// `and`/`or` runtime type-dispatch — are emitted as a single `unreachable`).
1331struct Plan {
1332    ops: Vec<Op>,
1333    kinds: KindTable,
1334    num_params: u32,
1335    num_regs: u32,
1336    result: Option<Kind>,
1337    reachable_blocks: Vec<bool>,
1338    /// Per-op struct slot/field/count map (see [`kind::struct_layout`]) — drives `NewStruct`
1339    /// sizing and `StructInsert`/`GetField` slot addressing.
1340    structs: kind::StructLayout,
1341    /// Per-pc: whether this `StructInsert` must copy-on-write its target to preserve struct value
1342    /// semantics (see [`cow_struct_inserts`]).
1343    cow_inserts: Vec<bool>,
1344    /// Per composite-handle register, its resolved access SHAPE — `structs.reg_shape` (params + local
1345    /// structs) COMPLETED post-inference with locally-built map/enum/het-tuple shapes (which need the
1346    /// register kinds inference produced). Read at each `MakeClosure` to type a captured composite.
1347    reg_shape: std::collections::HashMap<u16, kind::ParamShape>,
1348    /// If this function `Return`s a single statically-known closure (every reachable closure `Return`
1349    /// agreeing on one body function index), that index — so a caller of this function can resolve a
1350    /// `CallValue` on the returned handle. `None` if it returns no closure, or returns more than one.
1351    return_closure: Option<u16>,
1352    /// Per op position, for an `IterNext`, the register its loop walks (the `IterPrepare`↔`IterNext`
1353    /// pairing), so the step can tell a sequence's slots from a Text's characters.
1354    iter_iterable: Vec<Option<usize>>,
1355    /// Numeric ranges consumed only by the immediately following iterator. Nothing can observe
1356    /// a sequence representation, so the loop stores the captured bounds instead.
1357    range_loops: std::collections::HashMap<u16, (u16, u16)>,
1358    /// The place lowering's record-field moves (see [`PlaceSites`]).
1359    place: PlaceSites,
1360    /// Per register: every read of it is transient (see [`transient_reads`]), so the value it holds
1361    /// needs no alias retain.
1362    transient: Vec<bool>,
1363    /// Per register, the DECLARED type of the value it holds wherever one is known — a parameter's,
1364    /// a declared construction's or binding's, one the layout pass carried to it — which is what a
1365    /// display of the value renders ([`display`]).
1366    declared: std::collections::HashMap<u16, BoundaryType>,
1367    /// The `mutable` parameters (registers below `num_params`): each one's final value is a result of the
1368    /// function after its declared one, which the caller stores into the argument register it lent, as the VM's
1369    /// register window leaves it (`CompiledFunction::mutable_param_regs`).
1370    inout: Vec<u16>,
1371    /// Per register: it holds a tagged word, the exact integer [`exact`] decided it can outgrow i64 for.
1372    /// Empty in a module no integer of which can.
1373    exact: Vec<bool>,
1374    /// Per parameter: its argument arrives tagged ([`exact::Signatures`]).
1375    params_tagged: Vec<bool>,
1376    /// The function's result is tagged.
1377    ret_tagged: bool,
1378    absence: bool,
1379    absence_regs: Vec<bool>,
1380    absence_globals: Vec<bool>,
1381    /// What the plan does with values of the exact extension ([`tower`]).
1382    tower: tower::Towers,
1383    /// A STUB: a function unreachable from `Main` that the AOT dropped (its body is a single `unreachable`
1384    /// trap, its type `() -> ()`). This lets a program import a large stdlib module and compile even when
1385    /// the UNUSED functions use ops the AOT can't lower (e.g. `uuid_v5` pulls in `uuid.lg`, whose unused
1386    /// `uuidParse`/`decodeNibbles` use a `Lanes16Word8` SIMD vocabulary the backend doesn't have).
1387    stub: bool,
1388}
1389
1390impl Plan {
1391    /// A dropped (unreachable) function — a `() -> ()` body that just traps.
1392    fn stub() -> Plan {
1393        Plan {
1394            ops: Vec::new(),
1395            kinds: KindTable::empty(),
1396            num_params: 0,
1397            num_regs: 0,
1398            result: None,
1399            reachable_blocks: Vec::new(),
1400            structs: kind::StructLayout::default(),
1401            cow_inserts: Vec::new(),
1402            reg_shape: std::collections::HashMap::new(),
1403            return_closure: None,
1404            iter_iterable: Vec::new(),
1405            range_loops: std::collections::HashMap::new(),
1406            place: PlaceSites::default(),
1407            transient: Vec::new(),
1408            declared: std::collections::HashMap::new(),
1409            inout: Vec::new(),
1410            exact: Vec::new(),
1411            params_tagged: Vec::new(),
1412            ret_tagged: false,
1413            absence: false,
1414            absence_regs: Vec::new(),
1415            absence_globals: Vec::new(),
1416            tower: tower::Towers::default(),
1417            stub: true,
1418        }
1419    }
1420}
1421
1422/// Only erase a range when its one definition is followed immediately by its only use,
1423/// IterPrepare. A returned/stored/read range remains an ordinary sequence.
1424fn range_loop_registers(
1425    ops: &[Op],
1426    functions: &[CompiledFunction],
1427) -> std::collections::HashMap<u16, (u16, u16)> {
1428    let mut defs = std::collections::HashMap::<u16, usize>::new();
1429    let mut uses = std::collections::HashMap::<u16, usize>::new();
1430    for op in ops {
1431        let (d, u) = crate::vm::instruction::op_def_uses(op, functions);
1432        for r in d {
1433            *defs.entry(r).or_default() += 1;
1434        }
1435        for r in u {
1436            *uses.entry(r).or_default() += 1;
1437        }
1438    }
1439    // The constructor must be the iterator entry's sole predecessor. A branch may otherwise
1440    // skip NewRange and supply a pre-existing sequence in the same register.
1441    let mut incoming = vec![0_usize; ops.len()];
1442    for (pc, op) in ops.iter().enumerate() {
1443        for next in crate::vm::instruction::op_successors(op, pc, ops.len()) {
1444            if let Some(count) = incoming.get_mut(next) {
1445                *count += 1;
1446            }
1447        }
1448    }
1449    ops.windows(2)
1450        .enumerate()
1451        .filter_map(|(pc, pair)| match (&pair[0], &pair[1]) {
1452            (Op::NewRange { dst, start, end }, Op::IterPrepare { iterable })
1453                if dst == iterable
1454                    && defs.get(dst) == Some(&1)
1455                    && uses.get(dst) == Some(&1)
1456                    && incoming[pc + 1] == 1 =>
1457            {
1458                Some((*dst, (*start, *end)))
1459            }
1460            _ => None,
1461        })
1462        .collect()
1463}
1464
1465/// How the VM's place lowering (`Compiler::compile_place_mutation`) moves one level of a place out
1466/// and back in, recognised per op position so wasm can lower it as the MOVE it is.
1467///
1468/// A mutation through `r's f` compiles to: `GetField d = r.f`, then `SetIndex r["f"] = nothing`, then
1469/// the mutation of `d`, then `SetIndex r["f"] = d`; one through `item i of c` to the same shape with
1470/// `Index d = c[i]` and `SetIndex c[i] = …`, and one of a compiler-written module-level binding with
1471/// `GlobalGet d = g` and `GlobalSet g = …`. The `nothing` write exists for the VM alone — it drops
1472/// the parent's own reference so the VM's ownership check on `d` counts only real aliases. The wasm
1473/// equivalent is not to count the extraction as an alias: the level is TAKEN (no retain, so mutating
1474/// `d` copies only when something else really holds it), the clear stores nothing (its
1475/// copy-on-write of the parent still runs, so the put-back lands in the parent's own storage), and
1476/// PUTTING it back is not a second holder either (no retain). A read not followed by its clear stays
1477/// an ordinary aliasing read.
1478#[derive(Default)]
1479struct PlaceSites {
1480    /// Per `SetIndex`: the Text constant its index register holds there — the field a record write
1481    /// names — when the block defines that register with a `LoadConst` before the write.
1482    field_at: Vec<Option<u32>>,
1483    /// Per `GetField`/`Index`: the level is taken out by the place lowering.
1484    take: Vec<bool>,
1485    /// Per `SetIndex`: the `nothing` that clears a level just taken out.
1486    clear: Vec<bool>,
1487    /// Per `SetIndex`: the value written is the level taken out earlier, put back.
1488    put_back: Vec<bool>,
1489}
1490
1491/// Where a taken level sat in its parent: a record field (by name), an item (by index register), or
1492/// a module-level binding (by global index; its "parent" is the globals store).
1493#[derive(Clone, Copy, PartialEq)]
1494enum PlaceKey {
1495    Field(u32),
1496    Item(u16),
1497    Global(u16),
1498}
1499
1500impl PlaceSites {
1501    fn of(ops: &[Op], constants: &[Constant], functions: &[CompiledFunction]) -> PlaceSites {
1502        let n = ops.len();
1503        let Some(blocks) = super::cfg::Blocks::new(ops) else {
1504            return PlaceSites::default();
1505        };
1506        // The constant `reg` holds just before `pc`: its latest definition in `pc`'s own block, when
1507        // that definition is a `LoadConst`. A definition in another block has other paths into
1508        // `pc` and answers nothing — the place lowering loads each name right beside its use.
1509        let const_at = |pc: usize, reg: u16| -> Option<u32> {
1510            let mut j = pc;
1511            while j > 0 && !blocks.is_leader(j) {
1512                j -= 1;
1513                if let Op::LoadConst { dst, idx } = ops[j] {
1514                    if dst == reg {
1515                        return Some(idx);
1516                    }
1517                    continue;
1518                }
1519                if crate::vm::instruction::op_def_uses(&ops[j], functions)
1520                    .0
1521                    .contains(&reg)
1522                {
1523                    return None;
1524                }
1525            }
1526            None
1527        };
1528        let text_const = |c: u32| matches!(constants.get(c as usize), Some(Constant::Text(_)));
1529        let is_nothing = |c: Option<u32>| {
1530            c.is_some_and(|c| matches!(constants.get(c as usize), Some(Constant::Nothing)))
1531        };
1532        let same_name = |a: u32, b: u32| matches!((constants.get(a as usize), constants.get(b as usize)), (Some(Constant::Text(x)), Some(Constant::Text(y))) if x == y);
1533        let mut field_at = vec![None; n];
1534        for (pc, op) in ops.iter().enumerate() {
1535            if let Op::SetIndex { index, .. } | Op::SetIndexUnchecked { index, .. } = *op {
1536                field_at[pc] = const_at(pc, index).filter(|&c| text_const(c));
1537            }
1538        }
1539        // Whether the op at `at` writes `(parent, key)` — a field by its name, an item by the very
1540        // index register the read used, a global by its index.
1541        let writes = |at: usize, parent: u16, key: PlaceKey| -> bool {
1542            match (ops[at], key) {
1543                (
1544                    Op::SetIndex { collection, .. } | Op::SetIndexUnchecked { collection, .. },
1545                    PlaceKey::Field(f),
1546                ) => collection == parent && field_at[at].is_some_and(|c| same_name(c, f)),
1547                (
1548                    Op::SetIndex {
1549                        collection, index, ..
1550                    }
1551                    | Op::SetIndexUnchecked {
1552                        collection, index, ..
1553                    },
1554                    PlaceKey::Item(r),
1555                ) => collection == parent && index == r,
1556                (Op::GlobalSet { idx, .. }, PlaceKey::Global(g)) => idx == g,
1557                _ => false,
1558            }
1559        };
1560        let set_value = |at: usize| match ops[at] {
1561            Op::SetIndex { value, .. } | Op::SetIndexUnchecked { value, .. } => Some(value),
1562            Op::GlobalSet { src, .. } => Some(src),
1563            _ => None,
1564        };
1565        let mut take = vec![false; n];
1566        let mut clear = vec![false; n];
1567        let mut put_back = vec![false; n];
1568        let mut taken: Vec<(u16, PlaceKey, u16)> = Vec::new();
1569        for (pc, op) in ops.iter().enumerate() {
1570            let read = match *op {
1571                Op::GetField { dst, obj, field } => Some((dst, obj, PlaceKey::Field(field))),
1572                Op::Index {
1573                    dst,
1574                    collection,
1575                    index,
1576                }
1577                | Op::IndexUnchecked {
1578                    dst,
1579                    collection,
1580                    index,
1581                } => Some((dst, collection, PlaceKey::Item(index))),
1582                Op::GlobalGet { dst, idx } => Some((dst, 0, PlaceKey::Global(idx))),
1583                _ => None,
1584            };
1585            if let Some((dst, parent, key)) = read {
1586                let next = ops[pc + 1..]
1587                    .iter()
1588                    .position(|o| !matches!(o, Op::LoadConst { .. }))
1589                    .map(|i| pc + 1 + i);
1590                if let Some(at) = next {
1591                    if writes(at, parent, key)
1592                        && is_nothing(set_value(at).and_then(|v| const_at(at, v)))
1593                    {
1594                        take[pc] = true;
1595                        clear[at] = true;
1596                        taken.push((parent, key, dst));
1597                        continue;
1598                    }
1599                }
1600                // A global read that is stored straight back — the same register, in straight-line
1601                // code, with nothing between that could read the global or run other code — is a take
1602                // with no clear: the mutation between is the global's own.
1603                if let PlaceKey::Global(g) = key {
1604                    if stored_back(ops, pc, g, dst) {
1605                        take[pc] = true;
1606                        taken.push((parent, key, dst));
1607                    }
1608                }
1609                continue;
1610            }
1611            if clear[pc] {
1612                continue;
1613            }
1614            if let Some(value) = set_value(pc) {
1615                let back = taken
1616                    .iter()
1617                    .position(|&(parent, key, d)| d == value && writes(pc, parent, key));
1618                if let Some(i) = back {
1619                    put_back[pc] = true;
1620                    taken.remove(i);
1621                }
1622            }
1623        }
1624        PlaceSites {
1625            field_at,
1626            take,
1627            clear,
1628            put_back,
1629        }
1630    }
1631}
1632
1633/// Per register, the declared type of what it holds: each parameter's, then each declaration the region
1634/// seeded, then whatever the layout pass carried to a register the first two leave unknown.
1635fn declared_registers(
1636    structs: &kind::StructLayout,
1637    seeded: Vec<(usize, u16, BoundaryType)>,
1638    param_types: &[Option<BoundaryType>],
1639) -> std::collections::HashMap<u16, BoundaryType> {
1640    let mut declared: std::collections::HashMap<u16, BoundaryType> = param_types
1641        .iter()
1642        .enumerate()
1643        .filter_map(|(i, t)| t.clone().map(|t| (i as u16, t)))
1644        .collect();
1645    for (_, reg, bt) in seeded {
1646        declared.entry(reg).or_insert(bt);
1647    }
1648    for (reg, bt) in &structs.reg_declared {
1649        declared.entry(*reg).or_insert_with(|| bt.clone());
1650    }
1651    declared
1652}
1653
1654/// Per register: whether every read of it is TRANSIENT — it only looks at the value in place, and
1655/// nothing can have changed a heap value between the register's definition and the read.
1656///
1657/// A read that takes a handle out of a global, a field or an item RETAINS it (word 12), so a later
1658/// mutation through either holder copies first — that is value semantics for a handle that may be
1659/// mutated or kept. A register that is only read — indexed, measured, compared, shown, handed to a
1660/// call (which retains what it passes) — within the block that defined it, with no op in between that
1661/// can change a heap value, is neither mutated nor kept: retaining it would only make the next
1662/// mutation of the source copy the whole value, which is what made reading a global list and then
1663/// writing it cost a copy of the list every time.
1664///
1665/// The reads are enumerated per op ([`pure_read_operands`]); any other use of a register — a move, a
1666/// store, an iteration, a return, a mutation — makes it non-transient. A register read in a block
1667/// other than the one that last defined it is non-transient too.
1668fn transient_reads(ops: &[Op], num_regs: u32, functions: &[CompiledFunction]) -> Vec<bool> {
1669    let mut transient = vec![true; num_regs as usize];
1670    let Some(blocks) = super::cfg::Blocks::new(ops) else {
1671        return vec![false; num_regs as usize];
1672    };
1673    // Registers defined in the current block since its start and since the last op that can change a
1674    // heap value.
1675    let mut clean: std::collections::HashSet<crate::vm::instruction::Reg> =
1676        std::collections::HashSet::new();
1677    for (pc, op) in ops.iter().enumerate() {
1678        if blocks.is_leader(pc) {
1679            clean.clear();
1680        }
1681        let (defs, uses) = crate::vm::instruction::op_def_uses(op, functions);
1682        let pure = pure_read_operands(op, functions);
1683        for r in uses {
1684            if !pure.contains(&r) || !clean.contains(&r) {
1685                if let Some(t) = transient.get_mut(r as usize) {
1686                    *t = false;
1687                }
1688            }
1689        }
1690        if !leaves_the_heap_alone(op) {
1691            clean.clear();
1692        }
1693        for r in defs {
1694            clean.insert(r);
1695        }
1696    }
1697    transient
1698}
1699
1700/// The operands `op` only READS in place, keeping nothing: the registers [`transient_reads`] can
1701/// count a transient use. A call's arguments are here because the call retains every argument it
1702/// passes, and so are a host import's — the host takes them by value — except each one its row says
1703/// the host KEEPS past the call ([`HostFn::retained_params`]: a closure it re-enters, a handle it
1704/// stores). Anything that stores, moves, iterates, returns or mutates a register is not.
1705fn pure_read_operands(op: &Op, functions: &[CompiledFunction]) -> Vec<crate::vm::instruction::Reg> {
1706    match *op {
1707        Op::CallBuiltin {
1708            builtin,
1709            args_start,
1710            arg_count,
1711            ..
1712        } => match dom_import_of(builtin) {
1713            Some(host) => {
1714                let kept = host.retained_params();
1715                (0..arg_count)
1716                    .filter(|i| !kept.contains(&usize::from(*i)))
1717                    .map(|i| args_start + i)
1718                    .collect()
1719            }
1720            None => Vec::new(),
1721        },
1722        Op::Index {
1723            collection, index, ..
1724        }
1725        | Op::IndexUnchecked {
1726            collection, index, ..
1727        } => vec![collection, index],
1728        Op::Length { collection, .. } => vec![collection],
1729        Op::Contains {
1730            collection, value, ..
1731        } => vec![collection, value],
1732        Op::GetField { obj, .. } => vec![obj],
1733        Op::Show { src }
1734        | Op::Not { src, .. }
1735        | Op::FormatValue { src, .. }
1736        | Op::DeepClone { src, .. } => vec![src],
1737        Op::JumpIfFalse { cond, .. } | Op::JumpIfTrue { cond, .. } => vec![cond],
1738        Op::SliceOp {
1739            collection,
1740            start,
1741            end,
1742            ..
1743        } => vec![collection, start, end],
1744        Op::Add { lhs, rhs, .. }
1745        | Op::Sub { lhs, rhs, .. }
1746        | Op::Mul { lhs, rhs, .. }
1747        | Op::Div { lhs, rhs, .. }
1748        | Op::ExactDiv { lhs, rhs, .. }
1749        | Op::FloorDiv { lhs, rhs, .. }
1750        | Op::Mod { lhs, rhs, .. }
1751        | Op::Pow { lhs, rhs, .. }
1752        | Op::Lt { lhs, rhs, .. }
1753        | Op::Gt { lhs, rhs, .. }
1754        | Op::LtEq { lhs, rhs, .. }
1755        | Op::GtEq { lhs, rhs, .. }
1756        | Op::Eq { lhs, rhs, .. }
1757        | Op::NotEq { lhs, rhs, .. }
1758        | Op::ApproxEq { lhs, rhs, .. }
1759        | Op::Concat { lhs, rhs, .. }
1760        | Op::SeqConcat { lhs, rhs, .. }
1761        | Op::UnionOp { lhs, rhs, .. }
1762        | Op::IntersectOp { lhs, rhs, .. } => vec![lhs, rhs],
1763        Op::Call { .. } => crate::vm::instruction::op_def_uses(op, functions).1,
1764        _ => Vec::new(),
1765    }
1766}
1767
1768/// Whether `op` cannot change any heap value in place — the ops a transient read may sit across.
1769fn leaves_the_heap_alone(op: &Op) -> bool {
1770    matches!(
1771        op,
1772        Op::LoadConst { .. }
1773            | Op::Move { .. }
1774            | Op::Add { .. }
1775            | Op::Sub { .. }
1776            | Op::Mul { .. }
1777            | Op::Div { .. }
1778            | Op::ExactDiv { .. }
1779            | Op::FloorDiv { .. }
1780            | Op::Mod { .. }
1781            | Op::Pow { .. }
1782            | Op::DivPow2 { .. }
1783            | Op::MagicDivU { .. }
1784            | Op::Lt { .. }
1785            | Op::Gt { .. }
1786            | Op::LtEq { .. }
1787            | Op::GtEq { .. }
1788            | Op::Eq { .. }
1789            | Op::NotEq { .. }
1790            | Op::ApproxEq { .. }
1791            | Op::Not { .. }
1792            | Op::Concat { .. }
1793            | Op::SeqConcat { .. }
1794            | Op::BitXor { .. }
1795            | Op::BitAnd { .. }
1796            | Op::BitOr { .. }
1797            | Op::Shl { .. }
1798            | Op::Shr { .. }
1799            | Op::Index { .. }
1800            | Op::IndexUnchecked { .. }
1801            | Op::Length { .. }
1802            | Op::Contains { .. }
1803            | Op::GetField { .. }
1804            | Op::GlobalGet { .. }
1805            | Op::FormatValue { .. }
1806            | Op::SliceOp { .. }
1807            | Op::DeepClone { .. }
1808            | Op::UnionOp { .. }
1809            | Op::IntersectOp { .. }
1810            | Op::NewList { .. }
1811            | Op::NewEmptyList { .. }
1812            | Op::NewEmptyListWithCapacity { .. }
1813            | Op::NewEmptyListI32 { .. }
1814            | Op::NewEmptyListFixed { .. }
1815            | Op::NewEmptySet { .. }
1816            | Op::NewEmptyMap { .. }
1817            | Op::NewEmptyMapWithCapacity { .. }
1818            | Op::NewRange { .. }
1819            | Op::NewTuple { .. }
1820            | Op::NewStruct { .. }
1821            | Op::NewInductive { .. }
1822            | Op::TestArm { .. }
1823            | Op::BindArm { .. }
1824            | Op::Show { .. }
1825            | Op::LoadToday { .. }
1826            | Op::LoadNow { .. }
1827            | Op::Jump { .. }
1828            | Op::JumpIfFalse { .. }
1829            | Op::JumpIfTrue { .. }
1830    )
1831}
1832
1833/// Whether the value `GlobalGet dst = g` at `pc` read is stored back into `g` from `dst` before anything
1834/// reads `g` again or control leaves straight-line code.
1835fn stored_back(ops: &[Op], pc: usize, g: u16, dst: u16) -> bool {
1836    for op in &ops[pc + 1..] {
1837        match *op {
1838            Op::GlobalSet { idx, src } if idx == g && src == dst => return true,
1839            Op::GlobalGet { idx, .. } if idx == g => return false,
1840            Op::Call { .. }
1841            | Op::CallValue { .. }
1842            | Op::CallBuiltin { .. }
1843            | Op::Jump { .. }
1844            | Op::JumpIfFalse { .. }
1845            | Op::JumpIfTrue { .. }
1846            | Op::IterNext { .. }
1847            | Op::Return { .. }
1848            | Op::ReturnNothing
1849            | Op::Halt => return false,
1850            _ => {}
1851        }
1852    }
1853    false
1854}
1855
1856/// The slot of `field` (a field-name constant index) in the record held by `obj` — its declared layout
1857/// wherever the record's type is known, else the local layout of a record built here without one.
1858fn record_field_slot(plan: &Plan, obj: u16, field: u32) -> Option<usize> {
1859    if let Some(ParamShape::Struct(layout)) = plan.reg_shape.get(&obj) {
1860        return layout.iter().position(|(f, _, _)| *f == field);
1861    }
1862    plan.structs
1863        .reg_layout
1864        .get(&obj)?
1865        .iter()
1866        .position(|(f, _)| *f == field)
1867}
1868
1869/// Infer register kinds with reachability-DCE: walk the CFG to find the reachable
1870/// blocks, then run the strict kind inference over reachable ops only (so a dead
1871/// branch's writes never poison a register). Returns the kinds plus the per-block
1872/// reachability the emitter uses.
1873fn infer_with_reachability(
1874    ops: &[Op],
1875    constants: &[Constant],
1876    struct_types: &[StructTypeDef],
1877    enum_types: &[EnumTypeDef],
1878    fn_return_types: &[Option<BoundaryType>],
1879    num_regs: usize,
1880    seeds: &[Option<Kind>],
1881    ret_of: &dyn Fn(usize) -> Option<Kind>,
1882    global_of: &dyn Fn(u16) -> Option<Kind>,
1883    closure_ret: &dyn Fn(usize) -> Option<Kind>,
1884    ret_layout: &dyn Fn(u16) -> Option<FieldLayout>,
1885    fn_return_closure: &dyn Fn(u16) -> Option<u16>,
1886    param_layouts: &[(u16, ParamShape)],
1887    param_closures: &[(u16, u16)],
1888    global_layout: &dyn Fn(u16) -> Option<FieldLayout>,
1889    global_declared: &dyn Fn(u16) -> Option<BoundaryType>,
1890    linked: bool,
1891    functions: &[crate::vm::instruction::CompiledFunction],
1892    inout: &[u16],
1893) -> R<(KindTable, Vec<bool>, Vec<bool>)> {
1894    let blocks = Blocks::new(ops).ok_or(WasmLowerError::Unsupported(
1895        "jump target escapes the function",
1896    ))?;
1897    let (pc_reach, block_reach) = reachability(ops, &blocks);
1898    // The general Int-overflow→BigInt promotion set (empty unless linked): registers only observed or
1899    // fed into more BigInt arithmetic, computed once over this region's post-regsplit ops.
1900    let bigint_demand = kind::bigint_demanded_regs(ops, functions, linked);
1901    // A loan clears the caller's slot, then restores it before any read. Keep
1902    // the clear in emitted code (including for heap roots), but do not unify
1903    // an unobserved absence with the slot's payload type.
1904    let dead_clears = regsplit::unobserved_nothing_writes(ops, constants, functions, inout);
1905    let kind_reach: Vec<_> = pc_reach
1906        .iter()
1907        .enumerate()
1908        .map(|(pc, &reachable)| reachable && !dead_clears.contains(&pc))
1909        .collect();
1910    let kinds = kind::infer(
1911        ops,
1912        constants,
1913        struct_types,
1914        enum_types,
1915        fn_return_types,
1916        num_regs,
1917        seeds,
1918        ret_of,
1919        global_of,
1920        closure_ret,
1921        ret_layout,
1922        fn_return_closure,
1923        param_layouts,
1924        param_closures,
1925        global_layout,
1926        global_declared,
1927        &kind_reach,
1928        linked,
1929        &bigint_demand,
1930    )?;
1931    Ok((kinds, pc_reach, block_reach))
1932}
1933
1934/// Compute reachability from the entry block. Returns `(per-pc reachable,
1935/// per-block reachable)`.
1936fn reachability(ops: &[Op], blocks: &Blocks) -> (Vec<bool>, Vec<bool>) {
1937    let nb = blocks.num_blocks();
1938    let mut block_reach = vec![false; nb];
1939    let mut stack = vec![0usize];
1940    while let Some(k) = stack.pop() {
1941        if block_reach[k] {
1942            continue;
1943        }
1944        block_reach[k] = true;
1945        for s in block_successors(ops, blocks, k) {
1946            if !block_reach[s] {
1947                stack.push(s);
1948            }
1949        }
1950    }
1951    let mut pc_reach = vec![false; ops.len()];
1952    for (k, &live) in block_reach.iter().enumerate() {
1953        if live {
1954            for pc in blocks.start(k)..blocks.end(k) {
1955                pc_reach[pc] = true;
1956            }
1957        }
1958    }
1959    (pc_reach, block_reach)
1960}
1961
1962/// The successor blocks of block `k`.
1963fn block_successors(ops: &[Op], blocks: &Blocks, k: usize) -> Vec<usize> {
1964    let n = ops.len();
1965    let fallthrough = |pc: usize| -> Vec<usize> {
1966        if pc + 1 < n {
1967            vec![blocks.block_of(pc + 1)]
1968        } else {
1969            vec![]
1970        }
1971    };
1972    for pc in blocks.start(k)..blocks.end(k) {
1973        match ops[pc] {
1974            Op::Jump { target } => return vec![blocks.block_of(target)],
1975            Op::JumpIfFalse { target, .. } | Op::JumpIfTrue { target, .. } => {
1976                let mut s = vec![blocks.block_of(target)];
1977                s.extend(fallthrough(pc));
1978                return s;
1979            }
1980            // `IterNext` branches to `exit` (the matching `IterPop`) when the snapshot is
1981            // exhausted, else falls through to the loop body — both blocks are reachable.
1982            Op::IterNext { exit, .. } => {
1983                let mut s = vec![blocks.block_of(exit)];
1984                s.extend(fallthrough(pc));
1985                return s;
1986            }
1987            Op::Return { .. }
1988            | Op::ReturnNothing
1989            | Op::Halt
1990            | Op::FailWith { .. }
1991            | Op::CallBuiltin {
1992                builtin:
1993                    BuiltinId::Fail
1994                    | BuiltinId::FailReason
1995                    | BuiltinId::VfsMount
1996                    | BuiltinId::VfsWriteFile,
1997                ..
1998            } => return vec![],
1999            _ => {}
2000        }
2001    }
2002    // Fell through the block end with no terminator.
2003    if blocks.end(k) < n {
2004        vec![blocks.block_of(blocks.end(k))]
2005    } else {
2006        vec![]
2007    }
2008}
2009
2010/// The failure a browser page reports for `Mount … at …` and `Write … to file …`: the file system
2011/// those statements read and write is the compiled tiers', and a page has none.
2012pub const VFS_IN_THE_BROWSER: &str =
2013    "a page in the browser has no file system: mounting a journal and writing a file run on the compiled tiers";
2014
2015/// Lower a whole program to a self-contained WebAssembly module (the bytes of a `.wasm` file).
2016/// Returns [`WasmLowerError::Unsupported`] for any program outside the scalar fragment — a
2017/// sound refusal, never a wrong module.
2018pub fn assemble_program(
2019    program: &CompiledProgram,
2020    policies: &PolicyRegistry,
2021    interner: &Interner,
2022) -> R<Vec<u8>> {
2023    assemble_program_impl(
2024        program,
2025        policies,
2026        interner,
2027        false,
2028        Reclaim::Counted,
2029        &HostEntries::default(),
2030    )
2031}
2032
2033/// [`assemble_program`] for a host that also enters the module by name beyond `main` — each
2034/// component in `entries` stays in the module (reached from its mount as `main` reaches the page's
2035/// own) and its `__mount_<C>` is exported under that name. With the default entries this IS
2036/// [`assemble_program`].
2037pub fn assemble_program_with(
2038    program: &CompiledProgram,
2039    policies: &PolicyRegistry,
2040    interner: &Interner,
2041    entries: &HostEntries,
2042) -> R<Vec<u8>> {
2043    assemble_program_impl(
2044        program,
2045        policies,
2046        interner,
2047        false,
2048        Reclaim::Counted,
2049        entries,
2050    )
2051}
2052
2053/// [`assemble_program_with`] as a check-mode module (`Reclaim::Checked`): the same module with the
2054/// heap census exported (`__logos_heap_census`), which a heap test reads every true count back
2055/// through. A shipped page never carries it.
2056pub fn assemble_program_checked(
2057    program: &CompiledProgram,
2058    policies: &PolicyRegistry,
2059    interner: &Interner,
2060    entries: &HostEntries,
2061) -> R<Vec<u8>> {
2062    assemble_program_impl(
2063        program,
2064        policies,
2065        interner,
2066        false,
2067        Reclaim::Checked,
2068        entries,
2069    )
2070}
2071
2072/// Reclamation for standalone modules. Pages collect at the end of a host turn; batch
2073/// programs pin live caller registers and collect at loop backedges and main's exit.
2074#[derive(Clone, Copy, PartialEq, Eq, Debug)]
2075enum Reclaim {
2076    /// Blocks are reused only where their death is structural — a grown buffer's old one.
2077    Off,
2078    /// True holder counts, the turn's retained list, and the safepoint that frees what nothing holds
2079    /// once the host's turn ends.
2080    Counted,
2081    /// [`Reclaim::Counted`] plus `__logos_heap_census`, the check-mode instrument that recomputes
2082    /// every count from the program's roots.
2083    Checked,
2084}
2085
2086/// Linker-mode assembly: an integer `Op::Pow` lowers to the real `logicaffeine_base::BigInt` runtime
2087/// (`logos_rt_bigint_from_i64`→`_pow`→`_to_text`) yielding a `Text` handle, so an overflowing
2088/// `x to the power of y` computes the exact big integer the VM's BigInt promotion prints instead of
2089/// trapping. The module imports `env.__linear_memory` (the linker supplies one shared memory) and the
2090/// three `logos_rt_bigint_*` functions by undefined symbol; [`super::reloc::module_to_relocatable`] +
2091/// `rust-lld` link it against the prebuilt base runtime. Emitter-side heap allocation is refused (two
2092/// allocators over one linear memory would corrupt it — the only heap value is the runtime-built Text).
2093pub(crate) fn assemble_program_linked(
2094    program: &CompiledProgram,
2095    policies: &PolicyRegistry,
2096    interner: &Interner,
2097) -> R<Vec<u8>> {
2098    assemble_program_impl(
2099        program,
2100        policies,
2101        interner,
2102        true,
2103        Reclaim::Off,
2104        &HostEntries::default(),
2105    )
2106}
2107
2108/// A refusal that names where it happened: the function whose planning or lowering stopped (`Main`
2109/// for the program's own top level). The backend's own words say what it could not do; the name is
2110/// what a reader can go and look at.
2111fn within_function(
2112    e: WasmLowerError,
2113    program: &CompiledProgram,
2114    interner: &Interner,
2115    fi: Option<usize>,
2116) -> WasmLowerError {
2117    let name = match fi {
2118        None => "Main".to_string(),
2119        Some(fi) => match program.functions.get(fi).map(|f| interner.resolve(f.name)) {
2120            Some(name) if !name.is_empty() => format!("`{name}`"),
2121            _ => format!("function #{fi}"),
2122        },
2123    };
2124    let what = match e {
2125        WasmLowerError::Unsupported(what) => what.to_string(),
2126        WasmLowerError::UnsupportedOwned(what) => what,
2127    };
2128    WasmLowerError::UnsupportedOwned(format!("{what} (in {name})"))
2129}
2130
2131fn assemble_program_impl(
2132    program: &CompiledProgram,
2133    policies: &PolicyRegistry,
2134    interner: &Interner,
2135    linked: bool,
2136    reclaim: Reclaim,
2137    entries: &HostEntries,
2138) -> R<Vec<u8>> {
2139    if !linked && crate::vm::tower::reaches(program) {
2140        return Err(WasmLowerError::UnsupportedOwned(tower::REFUSAL.to_string()));
2141    }
2142    // ---- 1. Plan Main + every user function (rebase, infer kinds, resolve result kind) ----
2143    let layout = crate::vm::reach::code_layout(program).map_err(WasmLowerError::Unsupported)?;
2144    let ret_of = |fi: usize| -> Option<Kind> { declared_result(program, fi) };
2145    let no_closure = |_: usize| -> Option<Kind> { None };
2146    let no_ret_layout = |_: u16| -> Option<FieldLayout> { None };
2147    let no_ret_closure = |_: u16| -> Option<u16> { None };
2148    let no_param_origin = |_: usize, _: usize| -> Option<u16> { None };
2149    let no_exact_param = |_: usize, _: usize| false;
2150
2151    // Plan Main once with no resolvers — it types both the values stored into globals (read below)
2152    // AND the local registers a `MakeClosure` captures (the cross-scope closure-capture flow below).
2153    let num_globals = program.globals.len();
2154    let no_globals = |_: u16| None;
2155    let no_global_layout = |_: u16| -> Option<FieldLayout> { None };
2156    // The bootstrap pass runs BEFORE global types are known, so it answers "nothing known" for a
2157    // global map exactly as it does for a global record — the strict pass below is where the real
2158    // answers arrive.
2159    let no_global_declared = |_: u16| -> Option<BoundaryType> { None };
2160    let no_caps: Vec<Vec<Option<Kind>>> = Vec::new();
2161    let main_p1 = plan_main(
2162        program,
2163        &layout,
2164        &ret_of,
2165        &no_globals,
2166        &no_closure,
2167        &no_ret_layout,
2168        &no_ret_closure,
2169        &no_global_layout,
2170        &no_global_declared,
2171        linked,
2172    )?;
2173    // ★ A GLOBAL'S KIND IS ITS DECLARATION'S, where it has one. What Main stored says only what the
2174    // value looked like when it went in, and `a new Seq of Text` goes in EMPTY: Main never pushes to
2175    // a page's outbox or a store's list, so its kind there is an element-less sequence, and every
2176    // function reading it — the only place anything is ever read out — was refused ("Show of an
2177    // unknown-kind value") for a list whose element type is written in the declaration. The
2178    // inferred kind stays the answer for a global with no declaration, and wins a disagreement in
2179    // width (a value can only be stored at the width it has).
2180    let global_kinds_cell: std::cell::RefCell<Vec<Option<Kind>>> = std::cell::RefCell::new({
2181        let mut gk = vec![None; num_globals];
2182        for (pc, op) in main_p1.ops.iter().enumerate() {
2183            // Taking and returning a mutable loan do not redeclare the global's payload.
2184            // The first planning pass has not resolved GlobalGet yet, so a put-back's
2185            // temporary register can still have the fallback integer kind.
2186            if main_p1.place.clear[pc] || main_p1.place.put_back[pc] {
2187                continue;
2188            }
2189            if let Op::GlobalSet { idx, src } = *op {
2190                if let Some(k) = main_p1.kinds.get(src as usize) {
2191                    if k != Kind::Nothing {
2192                        gk[idx as usize] = Some(k);
2193                    }
2194                }
2195            }
2196        }
2197        for (idx, k) in gk.iter_mut().enumerate() {
2198            let declared = program
2199                .global_types
2200                .get(idx)
2201                .and_then(|t| t.as_ref())
2202                .and_then(kind::boundary_to_kind);
2203            if let Some(d) = declared {
2204                if k.map_or(true, |k| k.wasm_valtype() == d.wasm_valtype()) {
2205                    *k = Some(d);
2206                }
2207            }
2208        }
2209        gk
2210    });
2211    let global_of =
2212        |idx: u16| -> Option<Kind> { global_kinds_cell.borrow().get(idx as usize).copied().flatten() };
2213    // ★ Per global, the RESOLVED FIELD LAYOUT of the record it holds — the global analog of a
2214    // struct parameter's `ParamShape::Struct`, and the thing that lets a FUNCTION read a
2215    // module-level record's field. Main builds the record, so its declared type is known there;
2216    // a function that only reads the global has no value register for the fields and, without
2217    // this, resolved no static slot at all ("field access with no static slot"). That refusal
2218    // took out every `## Store` on this tier — a store IS a record global, read by every action.
2219    let global_layouts: Vec<Option<FieldLayout>> = {
2220        let mut gl = vec![None; num_globals];
2221        for op in &main_p1.ops {
2222            if let Op::GlobalSet { idx, src } = *op {
2223                if main_p1.kinds.get(src as usize) == Some(Kind::Struct) {
2224                    gl[idx as usize] = global_struct_layout(
2225                        &main_p1,
2226                        src,
2227                        &program.struct_types,
2228                        &program.constants,
2229                    );
2230                }
2231            }
2232        }
2233        gl
2234    };
2235    let global_layout_of =
2236        |idx: u16| -> Option<FieldLayout> { global_layouts.get(idx as usize).cloned().flatten() };
2237    // ★ AND THE GENERAL ANALOG: the global's DECLARED TYPE, handed over whole.
2238    //
2239    // A function that only READS a global has no construction to trace, so every layout it needs
2240    // must come from the declaration — the same position a struct parameter is in, answered the
2241    // same way. This used to be THREE resolvers, each flattening the declared type into one
2242    // pre-chewed answer: the element layout of a `Seq of <record>`, the value kind and layout of a
2243    // `Map of K to <record>`, and finally the element layout of a `Map of K to (Seq of <record>)`.
2244    //
2245    // ★ Each was added after a real program was refused, and each left the next nesting broken. The
2246    // last one existed because per-instance component state wraps every field in a map, so a page's
2247    // `Seq of Memo` arrives here as `Map of Text to (Seq of Memo)` — and a list of lists, a map of
2248    // maps and a list of maps were all still refused with "field access with no static slot" after
2249    // it landed. A type is a TREE; three flattenings of it are three chances to have missed a
2250    // branch. Passing the tree costs a clone per index and cannot miss one.
2251    let global_declared_of = |idx: u16| -> Option<BoundaryType> {
2252        program.global_types.get(idx as usize).cloned().flatten()
2253    };
2254    // Per global, the body function index of the CLOSURE it holds (a Main `Let f be (…) -> …` used in a
2255    // function/closure is promoted to a global), so a closure capturing such a global resolves the call
2256    // to the captured closure — the global analog of the local captured-closure trace.
2257    let global_closures: Vec<Option<u16>> = {
2258        let mut gc = vec![None; num_globals];
2259        for op in &main_p1.ops {
2260            if let Op::GlobalSet { idx, src } = *op {
2261                if let Some(&c) = main_p1.structs.closure_of.get(&src) {
2262                    gc[idx as usize] = Some(c);
2263                }
2264            }
2265        }
2266        gc
2267    };
2268    let global_closure_of =
2269        |idx: u16| -> Option<u16> { global_closures.get(idx as usize).copied().flatten() };
2270
2271    // CROSS-SCOPE + NESTED CLOSURE PLANNING — a FIXPOINT. A closure's capture kinds come from where it
2272    // is BUILT (its `MakeClosure`); its result kind flows UP to callers. A NESTED closure (built inside
2273    // another closure body) crosses BOTH directions over more levels than the old 2-pass could resolve
2274    // (the inner's captures need the outer planned; the outer's result needs the inner planned). So:
2275    // plan the non-closure functions (no captures → clean), then ITERATE — extract capture kinds/shapes
2276    // from EVERY currently-planned region (so a closure built inside an already-planned closure body
2277    // gets its captures) and re-plan every function with the latest captures + inferred call-result
2278    // kinds, TOLERATING a closure whose captures aren't resolvable yet (`.ok()`; it succeeds a later
2279    // round once its build-region is planned). Converges in O(nesting depth) rounds; the final STRICT
2280    // pass below is the backstop that rejects a genuinely-unsupported function.
2281    let no_shapes: Vec<Vec<Option<ParamShape>>> = Vec::new();
2282    let no_capture_closures: Vec<Vec<Option<u16>>> = Vec::new();
2283    let mut plans: Vec<Option<Plan>> = (0..program.functions.len()).map(|_| None).collect();
2284    for fi in 0..program.functions.len() {
2285        if !layout.is_closure[fi] {
2286            // ★ THE WARM-UP TOLERATES A FAILURE, which is what this pass's own note says it does
2287            // and what the strict pass below exists to be the backstop for. It propagated instead,
2288            // and the difference is not academic: this round passes `no_global_layout` for BOTH
2289            // global shapes, so a function reading a composite GLOBAL — which is every component's
2290            // render function, since `State:` lives in module bindings — cannot resolve it HERE and
2291            // resolves it perfectly THERE. A page was therefore refused by the pass that is not
2292            // allowed to refuse anything, with a message about register kinds that the strict pass
2293            // would never have produced.
2294            plans[fi] = plan_function(
2295                program,
2296                fi,
2297                &layout,
2298                &ret_of,
2299                &global_of,
2300                &no_closure,
2301                &no_ret_layout,
2302                &no_ret_closure,
2303                &no_global_layout,
2304                &no_global_declared,
2305                &no_param_origin,
2306                &no_exact_param,
2307                &no_caps,
2308                &no_shapes,
2309                &no_capture_closures,
2310                false,
2311                linked,
2312            )
2313            .ok();
2314        }
2315    }
2316    let mut capture_kinds: Vec<Vec<Option<Kind>>> = Vec::new();
2317    let mut capture_shapes: Vec<Vec<Option<ParamShape>>> = Vec::new();
2318    let mut capture_closures: Vec<Vec<Option<u16>>> = Vec::new();
2319    let mut exact_args: Vec<Vec<bool>> = program
2320        .functions
2321        .iter()
2322        .map(|f| vec![false; f.param_count as usize])
2323        .collect();
2324    for _ in 0..(program.functions.len() + 4) {
2325        let (ck, cs, cc) =
2326            extract_capture_kinds(program, &main_p1, &plans, &global_of, &global_closure_of);
2327        capture_kinds = ck;
2328        capture_shapes = cs;
2329        capture_closures = cc;
2330        let cur_results: Vec<Option<Kind>> = plans
2331            .iter()
2332            .map(|p| p.as_ref().and_then(|p| p.result))
2333            .collect();
2334        let cur_layouts: Vec<Option<FieldLayout>> = plans
2335            .iter()
2336            .map(|p| {
2337                p.as_ref().and_then(|p| {
2338                    fn_return_struct_layout(p, &program.struct_types, &program.constants)
2339                })
2340            })
2341            .collect();
2342        let cur_ret_closures: Vec<Option<u16>> = plans
2343            .iter()
2344            .map(|p| p.as_ref().and_then(|p| p.return_closure))
2345            .collect();
2346        let closure_ret = |fi: usize| cur_results.get(fi).copied().flatten();
2347        let ret_of_i = |fi: usize| {
2348            cur_results
2349                .get(fi)
2350                .copied()
2351                .flatten()
2352                .or_else(|| declared_result(program, fi))
2353        };
2354        let ret_layout_of = |func: u16| cur_layouts.get(func as usize).cloned().flatten();
2355        let ret_closure_of = |func: u16| cur_ret_closures.get(func as usize).copied().flatten();
2356        // CLOSURES AS ARGUMENTS. Re-plan Main with this round's resolvers so its `closure_of` reflects
2357        // a returned closure bound to a local (then passed straight into a function); attribute every
2358        // call's closure arguments to the parameters they feed, so `f(args)` resolves when `f` is a
2359        // parameter. Recomputed each round — a param's origin can resolve transitively as callers plan.
2360        let main_iter = plan_main(
2361            program,
2362            &layout,
2363            &ret_of_i,
2364            &global_of,
2365            &closure_ret,
2366            &ret_layout_of,
2367            &ret_closure_of,
2368            &global_layout_of,
2369            &global_declared_of,
2370            linked,
2371        )
2372        .ok();
2373        let mut scan_plans: Vec<&Plan> = vec![main_iter.as_ref().unwrap_or(&main_p1)];
2374        scan_plans.extend(plans.iter().flatten());
2375        let param_origins = compute_param_origins(program, &scan_plans);
2376        let param_origin = |fi: usize, pi: usize| {
2377            param_origins
2378                .get(fi)
2379                .and_then(|v| v.get(pi))
2380                .copied()
2381                .flatten()
2382        };
2383        let mut progress = exact_arguments(program, &scan_plans, &mut exact_args);
2384        let exact_param = |fi: usize, pi: usize| exact_args.get(fi).and_then(|v| v.get(pi)).copied().unwrap_or(false);
2385        for fi in 0..program.functions.len() {
2386            if let Ok(p) = plan_function(
2387                program,
2388                fi,
2389                &layout,
2390                &ret_of_i,
2391                &global_of,
2392                &closure_ret,
2393                &ret_layout_of,
2394                &ret_closure_of,
2395                &global_layout_of,
2396                &global_declared_of,
2397                &param_origin,
2398                &exact_param,
2399                &capture_kinds,
2400                &capture_shapes,
2401                &capture_closures,
2402                false,
2403                linked,
2404            ) {
2405                let changed = plans[fi].as_ref().map_or(true, |x| {
2406                    x.result != p.result || x.return_closure != p.return_closure
2407                });
2408                if changed {
2409                    progress = true;
2410                }
2411                plans[fi] = Some(p);
2412            }
2413        }
2414        // A global any region stores a value of the exact extension into holds one: every region is planned
2415        // again reading it as one, and a value of another kind stored into it lands converted.
2416        if linked {
2417            let regions = main_iter.iter().chain(plans.iter().flatten());
2418            progress |= tower::exact_globals(regions, &mut global_kinds_cell.borrow_mut());
2419        }
2420        if !progress {
2421            break;
2422        }
2423    }
2424    // ★ A FUNCTION THE WARM-UP COULD NOT PLAN IS NOT AN ERROR HERE. This round deliberately runs
2425    // WITHOUT the global layouts and capture shapes, so a function that needs them resolves only in
2426    // the strict pass below — which re-plans every function anyway and is the one allowed to refuse.
2427    // A stub contributes no result kind and no return layout, which is exactly "not known yet"; its
2428    // callers simply resolve less in this round and re-resolve in the next.
2429    let fns1: Vec<Plan> = plans
2430        .into_iter()
2431        .map(|p| p.unwrap_or_else(Plan::stub))
2432        .collect();
2433
2434    // Pass 2 (STRICT) re-plans every function WITH the resolvers (a call's inferred result kind +
2435    // struct-return field layout), so cross-region `f(…)'s field` resolves and a genuinely unknown
2436    // return is rejected rather than deferred. `capture_kinds` carries through so closure bodies keep
2437    // their capture typing. Resolvers affect only `GetField`, so pass-1 results/layouts stay valid.
2438    let fn_results_p1: Vec<Option<Kind>> = fns1.iter().map(|p| p.result).collect();
2439    let ret_layouts: Vec<Option<FieldLayout>> = fns1
2440        .iter()
2441        .map(|p| fn_return_struct_layout(p, &program.struct_types, &program.constants))
2442        .collect();
2443    let ret_closures: Vec<Option<u16>> = fns1.iter().map(|p| p.return_closure).collect();
2444    let closure_ret = |fi: usize| -> Option<Kind> { fn_results_p1.get(fi).copied().flatten() };
2445    let ret_of_inferred = |fi: usize| -> Option<Kind> {
2446        fn_results_p1
2447            .get(fi)
2448            .copied()
2449            .flatten()
2450            .or_else(|| declared_result(program, fi))
2451    };
2452    let ret_layout_of =
2453        |func: u16| -> Option<FieldLayout> { ret_layouts.get(func as usize).cloned().flatten() };
2454    let ret_closure_of =
2455        |func: u16| -> Option<u16> { ret_closures.get(func as usize).copied().flatten() };
2456    // Main is planned first (it doesn't depend on the strict `fns`, only on the converged resolvers)
2457    // so it can join the param-origin scan — a closure argument is frequently passed from Main.
2458    let mut main = plan_main(
2459        program,
2460        &layout,
2461        &ret_of_inferred,
2462        &global_of,
2463        &closure_ret,
2464        &ret_layout_of,
2465        &ret_closure_of,
2466        &global_layout_of,
2467        &global_declared_of,
2468        linked,
2469    )
2470    .map_err(|e| within_function(e, program, interner, None))?;
2471    let scan_plans: Vec<&Plan> = std::iter::once(&main).chain(fns1.iter()).collect();
2472    let param_origins = compute_param_origins(program, &scan_plans);
2473    let param_origin = |fi: usize, pi: usize| {
2474        param_origins
2475            .get(fi)
2476            .and_then(|v| v.get(pi))
2477            .copied()
2478            .flatten()
2479    };
2480    exact_arguments(program, &scan_plans, &mut exact_args);
2481    let exact_param = |fi: usize, pi: usize| exact_args.get(fi).and_then(|v| v.get(pi)).copied().unwrap_or(false);
2482    // Function-level DCE: a function that cannot run (see `vm::reach`, the analysis the
2483    // unlinkable-code gate also judges by) is dropped to a trap stub instead of being strictly
2484    // planned, so a program can demand a large stdlib module whose unused functions use ops this
2485    // backend does not lower.
2486    let reachable = crate::vm::reach::reach_with(program, &layout, interner, entries).functions;
2487    let mut fns: Vec<Plan> = {
2488        let mut v = Vec::with_capacity(program.functions.len());
2489        for fi in 0..program.functions.len() {
2490            if !reachable[fi] {
2491                if std::env::var_os("LOGOS_WASM_TRACE_FIELD").is_some() {
2492                    if let Some(f) = program.functions.get(fi) {
2493                        eprintln!(
2494                            "[wasm] stubbed (unreachable from Main): '{}'",
2495                            interner.resolve(f.name)
2496                        );
2497                    }
2498                }
2499                v.push(Plan::stub());
2500                continue;
2501            }
2502            match plan_function(
2503                program,
2504                fi,
2505                &layout,
2506                &ret_of_inferred,
2507                &global_of,
2508                &closure_ret,
2509                &ret_layout_of,
2510                &ret_closure_of,
2511                &global_layout_of,
2512                &global_declared_of,
2513                &param_origin,
2514                &exact_param,
2515                &capture_kinds,
2516                &capture_shapes,
2517                &capture_closures,
2518                true,
2519                linked,
2520            ) {
2521                Ok(p) => v.push(p),
2522                Err(e) => return Err(within_function(e, program, interner, Some(fi))),
2523            }
2524        }
2525        v
2526    };
2527    if tower::decide(program, &mut main, &mut fns, &global_kinds_cell.borrow()) && !linked {
2528        return Err(WasmLowerError::UnsupportedOwned(tower::RATIONAL_LISTS.to_string()));
2529    }
2530    // Which integers outgrow a machine word, and the tagged words that hold them ([`exact`]). A function
2531    // the host enters by name keeps machine words at its boundary: the module does not see that call.
2532    let entry_names = entries.names();
2533    let raw_boundary: Vec<bool> = program
2534        .functions
2535        .iter()
2536        .map(|f| entry_names.iter().any(|n| interner.resolve(f.name) == n))
2537        .collect();
2538    let exact_sig = exact::decide(
2539        program,
2540        &mut main,
2541        &mut fns,
2542        &raw_boundary,
2543        num_globals,
2544        linked,
2545    );
2546    let presence_enabled =
2547        absence::decide(&mut main, &mut fns, &program.constants, num_globals, linked);
2548
2549    // Whether the program uses the emitter's heap value model (a linear memory + bump allocator), an
2550    // iterator stack, or closures — computed HERE (before the import scan) so linker mode can import the
2551    // runtime allocator for the slab + refuse the shapes it can't yet share.
2552    // A heap op, OR a `LoadConst` of a Text literal (which materializes a Text object in memory).
2553    // A `FailWith` materializes its message Text before trapping, exactly as a `LoadConst` of a
2554    // Text does — so it needs the heap too. Missing this emitted a module whose `emit_alloc`
2555    // reached for a `__heap_ptr` global that was never declared: the bytes COMPILED and did not
2556    // VALIDATE, which `compile_to_wasm` reports as success.
2557    let loads_text = |op: &Op| match op {
2558        Op::LoadConst { idx, .. } | Op::FailWith { msg: idx } => {
2559            matches!(
2560                program.constants.get(*idx as usize),
2561                Some(Constant::Text(_))
2562            )
2563        }
2564        // A failure reason that is not already Text is materialized as one (its rendering, or the
2565        // refusal of a non-Text contract reason) before the host call.
2566        Op::CallBuiltin {
2567            builtin: BuiltinId::Fail | BuiltinId::FailReason,
2568            ..
2569        } => true,
2570        Op::CallBuiltin {
2571            builtin: BuiltinId::VfsMount | BuiltinId::VfsWriteFile,
2572            ..
2573        } => true,
2574        _ => false,
2575    };
2576    // A Text-typed `+`/`+=` (string concatenation) allocates a fresh Text, so it needs the heap even
2577    // if the program has no Text literal (it builds from a Text-valued variable).
2578    let concats_text = |p: &Plan, op: &Op| match *op {
2579        Op::Add { dst, .. } | Op::AddAssign { dst, .. } => {
2580            p.kinds.get(dst as usize) == Some(Kind::Text)
2581        }
2582        _ => false,
2583    };
2584    // Every composite value a module renders as Text renders through its shape's display function.
2585    let shown_shapes = {
2586        let plans: Vec<&Plan> = std::iter::once(&main).chain(fns.iter()).collect();
2587        display::ShownTable::new(display::ShownTable::collect(
2588            &plans,
2589            &program.struct_types,
2590            &program.enum_types,
2591        ))
2592    };
2593    let uses_heap = shown_shapes.len() > 0
2594        || std::iter::once(&main).chain(fns.iter()).any(|p| p.tower.holds())
2595        || std::iter::once(&main).chain(fns.iter()).any(|p| {
2596            p.ops
2597                .iter()
2598                .any(|op| op_uses_heap(op) || loads_text(op) || concats_text(p, op))
2599        });
2600    let uses_iter = std::iter::once(&main)
2601        .chain(fns.iter())
2602        .any(|p| p.ops.iter().any(|op| matches!(op, Op::IterPrepare { .. })));
2603    // Closures need a function table (for `call_indirect`) in the self-contained path; emit it only
2604    // when the program has one. LINKER MODE lowers a closure `CallValue` to a DIRECT `call` instead (the
2605    // callee is statically resolved, or already refused), so it needs NEITHER a table NOR an element
2606    // section — nothing the reloc transform can't handle. (A closure captured through a truly dynamic
2607    // value stays refused inside `lower_call_value`.)
2608    let has_closures = layout.is_closure.iter().any(|&c| c);
2609
2610    // ---- 2. Which host functions are used (in stable order) → their import indices ----
2611    let mut used = Vec::new();
2612    tower::note_imports(std::iter::once(&main).chain(fns.iter()), &mut used);
2613    let note = |h: HostFn, used: &mut Vec<HostFn>| {
2614        if !used.contains(&h) {
2615            used.push(h);
2616        }
2617    };
2618    // The host formatter a value of a given kind is stringified through (in a `Concat`, a Text-typed
2619    // `+`, or a whole-tuple / payload-enum `Show`). A kind with no scalar formatter notes nothing —
2620    // the per-op lowering soundly refuses it, so no import is wasted on a shape it can't emit.
2621    let note_fmt_kind = |k: Option<Kind>, used: &mut Vec<HostFn>| match k {
2622        Some(Kind::Int) => note(HostFn::FmtI64Into, used),
2623        Some(Kind::Float) => note(HostFn::FmtF64Into, used),
2624        Some(Kind::Bool) => note(HostFn::FmtBoolInto, used),
2625        // A whole `Seq of Int` / `Set of Int` operand is stringified by its collection formatter.
2626        Some(Kind::SeqInt | Kind::SeqAny) => note(HostFn::FmtSeqI64Into, used),
2627        // A whole `Seq of Bool` operand renders `[true, false, …]` via its own formatter.
2628        Some(Kind::SeqBool) => note(HostFn::FmtSeqBoolInto, used),
2629        Some(Kind::Set) => note(HostFn::FmtSetI64Into, used),
2630        // A BigInt operand of a concat is stringified to its decimal Text via the runtime.
2631        Some(Kind::BigInt) => note(HostFn::BigintToText, used),
2632        _ => {}
2633    };
2634    // A stringified operand (in a `Concat` or a Text-typed `+`) needs its scalar host formatter.
2635    let note_operand_fmt = |plan: &Plan, r: u16, used: &mut Vec<HostFn>| {
2636        note_fmt_kind(plan.kinds.get(r as usize), used)
2637    };
2638    for plan in std::iter::once(&main).chain(fns.iter()) {
2639        for (pc, op) in plan.ops.iter().enumerate() {
2640            if linked {
2641                let field_write = match *op {
2642                    Op::StructInsert { obj, value, .. } => plan
2643                        .structs
2644                        .slot
2645                        .get(pc)
2646                        .copied()
2647                        .flatten()
2648                        .map(|slot| (obj, slot as usize, value)),
2649                    Op::SetIndex {
2650                        collection, value, ..
2651                    }
2652                    | Op::SetIndexUnchecked {
2653                        collection, value, ..
2654                    } => plan
2655                        .place
2656                        .field_at
2657                        .get(pc)
2658                        .copied()
2659                        .flatten()
2660                        .and_then(|field| record_field_slot(plan, collection, field))
2661                        .map(|slot| (collection, slot, value)),
2662                    _ => None,
2663                };
2664                if let Some((obj, slot, value)) = field_write {
2665                    let rational_field = declared_record_slot_kind(
2666                        &plan.structs,
2667                        &program.struct_types,
2668                        &program.constants,
2669                        obj,
2670                        slot,
2671                    ) == Some(Kind::Rational);
2672                    match plan.kinds.get(value as usize) {
2673                        Some(Kind::Int) if rational_field => note(HostFn::RationalFromI64, &mut used),
2674                        Some(Kind::BigInt) if rational_field => note(HostFn::RationalFromBigint, &mut used),
2675                        _ => {}
2676                    }
2677                }
2678                // An integer handed to a rational parameter is the rational it equals.
2679                if let Op::Call {
2680                    func,
2681                    args_start,
2682                    arg_count,
2683                    ..
2684                }
2685                | Op::Spawn {
2686                    func,
2687                    args_start,
2688                    arg_count,
2689                }
2690                | Op::SpawnHandle {
2691                    func,
2692                    args_start,
2693                    arg_count,
2694                    ..
2695                } = *op
2696                {
2697                    let callee = fns.get(func as usize);
2698                    for a in 0..arg_count {
2699                        if callee.and_then(|f| f.kinds.get(a as usize)) == Some(Kind::Rational) {
2700                            match plan.kinds.get((args_start + a) as usize) {
2701                                Some(Kind::Int) => note(HostFn::RationalFromI64, &mut used),
2702                                Some(Kind::BigInt) => note(HostFn::RationalFromBigint, &mut used),
2703                                _ => {}
2704                            }
2705                        }
2706                    }
2707                }
2708                // A comparison over a rational orders both sides as rationals ([`lower_rational_compare`]).
2709                if let Op::Lt { lhs, rhs, .. }
2710                | Op::Gt { lhs, rhs, .. }
2711                | Op::LtEq { lhs, rhs, .. }
2712                | Op::GtEq { lhs, rhs, .. }
2713                | Op::Eq { lhs, rhs, .. }
2714                | Op::NotEq { lhs, rhs, .. } = *op
2715                {
2716                    let kind = |r: u16| plan.kinds.get(r as usize);
2717                    if (kind(lhs) == Some(Kind::Rational) || kind(rhs) == Some(Kind::Rational))
2718                        && (kind(lhs) == Some(Kind::Float) || kind(rhs) == Some(Kind::Float))
2719                    {
2720                        note(HostFn::RationalCmpF64, &mut used);
2721                    } else if kind(lhs) == Some(Kind::Rational) || kind(rhs) == Some(Kind::Rational) {
2722                        note(HostFn::RationalCmp, &mut used);
2723                        for r in [lhs, rhs] {
2724                            match kind(r) {
2725                                Some(Kind::Int) => note(HostFn::RationalFromI64, &mut used),
2726                                Some(Kind::BigInt) => note(HostFn::RationalFromBigint, &mut used),
2727                                _ => {}
2728                            }
2729                        }
2730                    }
2731                }
2732            }
2733            match *op {
2734                // Note the sink for any Show whose kind is known. An unknown-kind Show is NOT an
2735                // error here: it is either in a statically-dead block (never lowered — e.g. the
2736                // `Show` after an unbound-variable `FailWith`) or a genuinely unsupported kind that
2737                // the reachability-respecting per-block lowering will reject. Erroring here would
2738                // wrongly reject a program whose only unknown-kind Show is dead code.
2739                Op::Show { src } => {
2740                    if let Some(elems) = plan.structs.tuple_layouts.get(&src) {
2741                        // A whole-tuple `Show` (any tuple, homogeneous or not) assembles its `(…)`
2742                        // display as a Text and prints it, stringifying each element by its formatter.
2743                        note(HostFn::PrintText, &mut used);
2744                        for &e in elems {
2745                            note_operand_fmt(plan, e, &mut used);
2746                        }
2747                    } else if plan.kinds.get(src as usize) == Some(Kind::Enum) {
2748                        // A whole-enum `Show` prints the live variant's name via `print_text`; a
2749                        // PAYLOAD variant additionally stringifies each field inline (`Ctor(f0, …)`),
2750                        // so note every field type's formatter across the enum's variants.
2751                        note(HostFn::PrintText, &mut used);
2752                        if let Some(def) = plan
2753                            .structs
2754                            .ind_type_of
2755                            .get(&src)
2756                            .and_then(|tn| program.enum_types.iter().find(|e| &e.name == tn))
2757                        {
2758                            for v in &def.variants {
2759                                for ft in &v.field_types {
2760                                    note_fmt_kind(kind::boundary_to_kind(ft), &mut used);
2761                                }
2762                            }
2763                        }
2764                    } else if plan.kinds.get(src as usize) == Some(Kind::Map) {
2765                        // A whole-map `Show` assembles `{k: v, …}` and prints it; note `print_text` plus
2766                        // the key AND value formatters, from the kinds its lowering will use.
2767                        note(HostFn::PrintText, &mut used);
2768                        if let MapShowKinds::Entries(k, v) = map_show_kinds(plan, src) {
2769                            note_fmt_kind(k, &mut used);
2770                            note_fmt_kind(v, &mut used);
2771                        }
2772                    } else if plan.kinds.get(src as usize) == Some(Kind::SeqSeqInt) {
2773                        // A nested int-seq `Show` prints `[[…], …]`: `print_text` for the assembled
2774                        // outer string, and the scalar seq formatter for each inner `Seq of Int`.
2775                        note(HostFn::PrintText, &mut used);
2776                        note(HostFn::FmtSeqI64Into, &mut used);
2777                    } else if plan.kinds.get(src as usize) == Some(Kind::SeqEnum) {
2778                        // A whole `Seq of Enum` `Show` prints `[e0, …]` via `print_text`; each element's
2779                        // payload fields (if any) stringify through their own formatters.
2780                        note(HostFn::PrintText, &mut used);
2781                        if let Some(def) = plan
2782                            .structs
2783                            .seq_elem_ind_type
2784                            .get(&src)
2785                            .and_then(|tn| program.enum_types.iter().find(|e| &e.name == tn))
2786                        {
2787                            for v in &def.variants {
2788                                for ft in &v.field_types {
2789                                    note_fmt_kind(kind::boundary_to_kind(ft), &mut used);
2790                                }
2791                            }
2792                        }
2793                    } else if plan.kinds.get(src as usize) == Some(Kind::Struct) {
2794                        // A whole struct `Show` prints `TypeName { … }` via `print_text`; each field
2795                        // stringifies through its own formatter.
2796                        note(HostFn::PrintText, &mut used);
2797                        if let Some(def) = plan
2798                            .structs
2799                            .struct_name_of
2800                            .get(&src)
2801                            .and_then(|tn| program.struct_types.iter().find(|s| &s.name == tn))
2802                        {
2803                            for (_, bt) in &def.fields {
2804                                note_fmt_kind(kind::boundary_to_kind(bt), &mut used);
2805                            }
2806                        }
2807                    } else if plan.kinds.get(src as usize) == Some(Kind::SeqStruct) {
2808                        // A whole `Seq of Struct` `Show` — `print_text` plus each element struct's field
2809                        // formatters (resolved from the seq's element struct type).
2810                        note(HostFn::PrintText, &mut used);
2811                        if let Some(def) = plan
2812                            .structs
2813                            .seq_elem_struct_name
2814                            .get(&src)
2815                            .and_then(|tn| program.struct_types.iter().find(|s| &s.name == tn))
2816                        {
2817                            for (_, bt) in &def.fields {
2818                                note_fmt_kind(kind::boundary_to_kind(bt), &mut used);
2819                            }
2820                        }
2821                    } else if plan.kinds.get(src as usize) == Some(Kind::Rational) {
2822                        // A `Rational` `Show`: LINKER mode renders the BigInt-backed handle via
2823                        // `logos_rt_rational_to_text`→`print_text`; the self-contained i64/i64 value uses
2824                        // the dedicated two-arg (num, den) `print_rational` host sink.
2825                        if linked {
2826                            note(HostFn::RationalToText, &mut used);
2827                            note(HostFn::PrintText, &mut used);
2828                        } else {
2829                            note(HostFn::PrintRational, &mut used);
2830                        }
2831                    } else if plan.kinds.get(src as usize) == Some(Kind::Optional) {
2832                        // An `Optional` `Show` uses `print_nothing` for the null handle, and the boxed
2833                        // inner scalar's own sink for the present (`Some`) case.
2834                        note(HostFn::PrintNothing, &mut used);
2835                        let inner = plan
2836                            .structs
2837                            .opt_inner
2838                            .get(&src)
2839                            .copied()
2840                            .unwrap_or(Kind::Int);
2841                        if let Some(h) = HostFn::for_show(inner) {
2842                            note(h, &mut used);
2843                        }
2844                    } else if matches!(
2845                        plan.kinds.get(src as usize),
2846                        Some(Kind::Word32) | Some(Kind::Word64)
2847                    ) {
2848                        // A `Word` `Show` prints its unsigned value via `print_word`.
2849                        note(HostFn::PrintWord, &mut used);
2850                    } else if plan.kinds.get(src as usize) == Some(Kind::BigInt) {
2851                        // A `BigInt` `Show` renders the handle to a decimal Text then prints it.
2852                        note(HostFn::BigintToText, &mut used);
2853                        note(HostFn::PrintText, &mut used);
2854                    } else if plan.kinds.get(src as usize) == Some(Kind::Complex) {
2855                        // A `Complex` `Show` renders the handle to `re±imi` Text then prints it.
2856                        note(HostFn::ComplexToText, &mut used);
2857                        note(HostFn::PrintText, &mut used);
2858                    } else if plan.kinds.get(src as usize) == Some(Kind::Modular) {
2859                        note(HostFn::ModularToText, &mut used);
2860                        note(HostFn::PrintText, &mut used);
2861                    } else if plan.kinds.get(src as usize) == Some(Kind::Decimal) {
2862                        note(HostFn::DecimalToText, &mut used);
2863                        note(HostFn::PrintText, &mut used);
2864                    } else if plan.kinds.get(src as usize) == Some(Kind::Money) {
2865                        note(HostFn::MoneyToText, &mut used);
2866                        note(HostFn::PrintText, &mut used);
2867                    } else if plan.kinds.get(src as usize) == Some(Kind::Quantity) {
2868                        note(HostFn::QuantityToText, &mut used);
2869                        note(HostFn::PrintText, &mut used);
2870                    } else if plan.kinds.get(src as usize) == Some(Kind::Uuid) {
2871                        note(HostFn::UuidToText, &mut used);
2872                        note(HostFn::PrintText, &mut used);
2873                    } else if plan.kinds.get(src as usize) == Some(Kind::Dynamic) {
2874                        // A wire-decoded DYNAMIC value renders via `to_display_string` then prints.
2875                        note(HostFn::DynamicToText, &mut used);
2876                        note(HostFn::PrintText, &mut used);
2877                    } else if let Some(h) = plan.kinds.get(src as usize).and_then(HostFn::for_show)
2878                    {
2879                        note(h, &mut used);
2880                    }
2881                }
2882                Op::CallBuiltin {
2883                    builtin: BuiltinId::Pow,
2884                    args_start,
2885                    ..
2886                } => {
2887                    let bk = plan.kinds.get(args_start as usize);
2888                    let ek = plan.kinds.get((args_start + 1) as usize);
2889                    if let Some(h) = pow_host_for(bk, ek) {
2890                        note(h, &mut used);
2891                    }
2892                }
2893                // `a ** b` (the operator) shares `pow`'s host `pow_ff`/`pow_fi` for a Float result.
2894                // In LINKER mode an integer power drives the `logos_rt_bigint_*` runtime, leaving a
2895                // BigInt HANDLE (its `to_text` render is noted by the `Show` arm, not here).
2896                Op::Pow { dst, lhs, rhs } if plan.kinds.get(dst as usize) != Some(Kind::Rational) => {
2897                    let bk = plan.kinds.get(lhs as usize);
2898                    let ek = plan.kinds.get(rhs as usize);
2899                    if linked && bk == Some(Kind::Int) && ek == Some(Kind::Int) {
2900                        note(HostFn::BigintFromI64, &mut used);
2901                        note(HostFn::BigintPow, &mut used);
2902                    } else if let Some(h) = pow_host_for(bk, ek) {
2903                        note(h, &mut used);
2904                    }
2905                }
2906                // `+ - * / %` producing a BigInt (linker mode) call the matching `logos_rt_bigint_*` sink;
2907                // an `Int` operand is promoted with `from_i64`. Keyed on the result kind (which is BigInt
2908                // iff an operand was), so it wins over the numeric / Text-concat `Add` arms below.
2909                Op::Mul { dst, lhs, rhs }
2910                | Op::Add { dst, lhs, rhs }
2911                | Op::Sub { dst, lhs, rhs }
2912                | Op::Div { dst, lhs, rhs }
2913                | Op::Mod { dst, lhs, rhs }
2914                    if linked && plan.kinds.get(dst as usize) == Some(Kind::BigInt) =>
2915                {
2916                    note(
2917                        match *op {
2918                            Op::Add { .. } => HostFn::BigintAdd,
2919                            Op::Sub { .. } => HostFn::BigintSub,
2920                            Op::Div { .. } => HostFn::BigintDiv,
2921                            Op::Mod { .. } => HostFn::BigintMod,
2922                            _ => HostFn::BigintMul,
2923                        },
2924                        &mut used,
2925                    );
2926                    if plan.kinds.get(lhs as usize) == Some(Kind::Int)
2927                        || plan.kinds.get(rhs as usize) == Some(Kind::Int)
2928                    {
2929                        note(HostFn::BigintFromI64, &mut used);
2930                    }
2931                }
2932                // `+ - *` producing a Complex (linker mode) call the matching `logos_rt_complex_*` sink;
2933                // an `Int` operand is promoted with `from_i64` (real `n + 0i`).
2934                Op::Add { dst, lhs, rhs }
2935                | Op::Sub { dst, lhs, rhs }
2936                | Op::Mul { dst, lhs, rhs }
2937                    if linked && plan.kinds.get(dst as usize) == Some(Kind::Complex) =>
2938                {
2939                    note(
2940                        match *op {
2941                            Op::Add { .. } => HostFn::ComplexAdd,
2942                            Op::Sub { .. } => HostFn::ComplexSub,
2943                            _ => HostFn::ComplexMul,
2944                        },
2945                        &mut used,
2946                    );
2947                    if plan.kinds.get(lhs as usize) == Some(Kind::Int)
2948                        || plan.kinds.get(rhs as usize) == Some(Kind::Int)
2949                    {
2950                        note(HostFn::ComplexFromI64, &mut used);
2951                    }
2952                }
2953                // `complex(re, im)` builds a Complex handle: the int-part builder for two Int parts,
2954                // else the float-part builder (a `ComplexF`, parts as exact dyadic Rationals).
2955                Op::CallBuiltin {
2956                    builtin: BuiltinId::Complex,
2957                    args_start,
2958                    ..
2959                } if linked => {
2960                    if plan.kinds.get(args_start as usize) == Some(Kind::Int)
2961                        && plan.kinds.get((args_start + 1) as usize) == Some(Kind::Int)
2962                    {
2963                        note(HostFn::ComplexFromI64, &mut used);
2964                    } else {
2965                        note(HostFn::ComplexFromF64, &mut used);
2966                    }
2967                }
2968                // `abs(z)` of a Complex → its `f64` modulus via `logos_rt_complex_abs`.
2969                Op::CallBuiltin {
2970                    builtin: BuiltinId::Abs,
2971                    args_start,
2972                    ..
2973                } if linked && plan.kinds.get(args_start as usize) == Some(Kind::Complex) => {
2974                    note(HostFn::ComplexAbs, &mut used);
2975                }
2976                // `re(z)` / `im(z)` of a Complex → its parts as `f64`.
2977                Op::CallBuiltin {
2978                    builtin: BuiltinId::RealPart,
2979                    args_start,
2980                    ..
2981                } if linked && plan.kinds.get(args_start as usize) == Some(Kind::Complex) => {
2982                    note(HostFn::ComplexReF64, &mut used);
2983                }
2984                Op::CallBuiltin {
2985                    builtin: BuiltinId::ImagPart,
2986                    args_start,
2987                    ..
2988                } if linked && plan.kinds.get(args_start as usize) == Some(Kind::Complex) => {
2989                    note(HostFn::ComplexImF64, &mut used);
2990                }
2991                Op::Add { dst, lhs, rhs }
2992                | Op::Sub { dst, lhs, rhs }
2993                | Op::Mul { dst, lhs, rhs }
2994                    if linked && plan.kinds.get(dst as usize) == Some(Kind::Modular) =>
2995                {
2996                    note(
2997                        match *op {
2998                            Op::Add { .. } => HostFn::ModularAdd,
2999                            Op::Sub { .. } => HostFn::ModularSub,
3000                            _ => HostFn::ModularMul,
3001                        },
3002                        &mut used,
3003                    );
3004                    if plan.kinds.get(lhs as usize) == Some(Kind::Int)
3005                        || plan.kinds.get(rhs as usize) == Some(Kind::Int)
3006                    {
3007                        note(HostFn::ModularFromI64, &mut used);
3008                    }
3009                }
3010                Op::CallBuiltin {
3011                    builtin: BuiltinId::Modular,
3012                    ..
3013                } if linked => note(HostFn::ModularFromI64, &mut used),
3014                // `modular ÷ modular` (multiply by the inverse) and `pow(m, e)` modular exponentiation.
3015                Op::Div { dst, .. } | Op::ExactDiv { dst, .. }
3016                    if linked && plan.kinds.get(dst as usize) == Some(Kind::Modular) =>
3017                {
3018                    note(HostFn::ModularDiv, &mut used);
3019                }
3020                Op::Add { dst, lhs, rhs }
3021                | Op::Sub { dst, lhs, rhs }
3022                | Op::Mul { dst, lhs, rhs }
3023                    if linked && plan.kinds.get(dst as usize) == Some(Kind::Decimal) =>
3024                {
3025                    note(
3026                        match *op {
3027                            Op::Add { .. } => HostFn::DecimalAdd,
3028                            Op::Sub { .. } => HostFn::DecimalSub,
3029                            _ => HostFn::DecimalMul,
3030                        },
3031                        &mut used,
3032                    );
3033                    if plan.kinds.get(lhs as usize) == Some(Kind::Int)
3034                        || plan.kinds.get(rhs as usize) == Some(Kind::Int)
3035                    {
3036                        note(HostFn::DecimalFromI64, &mut used);
3037                    }
3038                }
3039                Op::CallBuiltin {
3040                    builtin: BuiltinId::Decimal,
3041                    ..
3042                } if linked => note(HostFn::DecimalFromText, &mut used),
3043                Op::Add { dst, lhs, rhs } | Op::Sub { dst, lhs, rhs }
3044                    if linked && plan.kinds.get(dst as usize) == Some(Kind::Money) =>
3045                {
3046                    let _ = (lhs, rhs);
3047                    note(
3048                        match *op {
3049                            Op::Add { .. } => HostFn::MoneyAdd,
3050                            _ => HostFn::MoneySub,
3051                        },
3052                        &mut used,
3053                    );
3054                }
3055                Op::CallBuiltin {
3056                    builtin: BuiltinId::Money,
3057                    ..
3058                } if linked => {
3059                    note(HostFn::MoneyFromDecimal, &mut used);
3060                    note(HostFn::MoneyFromI64, &mut used);
3061                }
3062                Op::Add { dst, lhs, rhs }
3063                | Op::Sub { dst, lhs, rhs }
3064                | Op::Mul { dst, lhs, rhs }
3065                | Op::Div { dst, lhs, rhs }
3066                    if linked && plan.kinds.get(dst as usize) == Some(Kind::Quantity) =>
3067                {
3068                    let _ = (lhs, rhs);
3069                    note(
3070                        match *op {
3071                            Op::Add { .. } => HostFn::QuantityAdd,
3072                            Op::Sub { .. } => HostFn::QuantitySub,
3073                            Op::Mul { .. } => HostFn::QuantityMul,
3074                            _ => HostFn::QuantityDiv,
3075                        },
3076                        &mut used,
3077                    );
3078                }
3079                Op::CallBuiltin {
3080                    builtin: BuiltinId::Quantity,
3081                    ..
3082                } if linked => note(HostFn::QuantityOfI64, &mut used),
3083                Op::CallBuiltin {
3084                    builtin: BuiltinId::Convert,
3085                    ..
3086                } if linked => note(HostFn::QuantityConvert, &mut used),
3087                // `+ - * /` on a Rational operand (linker): the BigInt-backed runtime op + a `from_i64`/
3088                // `from_bigint` promotion for any Int/BigInt operand that must widen to a Rational first.
3089                // (`/` here is a bare `Div` on two Rationals — the exact-division literal is `ExactDiv`.)
3090                Op::Add { dst, lhs, rhs }
3091                | Op::Sub { dst, lhs, rhs }
3092                | Op::Mul { dst, lhs, rhs }
3093                | Op::Div { dst, lhs, rhs }
3094                    if linked && plan.kinds.get(dst as usize) == Some(Kind::Rational) =>
3095                {
3096                    note(
3097                        match *op {
3098                            Op::Add { .. } => HostFn::RationalAdd,
3099                            Op::Sub { .. } => HostFn::RationalSub,
3100                            Op::Mul { .. } => HostFn::RationalMul,
3101                            _ => HostFn::RationalQuotient,
3102                        },
3103                        &mut used,
3104                    );
3105                    for r in [lhs, rhs] {
3106                        match plan.kinds.get(r as usize) {
3107                            Some(Kind::Int) => note(HostFn::RationalFromI64, &mut used),
3108                            Some(Kind::BigInt) => note(HostFn::RationalFromBigint, &mut used),
3109                            _ => {}
3110                        }
3111                    }
3112                }
3113                // `%`, `//`, `**` on a Rational (linker): the VM's rule for exact numbers in the runtime, with the
3114                // same promotions of an Int/BigInt operand.
3115                Op::Mod { dst, lhs, rhs } | Op::FloorDiv { dst, lhs, rhs } | Op::Pow { dst, lhs, rhs }
3116                    if linked && plan.kinds.get(dst as usize) == Some(Kind::Rational) =>
3117                {
3118                    note(
3119                        match *op {
3120                            Op::Mod { .. } => HostFn::RationalRemainder,
3121                            Op::FloorDiv { .. } => HostFn::RationalFloorQuotient,
3122                            _ => HostFn::RationalPower,
3123                        },
3124                        &mut used,
3125                    );
3126                    for r in [lhs, rhs] {
3127                        match plan.kinds.get(r as usize) {
3128                            Some(Kind::Int) => note(HostFn::RationalFromI64, &mut used),
3129                            Some(Kind::BigInt) => note(HostFn::RationalFromBigint, &mut used),
3130                            _ => {}
3131                        }
3132                    }
3133                }
3134                // A bitwise operator over a rational (linker): the integers two whole ones make.
3135                Op::BitXor { lhs, rhs, .. } | Op::BitAnd { lhs, rhs, .. } | Op::BitOr { lhs, rhs, .. }
3136                    if linked
3137                        && (plan.kinds.get(lhs as usize) == Some(Kind::Rational)
3138                            || plan.kinds.get(rhs as usize) == Some(Kind::Rational)) =>
3139                {
3140                    note(HostFn::RationalBitwise, &mut used);
3141                    for r in [lhs, rhs] {
3142                        match plan.kinds.get(r as usize) {
3143                            Some(Kind::Int) => note(HostFn::RationalFromI64, &mut used),
3144                            Some(Kind::BigInt) => note(HostFn::RationalFromBigint, &mut used),
3145                            _ => {}
3146                        }
3147                    }
3148                }
3149                // A real beside a rational (linker): the rational's double.
3150                Op::Add { dst, lhs, rhs }
3151                | Op::Sub { dst, lhs, rhs }
3152                | Op::Mul { dst, lhs, rhs }
3153                | Op::Div { dst, lhs, rhs }
3154                    if linked
3155                        && plan.kinds.get(dst as usize) == Some(Kind::Float)
3156                        && (plan.kinds.get(lhs as usize) == Some(Kind::Rational)
3157                            || plan.kinds.get(rhs as usize) == Some(Kind::Rational)) =>
3158                {
3159                    note(HostFn::RationalToF64, &mut used);
3160                }
3161                // `a / b` in a Rational context (`ExactDiv`, linker): the BigInt-backed division + the same
3162                // operand promotions (an Int/Int `7 / 2` promotes both, `r / 2` promotes only the Int).
3163                Op::ExactDiv { lhs, rhs, .. } if linked => {
3164                    note(HostFn::RationalDiv, &mut used);
3165                    for r in [lhs, rhs] {
3166                        match plan.kinds.get(r as usize) {
3167                            Some(Kind::Int) => note(HostFn::RationalFromI64, &mut used),
3168                            Some(Kind::BigInt) => note(HostFn::RationalFromBigint, &mut used),
3169                            _ => {}
3170                        }
3171                    }
3172                }
3173                // `floor`/`ceil`/`round`/`abs` of a Rational (linker): the exact `logos_rt_rational_*` sink.
3174                Op::CallBuiltin {
3175                    builtin:
3176                        b @ (BuiltinId::Floor | BuiltinId::Ceil | BuiltinId::Round | BuiltinId::Abs),
3177                    args_start,
3178                    ..
3179                } if linked && plan.kinds.get(args_start as usize) == Some(Kind::Rational) => {
3180                    note(
3181                        match b {
3182                            BuiltinId::Floor => HostFn::RationalFloor,
3183                            BuiltinId::Ceil => HostFn::RationalCeil,
3184                            BuiltinId::Round => HostFn::RationalRound,
3185                            _ => HostFn::RationalAbs,
3186                        },
3187                        &mut used,
3188                    );
3189                }
3190                // The `Uuid`-producing / -reading builtins (linker): each maps to its `logos_rt_uuid_*` sink.
3191                Op::CallBuiltin {
3192                    builtin:
3193                        b @ (BuiltinId::Uuid
3194                        | BuiltinId::UuidNil
3195                        | BuiltinId::UuidMax
3196                        | BuiltinId::UuidDns
3197                        | BuiltinId::UuidUrl
3198                        | BuiltinId::UuidOid
3199                        | BuiltinId::UuidX500
3200                        | BuiltinId::UuidVersion),
3201                    ..
3202                } if linked => {
3203                    note(
3204                        match b {
3205                            BuiltinId::Uuid => HostFn::UuidParse,
3206                            BuiltinId::UuidNil => HostFn::UuidNil,
3207                            BuiltinId::UuidMax => HostFn::UuidMax,
3208                            BuiltinId::UuidDns => HostFn::UuidDns,
3209                            BuiltinId::UuidUrl => HostFn::UuidUrl,
3210                            BuiltinId::UuidOid => HostFn::UuidOid,
3211                            BuiltinId::UuidX500 => HostFn::UuidX500,
3212                            _ => HostFn::UuidVersion,
3213                        },
3214                        &mut used,
3215                    );
3216                }
3217                // `uuid_from_bytes(seq)` boxes a Uuid from a packed 16-byte block via the runtime.
3218                Op::CallBuiltin {
3219                    builtin: BuiltinId::UuidFromBytes,
3220                    ..
3221                } if linked => note(HostFn::UuidFromPtr, &mut used),
3222                // The four SHA-1 SHA-NI ops call the `logos_rt_sha1*` runtime (base::sha_ops spec).
3223                Op::CallBuiltin {
3224                    builtin:
3225                        b @ (BuiltinId::Sha1Rnds4
3226                        | BuiltinId::Sha1Msg1
3227                        | BuiltinId::Sha1Msg2
3228                        | BuiltinId::Sha1Nexte),
3229                    ..
3230                } if linked => {
3231                    note(
3232                        match b {
3233                            BuiltinId::Sha1Rnds4 => HostFn::Sha1Rnds4,
3234                            BuiltinId::Sha1Msg1 => HostFn::Sha1Msg1,
3235                            BuiltinId::Sha1Msg2 => HostFn::Sha1Msg2,
3236                            _ => HostFn::Sha1Nexte,
3237                        },
3238                        &mut used,
3239                    );
3240                }
3241                // Lane-wise `Lanes + Lanes` / `lanes += lanes` → the `logos_rt_lanes4_add` runtime.
3242                Op::Add { lhs, .. }
3243                    if linked && plan.kinds.get(lhs as usize) == Some(Kind::Lanes) =>
3244                {
3245                    note(HostFn::Lanes4Add, &mut used)
3246                }
3247                Op::AddAssign { dst, .. }
3248                    if linked && plan.kinds.get(dst as usize) == Some(Kind::Lanes) =>
3249                {
3250                    note(HostFn::Lanes4Add, &mut used)
3251                }
3252                // Lane-wise `Lanes xor Lanes` → the `logos_rt_lanes4_xor` runtime.
3253                Op::BitXor { lhs, .. }
3254                    if linked && plan.kinds.get(lhs as usize) == Some(Kind::Lanes) =>
3255                {
3256                    note(HostFn::Lanes4Xor, &mut used)
3257                }
3258                // `Moment/Date ± Span` calendar arithmetic (linker) — the base's width picks the sink.
3259                Op::Add { lhs, rhs, .. } | Op::Sub { lhs, rhs, .. }
3260                    if linked
3261                        && (plan.kinds.get(lhs as usize) == Some(Kind::Span)
3262                            || plan.kinds.get(rhs as usize) == Some(Kind::Span)) =>
3263                {
3264                    let base = if plan.kinds.get(lhs as usize) == Some(Kind::Span) {
3265                        rhs
3266                    } else {
3267                        lhs
3268                    };
3269                    note(
3270                        if plan.kinds.get(base as usize) == Some(Kind::Date) {
3271                            HostFn::DateAddSpan
3272                        } else {
3273                            HostFn::MomentAddSpan
3274                        },
3275                        &mut used,
3276                    );
3277                }
3278                // `uuid == uuid` (equality on two Uuid operands, linker) — the 16-byte `logos_rt_uuid_eq`.
3279                Op::Eq { lhs, rhs, .. } | Op::NotEq { lhs, rhs, .. }
3280                    if linked
3281                        && plan.kinds.get(lhs as usize) == Some(Kind::Uuid)
3282                        && plan.kinds.get(rhs as usize) == Some(Kind::Uuid) =>
3283                {
3284                    note(HostFn::UuidEq, &mut used);
3285                }
3286                Op::LoadToday { .. } => note(HostFn::Today, &mut used),
3287                Op::LoadNow { .. } => note(HostFn::Now, &mut used),
3288                Op::CallBuiltin {
3289                    builtin: BuiltinId::RandomInt,
3290                    ..
3291                } => note(HostFn::RandomInt, &mut used),
3292                Op::CallBuiltin {
3293                    builtin: BuiltinId::EnvHas,
3294                    ..
3295                } => note(HostFn::EnvLen, &mut used),
3296                Op::CallBuiltin {
3297                    builtin: BuiltinId::EnvValue,
3298                    ..
3299                } => {
3300                    note(HostFn::EnvLen, &mut used);
3301                    note(HostFn::EnvInto, &mut used);
3302                }
3303                Op::CallBuiltin {
3304                    builtin: BuiltinId::TimeNow,
3305                    ..
3306                } => note(HostFn::TimeNow, &mut used),
3307                Op::Args { .. } => note(HostFn::Args, &mut used),
3308                // Every runtime failure hands its message to the host before trapping, so any
3309                // program that CAN fail declares the import. `FailWith` is reachable from
3310                // ordinary code (a bad index, a failed `Check`), so this is most programs.
3311                Op::FailWith { .. } => note(HostFn::LogosRtFail, &mut used),
3312                // `Fail with …` / a contract's reason: the same host call, and a non-Text value is
3313                // stringified by its formatter first.
3314                Op::CallBuiltin {
3315                    builtin: BuiltinId::Fail | BuiltinId::FailReason,
3316                    args_start,
3317                    ..
3318                } => {
3319                    note(HostFn::LogosRtFail, &mut used);
3320                    note_operand_fmt(plan, args_start, &mut used);
3321                }
3322                // A page has no file system: mounting a journal or writing a file fails with the
3323                // sentence that says so, through the same host call.
3324                Op::CallBuiltin {
3325                    builtin: BuiltinId::VfsMount | BuiltinId::VfsWriteFile,
3326                    ..
3327                } => note(HostFn::LogosRtFail, &mut used),
3328                // An indexing op emits an inline bounds check, and that check now reports WHICH
3329                // index before it traps. Over-approximating here is free: an unused import is
3330                // a name in the table, while a missing one is a module that cannot instantiate.
3331                Op::Div { .. }
3332                | Op::Mod { .. }
3333                | Op::Index { .. }
3334                | Op::IndexUnchecked { .. }
3335                | Op::SetIndex { .. }
3336                | Op::SetIndexUnchecked { .. } => note(HostFn::LogosRtFailAt, &mut used),
3337                Op::CallBuiltin {
3338                    builtin: BuiltinId::ParseInt,
3339                    ..
3340                } => note(HostFn::ParseInt, &mut used),
3341                Op::CallBuiltin {
3342                    builtin: BuiltinId::Contains,
3343                    ..
3344                } => note(HostFn::TextContains, &mut used),
3345                Op::CallBuiltin {
3346                    builtin: BuiltinId::DomSetAttribute,
3347                    args_start,
3348                    ..
3349                } => {
3350                    if plan.kinds.get(args_start as usize + 2) == Some(Kind::Bool) {
3351                        note(HostFn::DomSetBoolAttribute, &mut used)
3352                    } else {
3353                        note(HostFn::DomSetAttribute, &mut used)
3354                    }
3355                }
3356                Op::CallBuiltin { builtin, .. } if dom_import_of(builtin).is_some() => note(
3357                    dom_import_of(builtin).expect("guarded by the arm"),
3358                    &mut used,
3359                ),
3360                Op::CallBuiltin {
3361                    builtin: BuiltinId::ParseFloat,
3362                    ..
3363                } => note(HostFn::ParseFloat, &mut used),
3364                Op::CallBuiltin {
3365                    builtin: BuiltinId::ReadReals,
3366                    ..
3367                } => note(HostFn::ReadReals, &mut used),
3368                Op::CallBuiltin {
3369                    builtin: BuiltinId::ParseTimestamp,
3370                    ..
3371                } => note(HostFn::ParseTimestamp, &mut used),
3372                // `writeWireResidual(text)` frames the Text (`[len:u32][bytes]`) out to the host sink.
3373                Op::CallBuiltin {
3374                    builtin: BuiltinId::WriteWireResidual,
3375                    ..
3376                } => note(HostFn::WriteWireResidual, &mut used),
3377                // LINKER-mode extended temporal (calendar logic in `base::temporal`): `format_timestamp`
3378                // → a `Text` handle, `months_between`/`years_between` → an `Int`.
3379                Op::CallBuiltin {
3380                    builtin: BuiltinId::FormatTimestamp,
3381                    ..
3382                } if linked => note(HostFn::FormatTimestampRt, &mut used),
3383                Op::CallBuiltin {
3384                    builtin: BuiltinId::MonthsBetween,
3385                    ..
3386                } if linked => note(HostFn::MonthsBetweenRt, &mut used),
3387                Op::CallBuiltin {
3388                    builtin: BuiltinId::YearsBetween,
3389                    ..
3390                } if linked => note(HostFn::YearsBetweenRt, &mut used),
3391                Op::CallBuiltin {
3392                    builtin: BuiltinId::MakeDate,
3393                    ..
3394                } if linked => note(HostFn::MakeDateRt, &mut used),
3395                Op::CallBuiltin {
3396                    builtin: BuiltinId::MakeMoment,
3397                    ..
3398                } if linked => note(HostFn::MakeMomentRt, &mut used),
3399                // `in_zone(m, "zone")` → a `Text` (local wall-clock), `local_instant(m, "zone")` → a `Moment`.
3400                Op::CallBuiltin {
3401                    builtin: BuiltinId::InZone,
3402                    ..
3403                } if linked => note(HostFn::InZoneRt, &mut used),
3404                Op::CallBuiltin {
3405                    builtin: BuiltinId::LocalInstant,
3406                    ..
3407                } if linked => note(HostFn::LocalInstantRt, &mut used),
3408                // The general SIMD lane vocabulary (`base::LanesVal`) — the SSE byte/word-lane ops a Logos
3409                // codec compiles to. Each notes its `logos_rt_lanes_*` runtime fn (linker mode only).
3410                Op::CallBuiltin { builtin: b, .. } if linked && lanes_v_host_fn(b).is_some() => {
3411                    note(lanes_v_host_fn(b).unwrap(), &mut used)
3412                }
3413                // Money FX (linker): `to_currency`→convert; `set_rate` installs one rate (coercing the
3414                // rate arg Int→Rational / Decimal→Rational); `set_rates` installs a whole Map (the runtime
3415                // reads it — all three value-kind variants are noted since the map's value kind is resolved
3416                // at lowering; an imported-but-uncalled runtime fn is harmless, all are defined).
3417                Op::CallBuiltin {
3418                    builtin: BuiltinId::ToCurrency,
3419                    ..
3420                } if linked => note(HostFn::MoneyToCurrency, &mut used),
3421                Op::CallBuiltin {
3422                    builtin: BuiltinId::SetRate,
3423                    args_start,
3424                    ..
3425                } if linked => {
3426                    note(HostFn::MoneySetRate, &mut used);
3427                    match plan.kinds.get((args_start + 1) as usize) {
3428                        Some(Kind::Int) => note(HostFn::RationalFromI64, &mut used),
3429                        Some(Kind::Decimal) => note(HostFn::DecimalToRational, &mut used),
3430                        _ => {}
3431                    }
3432                }
3433                Op::CallBuiltin {
3434                    builtin: BuiltinId::SetRates,
3435                    ..
3436                } if linked => {
3437                    note(HostFn::MoneySetRatesInt, &mut used);
3438                    note(HostFn::MoneySetRatesRational, &mut used);
3439                    note(HostFn::MoneySetRatesDecimal, &mut used);
3440                }
3441                // `wireBytes(value)` — marshal the value via the REAL codec (by the arg's kind).
3442                Op::CallBuiltin {
3443                    builtin: BuiltinId::WireBytes,
3444                    args_start,
3445                    ..
3446                } if linked => {
3447                    if let Some(h) = wire_bytes_host_fn(plan.kinds.get(args_start as usize)) {
3448                        note(h, &mut used);
3449                    }
3450                }
3451                // `readWireProgram()` reads a host frame then DECODES it to a dynamic value; `run_accepted`
3452                // sandbox-evals a wire-received shipped function through the acceptance contract.
3453                Op::CallBuiltin {
3454                    builtin: BuiltinId::ReadWireProgram,
3455                    ..
3456                } if linked => {
3457                    note(HostFn::ReadWireFrame, &mut used);
3458                    note(HostFn::ReadWireProgramRt, &mut used);
3459                    // `readWireProgram` bump-allocs a receive buffer via `emit_alloc`, which in LINKER mode
3460                    // calls `logos_rt_alloc` — it MUST be imported, else `emit_alloc` falls back to the
3461                    // `__heap_ptr` global (undeclared in a linked module → an invalid global relocation).
3462                    note(HostFn::RtAlloc, &mut used);
3463                }
3464                Op::CallBuiltin {
3465                    builtin: BuiltinId::RunAccepted,
3466                    ..
3467                } if linked => note(HostFn::RunAccepted, &mut used),
3468                Op::CallBuiltin {
3469                    builtin:
3470                        BuiltinId::YearOf
3471                        | BuiltinId::MonthOf
3472                        | BuiltinId::DayOf
3473                        | BuiltinId::WeekdayOf
3474                        | BuiltinId::HourOf
3475                        | BuiltinId::MinuteOf
3476                        | BuiltinId::SecondOf
3477                        | BuiltinId::WeekOf
3478                        | BuiltinId::QuarterOf,
3479                    args_start,
3480                    ..
3481                } => {
3482                    // A `Date` argument uses the day-based `temporal_component_date`; a `Moment` uses the
3483                    // nanos-based `temporal_component`. (An unknown-kind arg in dead code notes nothing.)
3484                    if plan.kinds.get(args_start as usize) == Some(Kind::Date) {
3485                        note(HostFn::TemporalComponentDate, &mut used);
3486                    } else {
3487                        note(HostFn::TemporalComponent, &mut used);
3488                    }
3489                }
3490                // `format(x)` stringifies its argument with the same host formatter a Concat operand uses.
3491                Op::CallBuiltin {
3492                    builtin: BuiltinId::Format,
3493                    args_start,
3494                    arg_count,
3495                    ..
3496                } if arg_count > 0 => {
3497                    note_operand_fmt(plan, args_start, &mut used);
3498                }
3499                // A `Concat` — or a Text-typed `+`/`+=` (string concatenation) — stringifies its
3500                // operands; a non-Text operand needs its host formatter.
3501                Op::Concat { lhs, rhs, .. } => {
3502                    note_operand_fmt(plan, lhs, &mut used);
3503                    note_operand_fmt(plan, rhs, &mut used);
3504                }
3505                Op::Add { dst, lhs, rhs } if plan.kinds.get(dst as usize) == Some(Kind::Text) => {
3506                    note_operand_fmt(plan, lhs, &mut used);
3507                    note_operand_fmt(plan, rhs, &mut used);
3508                }
3509                Op::AddAssign { dst, src } if plan.kinds.get(dst as usize) == Some(Kind::Text) => {
3510                    note_operand_fmt(plan, dst, &mut used);
3511                    note_operand_fmt(plan, src, &mut used);
3512                }
3513                // A formatted piece: a `.N` precision spec (`"{x:.9}"`) uses the float-precision host; an
3514                // alignment/width spec (`"{x:>6}"`) stringifies the value (its own formatter) then pads
3515                // via `fmt_align_into`; a NO-spec debug piece (`"{x=}"`) just stringifies the value.
3516                // The lowering re-derives the exact spec; here we mirror EXACTLY which hosts each case
3517                // reaches, so no import is declared that the body never calls.
3518                Op::FormatValue { src, spec, .. } => {
3519                    let spec_s = match spec {
3520                        u32::MAX => None,
3521                        idx => match program.constants.get(idx as usize) {
3522                            Some(Constant::Text(s)) => Some(s.as_str()),
3523                            _ => None,
3524                        },
3525                    };
3526                    match spec_s {
3527                        Some(s) if s.starts_with('.') => note(HostFn::FmtF64PrecInto, &mut used),
3528                        Some(_) => {
3529                            note(HostFn::FmtAlignInto, &mut used);
3530                            note_fmt_kind(plan.kinds.get(src as usize), &mut used);
3531                        }
3532                        None => note_fmt_kind(plan.kinds.get(src as usize), &mut used),
3533                    }
3534                }
3535                // Observation (Wave 13, OBSERVED profile) — one host import; the
3536                // host resolves the site's category/message/label.
3537                Op::Obs { .. } => note(HostFn::Obs, &mut used),
3538                _ => {}
3539            }
3540        }
3541    }
3542    // A Text the HOST hands over — an element's text, a response body, the route, and every Text
3543    // argument it passes when it enters the page by name (an event and its value to the node
3544    // dispatcher, a failure's message to the failure handler) — is written into the module's heap
3545    // through `__logos_text_new`. A module that takes one has a heap and carries that allocator, even
3546    // when it builds no heap value of its own.
3547    for k in shown_shapes.leaf_kinds(&program.struct_types, &program.enum_types) {
3548        note_fmt_kind(Some(k), &mut used);
3549    }
3550    {
3551        let plans: Vec<&Plan> = std::iter::once(&main).chain(fns.iter()).collect();
3552        exact::note_imports(&plans, &mut |h| note(h, &mut used));
3553        if presence_enabled {
3554            note(HostFn::PrintNothing, &mut used);
3555        }
3556        if exact_sig.sequence_ints() {
3557            note(HostFn::ExactText, &mut used);
3558            note(HostFn::PrintText, &mut used);
3559        }
3560    }
3561    let host_entered: Vec<usize> = program
3562        .functions
3563        .iter()
3564        .enumerate()
3565        .filter(|(_, f)| entry_names.iter().any(|n| interner.resolve(f.name) == n))
3566        .map(|(at, _)| at)
3567        .collect();
3568    let takes_host_text = used.iter().any(|h| h.returns_host_text())
3569        || host_entered.iter().any(|&at| {
3570            let plan = &fns[at];
3571            (0..plan.num_params as usize).any(|r| plan.kinds.get(r) == Some(Kind::Text))
3572        });
3573    // A sequence the host hands over is built the same way, through `__logos_seq_new`.
3574    let takes_host_seq = used.iter().any(|h| h.returns_host_seq());
3575    let uses_heap = uses_heap || takes_host_text || takes_host_seq;
3576    // LINKER MODE with an emitter heap or an iterator stack imports the runtime allocator, to seed each
3577    // one's slab at the `main` prologue.
3578    if linked && (uses_heap || uses_iter) {
3579        note(HostFn::RtAlloc, &mut used);
3580    }
3581    // A self-contained heap grows `memory` on demand and reports failure the same way any other
3582    // inline check does — a program need not divide or index anything to exhaust its heap, so this
3583    // import cannot wait to be noticed by a specific op the way the others above are.
3584    if uses_heap && !linked {
3585        note(HostFn::LogosRtFailAt, &mut used);
3586    }
3587    // Re-sort into the canonical HOST_FNS order so indices are deterministic.
3588    let imports: Vec<HostFn> = HOST_FNS
3589        .iter()
3590        .copied()
3591        .filter(|h| used.contains(h))
3592        .collect();
3593    let host_index =
3594        |h: HostFn| -> Option<u32> { imports.iter().position(|x| *x == h).map(|i| i as u32) };
3595    let num_imports = imports.len() as u32;
3596    let main_index = num_imports;
3597    let fn_base = num_imports + 1; // wasm index of program.functions[0]
3598
3599    // ---- 3. Type table: host functions, then Main, then each function ----
3600    let mut types = TypeTable::default();
3601    let host_type: Vec<u32> = imports
3602        .iter()
3603        .map(|h| types.intern(h.params(), h.results()))
3604        .collect();
3605    let main_type = types.intern(vec![], result_valtypes(main.result));
3606    let mut fn_types: Vec<u32> = Vec::with_capacity(fns.len());
3607    let fn_stubbed: Vec<bool> = fns.iter().map(|p| p.stub).collect();
3608    let mut fn_param_valtypes: Vec<Vec<u8>> = Vec::with_capacity(fns.len());
3609    let mut fn_param_kinds: Vec<Vec<Option<Kind>>> = Vec::with_capacity(fns.len());
3610    for p in &fns {
3611        let params: Vec<u8> = (0..p.num_params)
3612            .map(|r| p.kinds.valtype(r as usize))
3613            .collect();
3614        fn_types.push(types.intern(params.clone(), plan_results(p)));
3615        fn_param_valtypes.push(params);
3616        fn_param_kinds.push((0..p.num_params).map(|r| p.kinds.get(r as usize)).collect());
3617    }
3618    // The exported closure trampoline (`__logos_call_closure(handle:i32, arg:i64)->i64`)
3619    // shares the funcref table it `call_indirect`s through, so it exists only in a
3620    // self-contained module that has closures. Its type is interned here (before the
3621    // type section is encoded); its body + index are built after the function bodies.
3622    let emit_trampoline = has_closures && !linked;
3623    let trampoline_type = emit_trampoline.then(|| types.intern(vec![I32, I64], vec![I64]));
3624    // The reader the linked value runtime calls back for a closure the program defines a real number by
3625    // (`logos_program_defines(body: i32, n: i64) -> i32`), the module's last function.
3626    let emit_definer = linked && std::iter::once(&main).chain(fns.iter()).any(tower::defines_reals);
3627    let definer_type = emit_definer.then(|| types.intern(vec![I32, I64], vec![I32]));
3628    // The display functions follow the trampoline: `(handle: i32) -> i32 Text`, one per shape.
3629    let mut shown_shapes = shown_shapes;
3630    shown_shapes.place(fn_base + fns.len() as u32 + u32::from(emit_trampoline));
3631    let shown_type = (shown_shapes.len() > 0).then(|| types.intern(vec![I32], vec![I32]));
3632    // The runtime functions follow the trampoline in the index space, and their indices have to be
3633    // known BEFORE any body is lowered because every allocation site calls them.
3634    let emit_heap_fns = uses_heap && !linked;
3635    // A page is interactive when its host RE-ENTERS it after `main`: through a callback it handed
3636    // the host, or through a function the host enters by name (an element's event arrives at the
3637    // node dispatcher, a timer's tick at `__lgx_tick`).
3638    let interactive = emit_heap_fns
3639        && (imports.iter().any(|h| h.registers_callback()) || !host_entered.is_empty());
3640    // S8's true counts, turn list and safepoint on every interactive page; the census only in a
3641    // check-mode module (`Reclaim::Checked`). See `Runtime::layout`.
3642    let runtime = emit_heap_fns.then(|| {
3643        Runtime::layout(
3644            num_imports + 1 + fns.len() as u32 + u32::from(emit_trampoline) + shown_shapes.len(),
3645            interactive,
3646            takes_host_text,
3647            takes_host_seq,
3648            uses_iter,
3649            exact::on(&main),
3650            reclaim,
3651            &mut types,
3652        )
3653    });
3654
3655    // ---- 4. Emit each function body, with the call/host context resolved ----
3656    let heap_global = num_globals as u32; // `__heap_ptr` follows the user globals
3657    let iter_global = heap_global + u32::from(uses_heap); // `__iter_sp` follows `__heap_ptr`
3658                                                          // The S8 turn-retained list's three globals (`data_ptr`, `len`, `cap`) follow `__iter_sp` —
3659                                                          // present exactly when `interactive` AND `reclaim` (batch modules never run a safepoint, so
3660                                                          // nothing would ever drain the list; see `Runtime::layout`).
3661    let retain_global = iter_global + u32::from(uses_iter);
3662    let retain_base = (emit_heap_fns && reclaim != Reclaim::Off).then_some(retain_global);
3663    let uses_counters = std::iter::once(&main).chain(fns.iter()).any(|p| {
3664        p.ops
3665            .iter()
3666            .any(|op| matches!(op, Op::NewCrdt { kind: 4 | 5, .. }))
3667    });
3668    let replica_global =
3669        uses_counters.then_some(retain_global + 3 * u32::from(retain_base.is_some()));
3670    // Live registration list and monotonic identities, independent of reusable heap addresses.
3671    let callback_base = (retain_base.is_some() && has_closures)
3672        .then_some(retain_global + 3 * u32::from(retain_base.is_some()) + u32::from(uses_counters));
3673    let fn_results: Vec<Option<Kind>> = fns.iter().map(|p| p.result).collect();
3674    let fn_inout: Vec<Vec<u16>> = fns.iter().map(|p| p.inout.clone()).collect();
3675    // `capture_kinds` (computed in the planning pass, global + local) is the same source the closure
3676    // body signatures were seeded from, so `MakeClosure`'s store / `CallValue`'s load / the signature
3677    // all agree on each capture's valtype.
3678    let rt_alloc = if linked && uses_heap {
3679        host_index(HostFn::RtAlloc)
3680    } else {
3681        None
3682    };
3683    let global_kinds: Vec<Option<Kind>> = global_kinds_cell.borrow().clone();
3684    let global_valtypes: Vec<u8> = global_kinds
3685        .iter()
3686        .map(|gk| gk.map(Kind::wasm_valtype).unwrap_or(I64))
3687        .collect();
3688    let text_pool_cell = std::cell::RefCell::new(TextPool::default());
3689    let text_pool = (!linked).then_some(&text_pool_cell);
3690    let shared_maps = std::iter::once(&main).chain(fns.iter()).any(|p| {
3691        p.ops
3692            .iter()
3693            .any(|op| matches!(op, Op::NewCrdt { kind: 6, .. }))
3694    });
3695    let absence_base = presence_enabled.then_some(
3696        num_globals as u32
3697            + u32::from(uses_heap)
3698            + u32::from(uses_iter)
3699            + 3 * u32::from(retain_base.is_some())
3700            + u32::from(uses_counters)
3701            + 2 * u32::from(callback_base.is_some()),
3702    );
3703    let may_safepoint = may_safepoint(&fns);
3704    let ctx = Ctx {
3705        absence_base,
3706        constants: &program.constants,
3707        global_valtypes: &global_valtypes,
3708        global_kinds: &global_kinds,
3709        runtime: runtime.as_ref(),
3710        shared_maps,
3711        text_pool,
3712        host_index: &host_index,
3713        fn_base,
3714        heap_global,
3715        iter_global,
3716        replica_global,
3717        uses_iter,
3718        fn_type: &fn_types,
3719        fn_param_valtypes: &fn_param_valtypes,
3720        fn_param_kinds: &fn_param_kinds,
3721        fn_stubbed: &fn_stubbed,
3722        fn_results: &fn_results,
3723        fn_inout: &fn_inout,
3724        functions: &program.functions,
3725        capture_kinds: &capture_kinds,
3726        enum_types: &program.enum_types,
3727        struct_types: &program.struct_types,
3728        policies,
3729        interner,
3730        linked,
3731        rt_alloc,
3732        retain_base,
3733        shown: &shown_shapes,
3734        exact: &exact_sig,
3735        hot: std::cell::Cell::new(false),
3736        batch_reclaim: !interactive && retain_base.is_some(),
3737        may_safepoint: &may_safepoint,
3738    };
3739    let main_body =
3740        emit_body(&main, &ctx).map_err(|e| within_function(e, program, interner, None))?;
3741    let mut fn_bodies = Vec::with_capacity(fns.len());
3742    for (fi, p) in fns.iter().enumerate() {
3743        fn_bodies
3744            .push(emit_body(p, &ctx).map_err(|e| within_function(e, program, interner, Some(fi)))?);
3745    }
3746    let mut shown_bodies = Vec::with_capacity(shown_shapes.len() as usize);
3747    for shape in shown_shapes.shapes() {
3748        shown_bodies.push(display::emit_display_fn(shape, &ctx)?);
3749    }
3750    // Build the trampoline body + its wasm function index (after all user functions).
3751    let trampoline_body = emit_trampoline
3752        .then(|| emit_closure_trampoline(&fns, program, &fn_types, &ctx, callback_base))
3753        .transpose()?;
3754    let trampoline_index = fn_base + fns.len() as u32;
3755    let definer_body = emit_definer.then(|| tower::emit_defining_reader(&fns, &ctx)).transpose()?;
3756
3757    // ---- 5. Assemble the module ----
3758    let mut module = vec![0x00, 0x61, 0x73, 0x6D, 0x01, 0x00, 0x00, 0x00];
3759    section(&mut module, 1, &types.encode());
3760
3761    // Import section (id 2): each host sink as a function import in `env`. In LINKER mode the program
3762    // also imports the ONE shared linear memory — `rust-lld` creates the output memory and resolves this
3763    // import (and the base runtime object's own `env.__linear_memory`) to it. A memory import occupies no
3764    // function-index slot, so the host functions keep their `host_index` indices regardless.
3765    let mut imp = Vec::new();
3766    leb_u32(&mut imp, imports.len() as u32 + u32::from(linked));
3767    for (i, h) in imports.iter().enumerate() {
3768        encode_name(&mut imp, "env");
3769        encode_name(&mut imp, h.field());
3770        imp.push(0x00); // import kind: function
3771        leb_u32(&mut imp, host_type[i]);
3772    }
3773    if linked {
3774        encode_name(&mut imp, "env");
3775        encode_name(&mut imp, "__linear_memory");
3776        imp.push(0x02); // import kind: memory
3777        imp.push(0x00); // limits: min only
3778        leb_u32(&mut imp, 0); // min 0 pages — lld unions this with the runtime's need + grows on demand
3779    }
3780    section(&mut module, 2, &imp);
3781
3782    // Function section (id 3): Main + each user function (type indices) + the trampoline + the
3783    // runtime functions.
3784    let runtime_count = runtime.as_ref().map_or(0, |r| r.fns.len() as u32);
3785    let mut func = Vec::new();
3786    leb_u32(
3787        &mut func,
3788        1 + fns.len() as u32
3789            + u32::from(emit_trampoline)
3790            + shown_shapes.len()
3791            + runtime_count
3792            + u32::from(emit_definer),
3793    );
3794    leb_u32(&mut func, main_type);
3795    for t in &fn_types {
3796        leb_u32(&mut func, *t);
3797    }
3798    if let Some(tt) = trampoline_type {
3799        leb_u32(&mut func, tt);
3800    }
3801    if let Some(st) = shown_type {
3802        for _ in 0..shown_shapes.len() {
3803            leb_u32(&mut func, st);
3804        }
3805    }
3806    if let Some(r) = &runtime {
3807        for t in &r.types {
3808            leb_u32(&mut func, *t);
3809        }
3810    }
3811    if let Some(dt) = definer_type {
3812        leb_u32(&mut func, dt);
3813    }
3814    section(&mut module, 3, &func);
3815
3816    // Table section (id 4): one funcref table holding every user function, so a closure's
3817    // `CallValue` can `call_indirect` it by index. (Emitted only when the program has closures AND is
3818    // self-contained — linker mode direct-calls closures, so it needs no table.)
3819    if has_closures && !linked {
3820        let mut table = Vec::new();
3821        leb_u32(&mut table, 1); // one table
3822        table.push(0x70); // elemtype: funcref
3823        table.push(0x00); // limits: min only
3824        leb_u32(&mut table, fns.len() as u32); // min = number of functions
3825        section(&mut module, 4, &table);
3826    }
3827
3828    // Memory section (id 5): one linear memory for the heap value model, exported as "memory". The
3829    // bump allocator never frees, so a build-then-scan program (a 1000-element array, an n-character
3830    // string built by `+`, a search that cuts a one-char Text per index) needs real headroom — one
3831    // page (64 KiB) overflows on any non-tiny input. `HEAP_PAGES` * 64 KiB is the address space; the
3832    // iterator stack grows down from its top, the heap up from 16, so they meet only at exhaustion.
3833    // LINKER MODE does NOT define a memory — it IMPORTS the shared one (above) and the bump allocator
3834    // draws from a runtime slab, so the runtime's `dlmalloc` owns the address space.
3835    if uses_heap && !linked {
3836        let mut mem = Vec::new();
3837        leb_u32(&mut mem, 1); // one memory
3838        mem.push(0x00); // limits: min only
3839        leb_u32(&mut mem, HEAP_PAGES); // min HEAP_PAGES pages
3840        section(&mut module, 5, &mem);
3841    }
3842
3843    // The dynamic heap starts above the interned text. The pool is filled while bodies are lowered,
3844    // which is finished by now, so this is the first moment the static region's size is known.
3845    let heap_base = HEAP_START + text_pool_cell.borrow().image.len() as i32;
3846
3847    // Global section (id 6): one mutable global per promoted Main binding (zero-initialized),
3848    // plus the bump-allocator pointer `__heap_ptr` when the program uses the heap.
3849    if num_globals > 0 || uses_heap || uses_iter || retain_base.is_some() || uses_counters {
3850        let mut glob = Vec::new();
3851        leb_u32(
3852            &mut glob,
3853            num_globals as u32
3854                + u32::from(uses_heap)
3855                + u32::from(uses_iter)
3856                + 3 * u32::from(retain_base.is_some())
3857                + u32::from(uses_counters)
3858                + 2 * u32::from(callback_base.is_some())
3859                + if presence_enabled {
3860                    num_globals as u32
3861                } else {
3862                    0
3863                },
3864        );
3865        for gk in &global_kinds {
3866            let vt = gk.map(Kind::wasm_valtype).unwrap_or(I64);
3867            glob.push(vt);
3868            glob.push(0x01); // mutable
3869                             // The zero-initializer MUST match the global's valtype — an `i32` (handle-kind) global
3870                             // with an `i64.const 0` init is invalid wasm. `i32` covers any heap handle (struct, enum,
3871                             // seq, map, …) a promoted Main binding may hold.
3872            if vt == F64 {
3873                glob.push(0x44); // f64.const 0
3874                glob.extend_from_slice(&0f64.to_le_bytes());
3875            } else if vt == I32 {
3876                i32_const(&mut glob, 0);
3877            } else {
3878                glob.push(0x42); // i64.const 0
3879                leb_i64(&mut glob, 0);
3880            }
3881            glob.push(0x0B); // end of init expr
3882        }
3883        if uses_heap {
3884            // `__heap_ptr`: mutable i32. Self-contained: init 16 (the low 16 bytes stay reserved/null).
3885            // LINKER MODE: init 0 — the `main` prologue seeds it from a runtime `logos_rt_alloc` SLAB, so
3886            // the bump region lives inside memory the runtime's `dlmalloc` owns (no collision).
3887            glob.push(I32);
3888            glob.push(0x01); // mutable
3889            i32_const(&mut glob, if linked { 0 } else { heap_base });
3890            glob.push(0x0B);
3891        }
3892        if uses_iter {
3893            // `__iter_sp`: mutable i32, the top `Repeat` frame (a heap block, see `FRAME_PREV`);
3894            // 0 while no loop runs.
3895            glob.push(I32);
3896            glob.push(0x01); // mutable
3897            i32_const(&mut glob, 0);
3898            glob.push(0x0B);
3899        }
3900        if retain_base.is_some() {
3901            // The S8 turn-retained list: `data_ptr`/`len`/`cap`, all i32, all zero (empty) at
3902            // start-up — grown like every other buffer in this backend on first use.
3903            for _ in 0..3 {
3904                glob.push(I32);
3905                glob.push(0x01); // mutable
3906                i32_const(&mut glob, 0);
3907                glob.push(0x0B);
3908            }
3909        }
3910        if uses_counters {
3911            glob.push(I64);
3912            glob.push(0x01);
3913            i64c(&mut glob, 0);
3914            glob.push(0x0B);
3915        }
3916        if callback_base.is_some() {
3917            for _ in 0..2 {
3918                glob.push(I32);
3919                glob.push(0x01);
3920                i32_const(&mut glob, 0);
3921                glob.push(0x0B);
3922            }
3923        }
3924        if presence_enabled {
3925            for _ in 0..num_globals {
3926                glob.extend([I32, 0x01]);
3927                i32_const(&mut glob, 1);
3928                glob.push(0x0b);
3929            }
3930        }
3931        section(&mut module, 6, &glob);
3932    }
3933
3934    // Export section (id 7): the synthesized top-level body as `main`, plus `memory` if this module
3935    // DEFINES one. In linker mode the memory is imported (the linker re-exports it), so we don't.
3936    let export_memory = uses_heap && !linked;
3937    // Export the user's `render` function as `__logos_render` so the browser host
3938    // can re-invoke the view after a reactive signal changes (immediate-mode
3939    // re-render). It is an ordinary compiled function at `fn_base + its position`;
3940    // we only give it a stable export name.
3941    let render_index = program
3942        .functions
3943        .iter()
3944        .position(|f| interner.resolve(f.name) == "render")
3945        .map(|p| fn_base + p as u32);
3946    // `__heap_ptr` is exported whenever the module has a heap, so a host can read how much of the
3947    // address space the page has claimed; an export widens nothing a host must implement.
3948    // Every function a host enters by name (`HostEntries::names`, from `lgx_lower::LGX_ENTRIES`) that
3949    // the program defines, under its own name — the page entries always, and each component the host
3950    // may mount on demand. A shipped page mounts none of its own.
3951    let host_entries: Vec<(String, u32)> = entries
3952        .names()
3953        .into_iter()
3954        .filter_map(|name| {
3955            let at = program
3956                .functions
3957                .iter()
3958                .position(|f| interner.resolve(f.name) == name)?;
3959            Some((name, fn_base + at as u32))
3960        })
3961        .collect();
3962    const EXPORT_FUNC: u8 = 0x00;
3963    const EXPORT_MEMORY: u8 = 0x02;
3964    const EXPORT_GLOBAL: u8 = 0x03;
3965    let mut exports: Vec<(&str, u8, u32)> = vec![("main", EXPORT_FUNC, main_index)];
3966    if export_memory {
3967        exports.push(("memory", EXPORT_MEMORY, 0));
3968    }
3969    if emit_trampoline {
3970        exports.push(("__logos_call_closure", EXPORT_FUNC, trampoline_index));
3971    }
3972    if let Some(ri) = render_index {
3973        exports.push(("__logos_render", EXPORT_FUNC, ri));
3974    }
3975    for (name, index) in &host_entries {
3976        exports.push((name.as_str(), EXPORT_FUNC, *index));
3977    }
3978    if uses_heap && !linked {
3979        exports.push(("__heap_ptr", EXPORT_GLOBAL, heap_global));
3980    }
3981    if let Some(r) = &runtime {
3982        for (i, f) in r.fns.iter().enumerate() {
3983            if let Some(name) = f.export() {
3984                exports.push((name, EXPORT_FUNC, r.first + i as u32));
3985            }
3986        }
3987    }
3988    if emit_definer {
3989        let definer_index =
3990            fn_base + fns.len() as u32 + u32::from(emit_trampoline) + shown_shapes.len() + runtime_count;
3991        exports.push((tower::DEFINER_SYMBOL, EXPORT_FUNC, definer_index));
3992    }
3993    let mut export = Vec::new();
3994    leb_u32(&mut export, exports.len() as u32);
3995    for (name, kind, index) in &exports {
3996        encode_name(&mut export, name);
3997        export.push(*kind);
3998        leb_u32(&mut export, *index);
3999    }
4000    section(&mut module, 7, &export);
4001
4002    // Element section (id 9): an active segment filling table slot `i` with function `i`'s funcref
4003    // (wasm index `fn_base + i`), so a closure storing function index `i` `call_indirect`s table[i].
4004    // Self-contained only — linker mode direct-calls closures (no table to fill).
4005    if has_closures && !linked {
4006        let mut elem = Vec::new();
4007        leb_u32(&mut elem, 1); // one segment
4008        leb_u32(&mut elem, 0); // flags 0: active, table 0, MVP funcref vec
4009        elem.push(0x41); // i32.const 0 (offset)
4010        leb_i32(&mut elem, 0);
4011        elem.push(0x0B); // end
4012        leb_u32(&mut elem, fns.len() as u32);
4013        for i in 0..fns.len() as u32 {
4014            leb_u32(&mut elem, fn_base + i);
4015        }
4016        section(&mut module, 9, &elem);
4017    }
4018
4019    // Code section (id 10): Main, then each function (each prefixed by its byte length),
4020    // then the trampoline, then the runtime functions.
4021    let mut code = Vec::new();
4022    leb_u32(
4023        &mut code,
4024        1 + fn_bodies.len() as u32
4025            + u32::from(emit_trampoline)
4026            + shown_shapes.len()
4027            + runtime_count
4028            + u32::from(emit_definer),
4029    );
4030    for entry in std::iter::once(&main_body).chain(fn_bodies.iter()) {
4031        leb_u32(&mut code, entry.len() as u32);
4032        code.extend_from_slice(entry);
4033    }
4034    if let Some(tb) = &trampoline_body {
4035        leb_u32(&mut code, tb.len() as u32);
4036        code.extend_from_slice(tb);
4037    }
4038    for body in &shown_bodies {
4039        leb_u32(&mut code, body.len() as u32);
4040        code.extend_from_slice(body);
4041    }
4042    if let Some(r) = &runtime {
4043        let env = RuntimeEnv {
4044            heap_global,
4045            iter_global,
4046            heap_base,
4047            fail_at: host_index(HostFn::LogosRtFailAt)
4048                .expect("a self-contained heap always imports logos_rt_fail_at"),
4049            exact_drop: host_index(HostFn::ExactDrop),
4050            exact_clone: host_index(HostFn::ExactClone),
4051            exact_cmp: host_index(HostFn::ExactCmp),
4052            exact_host: (|| {
4053                Some([
4054                    host_index(HostFn::ExactBox)?,
4055                    host_index(HostFn::ExactAdd)?,
4056                    host_index(HostFn::ExactSub)?,
4057                    host_index(HostFn::ExactMul)?,
4058                    host_index(HostFn::ExactNarrow)?,
4059                    host_index(HostFn::ExactClone)?,
4060                ])
4061            })(),
4062            retain_base,
4063            callback_base,
4064            global_kinds: global_kinds.clone(),
4065            shared_maps,
4066            runtime: r,
4067        };
4068        for body in r.bodies(&env) {
4069            leb_u32(&mut code, body.len() as u32);
4070            code.extend_from_slice(&body);
4071        }
4072    }
4073    if let Some(db) = &definer_body {
4074        leb_u32(&mut code, db.len() as u32);
4075        code.extend_from_slice(db);
4076    }
4077    section(&mut module, 10, &code);
4078
4079    // Data section (id 11): the interned text literals, one active segment at `STATIC_BASE`.
4080    // Emitted after the code section, which is where the spec puts it and where the pool is full.
4081    {
4082        let image = text_pool_cell.borrow();
4083        if !image.image.is_empty() {
4084            let mut data = Vec::new();
4085            leb_u32(&mut data, 1); // one segment
4086            leb_u32(&mut data, 0); // active, memory 0
4087            i32_const(&mut data, STATIC_BASE);
4088            data.push(0x0B); // end of the offset expression
4089            leb_u32(&mut data, image.image.len() as u32);
4090            data.extend_from_slice(&image.image);
4091            section(&mut module, 11, &data);
4092        }
4093    }
4094
4095    Ok(module)
4096}
4097
4098/// The declared result kind of `program.functions[fi]` (`None` for void / undeclared) — used
4099/// to type `Op::Call` results before the callee's own body is inferred.
4100fn declared_result(program: &CompiledProgram, fi: usize) -> Option<Kind> {
4101    let f = program.functions.get(fi)?;
4102    f.return_type
4103        .as_ref()
4104        .and_then(kind::boundary_to_kind)
4105        .or_else(|| f.ret_kind.map(Kind::from_slot))
4106}
4107
4108/// The maximal closure ranges contained in `[start, end)` (the DIRECT inline-closure children of a
4109/// region) — a closure nested inside another closure is excised with its parent, not here.
4110fn child_holes(closure_ranges: &[(usize, usize)], start: usize, end: usize) -> Vec<(usize, usize)> {
4111    closure_ranges
4112        .iter()
4113        .copied()
4114        .filter(|&(e, t)| {
4115            e >= start
4116                && t <= end
4117                && (e, t) != (start, end)
4118                && !closure_ranges.iter().any(|&(e2, t2)| {
4119                    (e2, t2) != (e, t) && e2 <= e && t <= t2 && e2 >= start && t2 <= end
4120                })
4121        })
4122        .collect()
4123}
4124
4125/// Extract one wasm function's op slice from `code[start..end)`: drop the `holes` (inline closure
4126/// bodies, each a separate wasm function) and rebase every jump-like target to the kept ops'
4127/// 0-based indices. A target that escapes the region or lands inside a hole is a hard error.
4128fn extract_region(code: &[Op], start: usize, end: usize, holes: &[(usize, usize)]) -> R<Vec<Op>> {
4129    let in_hole = |pc: usize| holes.iter().any(|&(s, e)| pc >= s && pc < e);
4130    let mut new_index = vec![usize::MAX; end];
4131    let mut kept = Vec::new();
4132    for pc in start..end {
4133        if !in_hole(pc) {
4134            new_index[pc] = kept.len();
4135            kept.push(pc);
4136        }
4137    }
4138    let rebase = |t: usize| -> R<usize> {
4139        if t >= start && t < end && new_index[t] != usize::MAX {
4140            Ok(new_index[t])
4141        } else {
4142            Err(WasmLowerError::Unsupported(
4143                "jump target escapes the function",
4144            ))
4145        }
4146    };
4147    let mut ops = Vec::with_capacity(kept.len());
4148    for &pc in &kept {
4149        ops.push(match code[pc] {
4150            Op::Jump { target } => Op::Jump {
4151                target: rebase(target)?,
4152            },
4153            Op::JumpIfFalse { cond, target } => Op::JumpIfFalse {
4154                cond,
4155                target: rebase(target)?,
4156            },
4157            Op::JumpIfTrue { cond, target } => Op::JumpIfTrue {
4158                cond,
4159                target: rebase(target)?,
4160            },
4161            Op::IterNext { dst, exit } => Op::IterNext {
4162                dst,
4163                exit: rebase(exit)?,
4164            },
4165            other => other,
4166        });
4167    }
4168    Ok(ops)
4169}
4170
4171/// Plan the synthesized top-level `main`: `code[0 .. main_end)` with inline closure bodies excised,
4172/// the Main register frame, no parameters, void result (it ends in `Halt`).
4173fn plan_main(
4174    program: &CompiledProgram,
4175    layout: &CodeLayout,
4176    ret_of: &dyn Fn(usize) -> Option<Kind>,
4177    global_of: &dyn Fn(u16) -> Option<Kind>,
4178    closure_ret: &dyn Fn(usize) -> Option<Kind>,
4179    ret_layout: &dyn Fn(u16) -> Option<FieldLayout>,
4180    fn_return_closure: &dyn Fn(u16) -> Option<u16>,
4181    global_layout: &dyn Fn(u16) -> Option<FieldLayout>,
4182    global_declared: &dyn Fn(u16) -> Option<BoundaryType>,
4183    linked: bool,
4184) -> R<Plan> {
4185    let holes = child_holes(&layout.closure_ranges, 0, layout.main_end);
4186    let ops = extract_region(&program.code, 0, layout.main_end, &holes)?;
4187    let num_regs = program.register_count as u32;
4188    // Split any register the VM reused across disjoint live ranges of conflicting wasm types into one
4189    // local per range (Main has no parameters to pin). Identity unless a real conflict exists.
4190    let (mut ops, num_regs, placed) = regsplit::split_registers(&ops, num_regs, 0, &program.functions);
4191    let fn_return_types = fn_return_types(program);
4192    // Main has no parameters, but its values have DECLARED types — an empty `a new Seq of Todo`
4193    // has no element to trace, and a loop over it must still resolve a field. Fed through the same
4194    // seed channels a parameter uses, because it is the same fact.
4195    let mut main_kind_seeds: Vec<Option<Kind>> = vec![None; num_regs as usize];
4196    let mut main_seeds: Vec<(u16, ParamShape)> = Vec::new();
4197    let main_declared = seed_declarations(
4198        program,
4199        &ops,
4200        &region_declarations(program, 0, layout.main_end, &holes, &placed),
4201        &mut main_kind_seeds,
4202        &mut main_seeds,
4203    );
4204    let (kinds, _pc_reach, reachable_blocks) = infer_with_reachability(
4205        &ops,
4206        &program.constants,
4207        &program.struct_types,
4208        &program.enum_types,
4209        &fn_return_types,
4210        num_regs as usize,
4211        &main_kind_seeds,
4212        ret_of,
4213        global_of,
4214        closure_ret,
4215        ret_layout,
4216        fn_return_closure,
4217        &main_seeds,
4218        &[],
4219        global_layout,
4220        global_declared,
4221        linked,
4222        &program.functions,
4223        &[],
4224    )?;
4225    let structs = kind::struct_layout(
4226        &ops,
4227        &program.constants,
4228        &program.struct_types,
4229        &program.enum_types,
4230        &fn_return_types,
4231        ret_layout,
4232        fn_return_closure,
4233        &main_seeds,
4234        &[],
4235        global_layout,
4236        global_declared,
4237        &main_declared,
4238    );
4239    let cow_inserts = cow_struct_inserts(&ops, &kinds, num_regs, &program.functions);
4240    let reg_shape = complete_reg_shape(&structs, &kinds, program);
4241    let iter_iterable = kind::iter_pairing(&ops);
4242    let place = PlaceSites::of(&ops, &program.constants, &program.functions);
4243    let transient = transient_reads(&ops, num_regs, &program.functions);
4244    let declared = declared_registers(&structs, main_declared, &[]);
4245    let range_loops = range_loop_registers(&ops, &program.functions);
4246    if linked {
4247        accumulate_as_add(&mut ops, &kinds);
4248    }
4249    let mut plan = Plan {
4250        range_loops,
4251        ops,
4252        kinds,
4253        num_params: 0,
4254        num_regs,
4255        result: None,
4256        reachable_blocks,
4257        structs,
4258        cow_inserts,
4259        reg_shape,
4260        return_closure: None,
4261        iter_iterable,
4262        place,
4263        transient,
4264        declared,
4265        inout: Vec::new(),
4266        exact: Vec::new(),
4267        params_tagged: Vec::new(),
4268        ret_tagged: false,
4269        absence: false,
4270        absence_regs: Vec::new(),
4271        absence_globals: Vec::new(),
4272        tower: tower::Towers::default(),
4273        stub: false,
4274    };
4275    tower::settle(&mut plan, program, linked)?;
4276    Ok(plan)
4277}
4278
4279/// Linker mode: `Set x to x + y` on a number the runtime holds — a rational, a big integer, a complex number, a
4280/// residue, a decimal, money, a quantity — is the sum an `Add` computes; the bytecode's in-place `AddAssign` names
4281/// the same value, so it lowers as that `Add`, with that `Add`'s imports.
4282fn accumulate_as_add(ops: &mut [Op], kinds: &KindTable) {
4283    for op in ops.iter_mut() {
4284        if let Op::AddAssign { dst, src } = *op {
4285            if matches!(
4286                kinds.get(dst as usize),
4287                Some(
4288                    Kind::Rational
4289                        | Kind::BigInt
4290                        | Kind::Complex
4291                        | Kind::Modular
4292                        | Kind::Decimal
4293                        | Kind::Money
4294                        | Kind::Quantity
4295                )
4296            ) {
4297                *op = Op::Add {
4298                    dst,
4299                    lhs: dst,
4300                    rhs: src,
4301                };
4302            }
4303        }
4304    }
4305}
4306
4307/// Each function's declared RETURN type, indexed by function index — for typing a caller's inline use
4308/// of a returned composite (`item k of f()`, `Inspect f()`).
4309fn fn_return_types(program: &CompiledProgram) -> Vec<Option<BoundaryType>> {
4310    program
4311        .functions
4312        .iter()
4313        .map(|f| f.return_type.clone())
4314        .collect()
4315}
4316
4317/// Complete a plan's per-register access SHAPE: `struct_layout`'s `reg_shape` (parameter + cross-region
4318/// + locally-built struct, all kind-free) EXTENDED with locally-built map / enum / heterogeneous-tuple
4319/// shapes — which need the inferred register kinds, unavailable inside `struct_layout`. A param shape
4320/// already present is never overridden. A captured local-built composite then resolves like any other.
4321fn complete_reg_shape(
4322    structs: &kind::StructLayout,
4323    kinds: &KindTable,
4324    program: &CompiledProgram,
4325) -> std::collections::HashMap<u16, ParamShape> {
4326    let mut out = structs.reg_shape.clone();
4327    for (reg, value_reg) in &structs.map_set_value {
4328        if !out.contains_key(reg) {
4329            if let Some(vk) = kinds.get(*value_reg as usize) {
4330                // No declared layout here, and none needed: a map BUILT in this region resolves a
4331                // field on its values through the register that wrote them (`map_value`), which is
4332                // the path that always worked. The layout slot exists for the two cases that have
4333                // no such register — a map PARAMETER and a map GLOBAL.
4334                let key = structs
4335                    .map_set_key
4336                    .get(reg)
4337                    .and_then(|k| kinds.get(*k as usize));
4338                out.insert(
4339                    *reg,
4340                    ParamShape::Map {
4341                        key,
4342                        value: vk,
4343                        layout: None,
4344                    },
4345                );
4346            }
4347        }
4348    }
4349    for (reg, elems) in &structs.tuple_layouts {
4350        if !out.contains_key(reg) {
4351            if let Some(ks) = elems
4352                .iter()
4353                .map(|e| kinds.get(*e as usize))
4354                .collect::<Option<Vec<Kind>>>()
4355            {
4356                // Heterogeneous only — a homogeneous tuple lays out as a self-describing `Seq`.
4357                if !ks.windows(2).all(|w| w[0] == w[1]) {
4358                    out.insert(*reg, ParamShape::Tuple(ks));
4359                }
4360            }
4361        }
4362    }
4363    for (reg, name) in &structs.ind_type_of {
4364        if !out.contains_key(reg) {
4365            if let Some(shape) = kind::enum_shape_of_name(name, &program.enum_types) {
4366                out.insert(*reg, ParamShape::Enum(shape));
4367            }
4368        }
4369    }
4370    out
4371}
4372
4373/// Each closure's captured VALUE kinds (by function index, then capture index), read from where the
4374/// closure is BUILT (`MakeClosure`) — in Main or a non-closure function (the `region_plans`, by
4375/// function index; closures are `None` there). A captured GLOBAL resolves via `global_of`; a captured
4376/// LOCAL from the enclosing region's inferred register kind. A capture not reachable here (e.g. one
4377/// built inside another closure body, which this pre-pass doesn't plan) stays `None` → seeded `Int`,
4378/// so a composite such capture rejects soundly rather than miscompiling.
4379fn extract_capture_kinds(
4380    program: &CompiledProgram,
4381    main_p1: &Plan,
4382    region_plans: &[Option<Plan>],
4383    global_of: &dyn Fn(u16) -> Option<Kind>,
4384    global_closure_of: &dyn Fn(u16) -> Option<u16>,
4385) -> (
4386    Vec<Vec<Option<Kind>>>,
4387    Vec<Vec<Option<ParamShape>>>,
4388    Vec<Vec<Option<u16>>>,
4389) {
4390    let mut kinds: Vec<Vec<Option<Kind>>> = program
4391        .functions
4392        .iter()
4393        .map(|f| {
4394            f.captures
4395                .iter()
4396                .map(|(_, g)| g.and_then(|gi| global_of(gi)))
4397                .collect()
4398        })
4399        .collect();
4400    let mut shapes: Vec<Vec<Option<ParamShape>>> = program
4401        .functions
4402        .iter()
4403        .map(|f| vec![None; f.captures.len()])
4404        .collect();
4405    // Per closure fi, per capture k: the body function index of a captured CLOSURE value (so calling
4406    // the captured closure resolves — closure composition like `(n) -> add1(add1(n))`). A captured
4407    // GLOBAL closure (a Main-`Let` closure promoted to a global) is resolved here; a captured LOCAL
4408    // closure is filled from the build-site `closure_of` in the loop below.
4409    let mut closures: Vec<Vec<Option<u16>>> = program
4410        .functions
4411        .iter()
4412        .map(|f| {
4413            f.captures
4414                .iter()
4415                .map(|(_, g)| g.and_then(|gi| global_closure_of(gi)))
4416                .collect()
4417        })
4418        .collect();
4419    for plan in std::iter::once(main_p1).chain(region_plans.iter().flatten()) {
4420        for op in &plan.ops {
4421            if let Op::MakeClosure {
4422                func, locals_start, ..
4423            } = *op
4424            {
4425                let fi = func as usize;
4426                let mut local_k: u16 = 0;
4427                for (k, (_sym, global)) in program.functions[fi].captures.iter().enumerate() {
4428                    if global.is_none() {
4429                        let reg = locals_start + local_k;
4430                        local_k += 1;
4431                        if let Some(kind) = plan.kinds.get(reg as usize) {
4432                            kinds[fi][k] = Some(kind);
4433                        }
4434                        // A captured composite's SHAPE comes from the enclosing region's unified
4435                        // `reg_shape` at the capture register — covering a function PARAMETER (struct/
4436                        // map/enum/het-tuple) and a locally-built struct, so the closure body resolves
4437                        // `capturedstruct's field` / `item k of capturedmap` / `Inspect capturedenum`
4438                        // exactly as a composite parameter does.
4439                        if let Some(shape) = plan.reg_shape.get(&reg) {
4440                            shapes[fi][k] = Some(shape.clone());
4441                        }
4442                        // A captured CLOSURE value: its statically-traced body function index at the
4443                        // build site, so the closure body can `call_indirect` the captured closure.
4444                        if let Some(&c) = plan.structs.closure_of.get(&reg) {
4445                            closures[fi][k] = Some(c);
4446                        }
4447                    }
4448                }
4449            }
4450        }
4451    }
4452    (kinds, shapes, closures)
4453}
4454
4455/// Plan `program.functions[fi]`: extract its region (regular functions are the appended tail; a
4456/// closure body is its inline `[entry, jover_target)` slice), excise any inline closures nested
4457/// inside it, rebase jump targets to 0-based, seed parameter kinds, infer register kinds, and
4458/// resolve its result kind (the declared `ret_kind`, else inferred from its `Return` operands).
4459/// A *capturing* closure (one that reads an enclosing local) needs the capture ABI and is deferred.
4460#[allow(clippy::too_many_arguments)]
4461fn plan_function(
4462    program: &CompiledProgram,
4463    fi: usize,
4464    layout: &CodeLayout,
4465    ret_of: &dyn Fn(usize) -> Option<Kind>,
4466    global_of: &dyn Fn(u16) -> Option<Kind>,
4467    closure_ret: &dyn Fn(usize) -> Option<Kind>,
4468    ret_layout: &dyn Fn(u16) -> Option<FieldLayout>,
4469    fn_return_closure: &dyn Fn(u16) -> Option<u16>,
4470    global_layout: &dyn Fn(u16) -> Option<FieldLayout>,
4471    global_declared: &dyn Fn(u16) -> Option<BoundaryType>,
4472    param_origin: &dyn Fn(usize, usize) -> Option<u16>,
4473    exact_param: &dyn Fn(usize, usize) -> bool,
4474    capture_kinds: &[Vec<Option<Kind>>],
4475    capture_shapes: &[Vec<Option<ParamShape>>],
4476    capture_closures: &[Vec<Option<u16>>],
4477    strict: bool,
4478    linked: bool,
4479) -> R<Plan> {
4480    let f = &program.functions[fi];
4481    let (start, end) = layout.func_region[fi];
4482    if start >= end || end > program.code.len() {
4483        return Err(WasmLowerError::Unsupported("malformed function bounds"));
4484    }
4485    let holes = child_holes(&layout.closure_ranges, start, end);
4486    let ops = extract_region(&program.code, start, end, &holes)?;
4487
4488    // A capturing closure body receives, after its real parameters, each capture's VALUE and a
4489    // present-FLAG (regs `p..p+cap_n` and `p+cap_n..p+2·cap_n`; see `CallValue`'s frame setup).
4490    // Real params + flags are Int by the closure contract; each capture VALUE is typed by its source
4491    // kind (`capture_kinds[fi]`, computed once from the `MakeClosure` site — a captured global's kind
4492    // or a captured local's enclosing-region kind), so closing over a composite (a `Seq`/`Map`/struct/
4493    // … handle) works whether it's global or function-local. `CallValue` passes them; `MakeClosure`
4494    // fills the closure object they are loaded from. A non-capturing function uses its declared kinds.
4495    let cap_n = f.captures.len() as u32;
4496    let num_params = f.param_count as u32 + 2 * cap_n;
4497    let mut seeds: Vec<Option<Kind>> = if cap_n > 0 {
4498        let mut s = vec![Some(Kind::Int); num_params as usize];
4499        // Real params take their DECLARED kind (a `(n: Float)` capturing closure must seed `n` as f64,
4500        // not the all-Int flag/entry-guard default) — the capturing-closure analog of the non-capturing
4501        // `function_param_seeds`. Capture VALUES then take their source kind; the present-FLAGS stay Int.
4502        for i in 0..f.param_count as usize {
4503            if let Some(Some(bt)) = f.param_types.get(i) {
4504                if let Some(k) = kind::boundary_to_kind(bt) {
4505                    s[i] = Some(k);
4506                }
4507            }
4508        }
4509        let caps = capture_kinds.get(fi).map(|v| v.as_slice()).unwrap_or(&[]);
4510        for k in 0..f.captures.len() {
4511            if let Some(kind) = caps.get(k).copied().flatten() {
4512                s[f.param_count as usize + k] = Some(kind);
4513            }
4514        }
4515        s
4516    } else {
4517        kind::function_param_seeds(f)
4518    };
4519    // A parameter some call hands a value of the exact extension holds one ([`exact_arguments`]), as a value of
4520    // another kind lands in a register that holds one.
4521    for (i, seed) in seeds.iter_mut().enumerate().take(f.param_count as usize) {
4522        if exact_param(fi, i) && seed.map_or(true, Kind::lands_in_tower) {
4523            *seed = Some(Kind::Tower);
4524        }
4525    }
4526    let num_regs = f.register_count as u32;
4527    // Split any register reused across disjoint live ranges of conflicting wasm types; parameters
4528    // (and capture/range members) are pinned so the function signature and range operands are
4529    // untouched. Identity unless a real conflict exists.
4530    let (mut ops, num_regs, placed) =
4531        regsplit::split_registers(&ops, num_regs, num_params, &program.functions);
4532    // Struct PARAMETERS' field layouts, resolved from the bytecode's `struct_types` — so `p's field`
4533    // resolves inside a `f(p: Point)` body (parameters are pinned by the splitter, so their registers
4534    // are unchanged). Only non-capturing functions have declared parameter types.
4535    let mut param_layouts = if cap_n == 0 {
4536        param_seeds(f, program)
4537    } else {
4538        Vec::new()
4539    };
4540    // ★ WHAT THE FUNCTION DECLARES IT RETURNS is what every `Return` hands back — the operand of each
4541    // takes that kind, so a value whose kind nothing in the body shows (a generic `T` monomorphized to
4542    // `Int`, a field read the backend could not type) still returns at the declared width.
4543    if let Some(k) = f.return_type.as_ref().and_then(kind::boundary_to_kind) {
4544        for op in &ops {
4545            if let Op::Return { src } = *op {
4546                if seeds.len() <= src as usize {
4547                    seeds.resize(src as usize + 1, None);
4548                }
4549                seeds[src as usize].get_or_insert(k);
4550            }
4551        }
4552    }
4553    // ★ AND EVERY VALUE THE BODY DECLARES: its kind (what an empty `a new Seq of Text` lacks), and
4554    // its shape where it has one (a `Seq of <record>`'s row layout, a `Map`'s value kind).
4555    let body_declared = seed_declarations(
4556        program,
4557        &ops,
4558        &region_declarations(program, start, end, &holes, &placed),
4559        &mut seeds,
4560        &mut param_layouts,
4561    );
4562    // A capture of a composite GLOBAL is typed with that global's SHAPE (the capture analog of a
4563    // composite parameter), so `item k of capturedmap` / `capturedstruct's field` / `Inspect
4564    // capturedenum` resolve in the closure body. The capture VALUE register (after the real params)
4565    // already has the right Kind seed; this adds its layout/value-kind/variant resolution.
4566    let local_shapes = capture_shapes.get(fi).map(|v| v.as_slice()).unwrap_or(&[]);
4567    for (k, (_sym, global)) in f.captures.iter().enumerate() {
4568        let shape = if let Some(gidx) = global {
4569            // A captured GLOBAL composite is typed by the global's resolved type (`global_types`).
4570            program
4571                .global_types
4572                .get(*gidx as usize)
4573                .and_then(|t| t.as_ref())
4574                .and_then(|bt| boundary_to_param_shape(bt, program))
4575        } else {
4576            // A captured LOCAL composite is typed by its shape read from the enclosing region's plan.
4577            local_shapes.get(k).cloned().flatten()
4578        };
4579        if let Some(shape) = shape {
4580            param_layouts.push((f.param_count + k as u16, shape));
4581        }
4582    }
4583    // A closure PARAMETER whose single statically-known origin a whole-program pass resolved: its
4584    // register (= the param index, pinned by the splitter) is pre-bound to that closure body, so
4585    // `f(args)` inside this function resolves its callee like a returned/local closure (closures as
4586    // arguments). Only the real params (`0..param_count`) — captures/flags are never closure args.
4587    let mut param_closures: Vec<(u16, u16)> = (0..f.param_count)
4588        .filter_map(|i| param_origin(fi, i as usize).map(|c| (i, c)))
4589        .collect();
4590    // A captured CLOSURE value (register `param_count + k`) is bound to its traced body function, so
4591    // calling the captured closure resolves its callee like a local one — closure composition.
4592    if let Some(caps) = capture_closures.get(fi) {
4593        for (k, c) in caps.iter().enumerate() {
4594            if let Some(c) = c {
4595                param_closures.push((f.param_count + k as u16, *c));
4596            }
4597        }
4598    }
4599    // A closure PARAMETER carries an i32 handle, not the i64 its `Closure` declared type would otherwise
4600    // seed (there is no `BoundaryType::Closure`). The origin pass already proved this param IS a closure,
4601    // so type it `Kind::Closure` — the closure-handle argument then matches and lowers/loads as i32.
4602    for &(reg, _) in &param_closures {
4603        if let Some(slot) = seeds.get_mut(reg as usize) {
4604            *slot = Some(Kind::Closure);
4605        }
4606    }
4607    // A CHANNEL PARAMETER (`Launch a task to worker with ch` passes a `Pipe of T` into `worker(ch: T)`)
4608    // is declared with its ELEMENT scalar type `T`, so `function_param_seeds` seeds `ch` as the scalar
4609    // `Kind::T` (an i64/f64). But the AOT models a channel as a Seq HANDLE (i32): every `Receive`/`Send`/
4610    // select recv-arm on `ch` uses it as a `chan` operand, and the caller passes the channel's i32
4611    // handle. Re-seed such a param to the channel's Seq kind (from its declared element) so the param
4612    // valtype matches the argument and the body's channel ops resolve — the wasm analog of the C tier's
4613    // channel-index param (`emit.rs`: a `Pipe of Int` param is live as the channel handle, not an Int).
4614    for reg in channel_param_regs(&ops, f.param_count) {
4615        if let Some(slot) = seeds.get_mut(reg as usize) {
4616            let seq = f
4617                .param_types
4618                .get(reg as usize)
4619                .and_then(|t| t.as_ref())
4620                .and_then(chan_param_seq_kind);
4621            if let Some(seq) = seq {
4622                *slot = Some(seq);
4623            }
4624        }
4625    }
4626    let fn_rt = fn_return_types(program);
4627    let (kinds, pc_reach, reachable_blocks) = infer_with_reachability(
4628        &ops,
4629        &program.constants,
4630        &program.struct_types,
4631        &program.enum_types,
4632        &fn_rt,
4633        num_regs as usize,
4634        &seeds,
4635        ret_of,
4636        global_of,
4637        closure_ret,
4638        ret_layout,
4639        fn_return_closure,
4640        &param_layouts,
4641        &param_closures,
4642        global_layout,
4643        global_declared,
4644        linked,
4645        &program.functions,
4646        &f.mutable_param_regs,
4647    )?;
4648
4649    // Result kind: the declared `ret_kind` (a scalar `SlotKind`) when present, EXCEPT a non-scalar
4650    // (handle) return — a `-> Point` etc. — cannot be a `SlotKind`, so its `ret_kind` defaults to
4651    // Int; the inferred kind (from the `Return` operands) then wins on a value-type disagreement.
4652    let inferred = infer_result(&ops, &kinds, &pc_reach, strict)?;
4653    let result = match (f.ret_kind.map(Kind::from_slot), inferred) {
4654        (Some(d), Some(i)) if d.wasm_valtype() != i.wasm_valtype() => Some(i),
4655        (Some(d), _) => Some(d),
4656        (None, i) => i,
4657    };
4658    let structs = kind::struct_layout(
4659        &ops,
4660        &program.constants,
4661        &program.struct_types,
4662        &program.enum_types,
4663        &fn_rt,
4664        ret_layout,
4665        fn_return_closure,
4666        &param_layouts,
4667        &param_closures,
4668        global_layout,
4669        global_declared,
4670        &body_declared,
4671    );
4672    let cow_inserts = cow_struct_inserts(&ops, &kinds, num_regs, &program.functions);
4673    let reg_shape = complete_reg_shape(&structs, &kinds, program);
4674    let return_closure = infer_return_closure(&ops, &kinds, &structs, &pc_reach);
4675    let iter_iterable = kind::iter_pairing(&ops);
4676    let place = PlaceSites::of(&ops, &program.constants, &program.functions);
4677    let transient = transient_reads(&ops, num_regs, &program.functions);
4678    let declared = declared_registers(&structs, body_declared, &f.param_types);
4679    let range_loops = range_loop_registers(&ops, &program.functions);
4680    let inout: Vec<u16> = f
4681        .mutable_param_regs
4682        .iter()
4683        .copied()
4684        .filter(|p| u32::from(*p) < num_params as u32)
4685        .collect();
4686    if !inout.is_empty() && !f.captures.is_empty() {
4687        return Err(WasmLowerError::Unsupported(
4688            "a function value's body with a `mutable` parameter",
4689        ));
4690    }
4691    if linked {
4692        accumulate_as_add(&mut ops, &kinds);
4693    }
4694    let mut plan = Plan {
4695        range_loops,
4696        ops,
4697        kinds,
4698        num_params,
4699        num_regs,
4700        result,
4701        reachable_blocks,
4702        structs,
4703        cow_inserts,
4704        reg_shape,
4705        return_closure,
4706        iter_iterable,
4707        place,
4708        transient,
4709        declared,
4710        inout,
4711        exact: Vec::new(),
4712        params_tagged: Vec::new(),
4713        ret_tagged: false,
4714        absence: false,
4715        absence_regs: Vec::new(),
4716        absence_globals: Vec::new(),
4717        tower: tower::Towers::default(),
4718        stub: false,
4719    };
4720    tower::settle(&mut plan, program, linked)?;
4721    Ok(plan)
4722}
4723
4724/// Parameter registers (`0..num_params`) USED as a channel operand anywhere in the body — the `chan`
4725/// side of a `Send`/`Receive`/`Try to send`/`Try to receive`/`Close` or a `select` recv arm. Such a
4726/// param arrived as a `Pipe of T` handle (a Seq in the AOT), not the scalar `T` its declaration seeds,
4727/// so its seed is re-typed to the channel Seq kind (see the call site).
4728fn channel_param_regs(ops: &[Op], num_params: u16) -> Vec<u16> {
4729    let mut regs = Vec::new();
4730    let mut note = |chan: u16| {
4731        if chan < num_params && !regs.contains(&chan) {
4732            regs.push(chan);
4733        }
4734    };
4735    for op in ops {
4736        match op {
4737            Op::ChanSend { chan, .. }
4738            | Op::ChanRecv { chan, .. }
4739            | Op::ChanTrySend { chan, .. }
4740            | Op::ChanTryRecv { chan, .. }
4741            | Op::ChanClose { chan }
4742            | Op::SelectArmRecv { chan, .. } => note(*chan),
4743            _ => {}
4744        }
4745    }
4746    regs
4747}
4748
4749/// The Seq handle kind an AOT channel of declared element type `bt` presents — the parameter-seed
4750/// counterpart of `kind::infer`'s `ChanNew` element→seq mapping. Bool rides the `SeqInt` i64-0/1
4751/// layout; an element with no self-describing seq kind leaves the param unmodeled (`None`).
4752fn chan_param_seq_kind(bt: &BoundaryType) -> Option<Kind> {
4753    Some(match bt {
4754        BoundaryType::Int | BoundaryType::Bool => Kind::SeqInt,
4755        BoundaryType::Float => Kind::SeqFloat,
4756        BoundaryType::Text => Kind::SeqText,
4757        _ => return None,
4758    })
4759}
4760
4761/// WHICH closure (body function index) this function returns, if any — the closure-valued analog of
4762/// [`fn_return_struct_layout`]. Scans REACHABLE closure-typed `Return`s (a nested closure's inline
4763/// body is unreachable here, so its `Return` is ignored); yields `Some(c)` iff they all agree on the
4764/// same statically-traced origin `c` (via `closure_of`, which is `Move`-aliased). `None` if it
4765/// returns no closure or more than one — a caller then cannot resolve a `CallValue` on the result.
4766fn infer_return_closure(
4767    ops: &[Op],
4768    kinds: &KindTable,
4769    structs: &kind::StructLayout,
4770    pc_reach: &[bool],
4771) -> Option<u16> {
4772    let mut found: Option<u16> = None;
4773    for (pc, op) in ops.iter().enumerate() {
4774        if !pc_reach.get(pc).copied().unwrap_or(true) {
4775            continue;
4776        }
4777        if let Op::Return { src } = *op {
4778            if kinds.get(src as usize) != Some(Kind::Closure) {
4779                continue;
4780            }
4781            match structs.closure_of.get(&src) {
4782                Some(&c) if found.is_none() => found = Some(c),
4783                Some(&c) if found == Some(c) => {}
4784                _ => return None,
4785            }
4786        }
4787    }
4788    found
4789}
4790
4791/// WHICH closure each function PARAMETER is always passed — the param-side, whole-program analog of
4792/// [`infer_return_closure`]. For every `Call`/`CallValue` in every planned region, attribute each
4793/// argument register's statically-traced closure origin (the caller's `closure_of`) to the callee's
4794/// matching parameter index. A parameter is bound to closure `c` iff EVERY observed call passes that
4795/// same `c` and nothing else; any disagreement (a different closure, or an untraced argument) yields
4796/// `None`, so a genuinely polymorphic / opaque closure parameter stays soundly rejected. Result
4797/// indexed `[fi][param_idx]`. Lets `f(args)` resolve its callee when `f` is a closure ARGUMENT.
4798/// `plans` is every region to scan (Main + the planned functions).
4799/// Mark in `exact` every parameter some direct call in `plans` hands a value of the exact extension, so the callee
4800/// holds one there; answers whether a mark is new. Marks only accumulate: a parameter that once received one is
4801/// planned holding one for good.
4802fn exact_arguments(program: &CompiledProgram, plans: &[&Plan], exact: &mut [Vec<bool>]) -> bool {
4803    let mut grew = false;
4804    for plan in plans {
4805        for op in &plan.ops {
4806            let (func, args_start, arg_count) = match *op {
4807                Op::Call {
4808                    func,
4809                    args_start,
4810                    arg_count,
4811                    ..
4812                }
4813                | Op::Spawn {
4814                    func,
4815                    args_start,
4816                    arg_count,
4817                }
4818                | Op::SpawnHandle {
4819                    func,
4820                    args_start,
4821                    arg_count,
4822                    ..
4823                } => (func as usize, args_start, arg_count),
4824                _ => continue,
4825            };
4826            let params = program.functions.get(func).map_or(0, |f| f.param_count);
4827            for i in 0..arg_count.min(params) {
4828                if plan.kinds.get((args_start + i) as usize) == Some(Kind::Tower) {
4829                    if let Some(mark) = exact.get_mut(func).and_then(|v| v.get_mut(i as usize)) {
4830                        grew |= !*mark;
4831                        *mark = true;
4832                    }
4833                }
4834            }
4835        }
4836    }
4837    grew
4838}
4839
4840fn compute_param_origins(program: &CompiledProgram, plans: &[&Plan]) -> Vec<Vec<Option<u16>>> {
4841    use std::collections::{HashMap, HashSet};
4842    let mut obs: HashMap<(usize, usize), HashSet<Option<u16>>> = HashMap::new();
4843    for plan in plans {
4844        for (pc, op) in plan.ops.iter().enumerate() {
4845            let (func, args_start, arg_count) = match *op {
4846                Op::Call {
4847                    func,
4848                    args_start,
4849                    arg_count,
4850                    ..
4851                } => (Some(func as usize), args_start, arg_count),
4852                Op::CallValue {
4853                    args_start,
4854                    arg_count,
4855                    ..
4856                } => (
4857                    plan.structs
4858                        .callee_func
4859                        .get(pc)
4860                        .copied()
4861                        .flatten()
4862                        .map(|f| f as usize),
4863                    args_start,
4864                    arg_count,
4865                ),
4866                _ => continue,
4867            };
4868            let Some(func) = func else { continue };
4869            for i in 0..arg_count {
4870                let origin = plan.structs.closure_of.get(&(args_start + i)).copied();
4871                obs.entry((func, i as usize)).or_default().insert(origin);
4872            }
4873        }
4874    }
4875    (0..program.functions.len())
4876        .map(|fi| {
4877            let pc = program.functions[fi].param_count as usize;
4878            (0..pc)
4879                .map(|i| match obs.get(&(fi, i)) {
4880                    Some(set) if set.len() == 1 => set.iter().next().copied().flatten(),
4881                    _ => None,
4882                })
4883                .collect()
4884        })
4885        .collect()
4886}
4887
4888/// Resolve a composite [`BoundaryType`] to its access-resolution [`ParamShape`] — the shared bridge
4889/// used to seed a parameter (its declared type), a closure capture (the captured global's type), or
4890/// any other cross-region composite. `None` for a scalar / self-describing type (no shape needed) or
4891/// one whose layout/kinds don't resolve (the access then stays soundly rejected).
4892fn boundary_to_param_shape(bt: &BoundaryType, program: &CompiledProgram) -> Option<ParamShape> {
4893    match bt {
4894        BoundaryType::Struct(name) => {
4895            kind::resolve_named_layout(name, &program.struct_types, &program.constants)
4896                .map(ParamShape::Struct)
4897        }
4898        // ★ A MAP CARRIES ITS VALUES' LAYOUT when those values are records, so `(item k of m)'s f`
4899        // resolves. Without it a map of records could be indexed and the record could not be read.
4900        BoundaryType::Map(key, value) => kind::boundary_to_kind(value).map(|vk| {
4901            let layout = match value.as_ref() {
4902                BoundaryType::Struct(name) => {
4903                    kind::resolve_named_layout(name, &program.struct_types, &program.constants)
4904                }
4905                _ => None,
4906            };
4907            ParamShape::Map {
4908                key: kind::boundary_to_kind(key),
4909                value: vk,
4910                layout,
4911            }
4912        }),
4913        // A named enum resolves its shape through `enum_types`; a `Result` carries its own. Both
4914        // arrive as one `ParamShape::Enum`, so nothing downstream has to know which it was.
4915        BoundaryType::Enum(_) | BoundaryType::Result(_, _) => {
4916            kind::enum_shape_of(bt, &program.enum_types).map(ParamShape::Enum)
4917        }
4918        BoundaryType::Tuple(elems) => elems
4919            .iter()
4920            .map(kind::boundary_to_kind)
4921            .collect::<Option<Vec<Kind>>>()
4922            .map(ParamShape::Tuple),
4923        // ★ `Seq of <record>` — the ELEMENT's layout, so a loop variable taken out of the list can
4924        // resolve a field. Without it, a function handed a list of records could read no field of
4925        // any row: the layout walk traces where a record was BUILT, and a parameter was not built
4926        // here. Reading a row of a table is the most ordinary thing a program does with one.
4927        BoundaryType::Seq(elem) => match elem.as_ref() {
4928            BoundaryType::Struct(name) => {
4929                kind::resolve_named_layout(name, &program.struct_types, &program.constants)
4930                    .map(ParamShape::SeqOfStruct)
4931            }
4932            _ => None,
4933        },
4934        _ => None,
4935    }
4936}
4937
4938/// Each non-scalar PARAMETER's access-resolution shape (parameter register `i` → [`ParamShape`]),
4939/// from the bytecode's `param_types`/`struct_types`. Seeded into `struct_layout` so `param's field`
4940/// (struct) and `item k of m` (map) resolve like a cross-region access. A struct/map whose layout
4941/// or value kind is unresolvable is simply omitted, leaving the access soundly rejected.
4942fn param_seeds(f: &CompiledFunction, program: &CompiledProgram) -> Vec<(u16, ParamShape)> {
4943    f.param_types
4944        .iter()
4945        .enumerate()
4946        .filter_map(|(i, pt)| {
4947            pt.as_ref()
4948                .and_then(|bt| boundary_to_param_shape(bt, program))
4949                .map(|shape| (i as u16, shape))
4950        })
4951        .collect()
4952}
4953
4954/// Every declaration ([`CompiledProgram::declared_types`]) whose op lies in the region
4955/// `[start, end)` outside `holes`, at that op's index in the region's final op stream: the index
4956/// [`extract_region`] gives it, carried through `placed` ([`regsplit::split_registers`]'s placement
4957/// of each extracted op) — so a declaration names the same op after both as before them.
4958fn region_declarations<'p>(
4959    program: &'p CompiledProgram,
4960    start: usize,
4961    end: usize,
4962    holes: &[(usize, usize)],
4963    placed: &[usize],
4964) -> Vec<(usize, &'p BoundaryType)> {
4965    let first = program
4966        .declared_types
4967        .partition_point(|(pc, _)| (*pc as usize) < start);
4968    program.declared_types[first..]
4969        .iter()
4970        .take_while(|(pc, _)| (*pc as usize) < end)
4971        .filter(|(pc, _)| {
4972            !holes
4973                .iter()
4974                .any(|&(s, e)| (*pc as usize) >= s && (*pc as usize) < e)
4975        })
4976        .filter_map(|(pc, bt)| {
4977            let pc = *pc as usize;
4978            let excised: usize = holes
4979                .iter()
4980                .filter(|&&(s, _)| s < pc)
4981                .map(|&(s, e)| e.min(pc) - s.max(start))
4982                .sum();
4983            Some((*placed.get(pc - start - excised)?, bt))
4984        })
4985        .collect()
4986}
4987
4988/// Seed each declared value's register: its KIND into `kinds` (a declaration the inference has
4989/// not yet refined wins; a register the region already seeds keeps its seed), and its SHAPE into
4990/// `shapes` where the type has one. The register is the one the declaring op defines.
4991fn seed_declarations(
4992    program: &CompiledProgram,
4993    ops: &[Op],
4994    declared: &[(usize, &BoundaryType)],
4995    kinds: &mut Vec<Option<Kind>>,
4996    shapes: &mut Vec<(u16, ParamShape)>,
4997) -> Vec<(usize, u16, BoundaryType)> {
4998    let mut seeded = Vec::new();
4999    for &(at, bt) in declared {
5000        let Some(op) = ops.get(at) else { continue };
5001        let defs = crate::vm::instruction::op_def_uses(op, &program.functions).0;
5002        let [dst] = defs[..] else { continue };
5003        if let Some(k) = kind::boundary_to_kind(bt) {
5004            if kinds.len() <= dst as usize {
5005                kinds.resize(dst as usize + 1, None);
5006            }
5007            kinds[dst as usize].get_or_insert(k);
5008        }
5009        if let Some(shape) = boundary_to_param_shape(bt, program) {
5010            shapes.push((dst, shape));
5011        }
5012        seeded.push((at, dst, bt.clone()));
5013    }
5014    seeded
5015}
5016
5017/// Infer a function's result kind from its `Return` operands (they must agree); `None` (void) if it
5018/// only `ReturnNothing`s or never returns a value. With `strict == false` (the first planning pass),
5019/// a `Return` of a not-yet-known kind is DEFERRED (skipped), not an error — it may resolve in the
5020/// second pass once callee return layouts are threaded (a function returning the result of a
5021/// struct-returning function). The strict (final) pass errors on a genuinely unknown return.
5022fn infer_result(ops: &[Op], kinds: &KindTable, pc_reach: &[bool], strict: bool) -> R<Option<Kind>> {
5023    let mut result = None;
5024    for (pc, op) in ops.iter().enumerate() {
5025        // A nested closure's body is emitted INLINE in this region (its parent jumps over it; it is
5026        // reached only through the closure call into its own separate function). That inline copy is
5027        // unreachable HERE, so its `Return` must not contribute to — or poison — this region's result.
5028        if !pc_reach.get(pc).copied().unwrap_or(true) {
5029            continue;
5030        }
5031        if let Op::Return { src } = *op {
5032            let k = match kinds.get(src as usize) {
5033                Some(k) => k,
5034                None if !strict => continue,
5035                None => {
5036                    return Err(WasmLowerError::Unsupported(
5037                        "return of an unknown-kind value",
5038                    ))
5039                }
5040            };
5041            match result {
5042                None => result = Some(k),
5043                Some(prev) if prev == k => {}
5044                // A `SeqAny` return (an empty `new Seq of T` return path, or a recursive-call result
5045                // not yet refined during the fixpoint) refines to a concrete sibling sequence — the
5046                // same rule `unify_strict` applies to register kinds. So a `mergeSort` returning
5047                // `arr` (SeqInt) on the base case and `result` (SeqAny until the recursion resolves)
5048                // on the recursive case agrees on SeqInt instead of falsely reading as mixed.
5049                Some(Kind::SeqAny) if k.is_seq() => result = Some(k),
5050                Some(prev) if prev.is_seq() && k == Kind::SeqAny => {}
5051                // A function that returns a value of the exact extension on one path returns every value as one.
5052                Some(Kind::Tower) if k.lands_in_tower() => {}
5053                Some(prev) if k == Kind::Tower && prev.lands_in_tower() => result = Some(Kind::Tower),
5054                Some(_) => return Err(WasmLowerError::Unsupported("function returns mixed kinds")),
5055            }
5056        }
5057    }
5058    Ok(result)
5059}
5060
5061/// A function's RETURN struct layout, resolved to `(field name-const-idx, field kind)` — `None`
5062/// unless the function returns a `Struct` whose every field kind is known. Lets a caller resolve
5063/// `f(…)'s field` cross-region (the returned struct is built in this — the callee's — region, so
5064/// its field-defining registers are not visible to the caller; the resolved kinds bridge that).
5065/// The resolved field layout of the record a `GlobalSet` put in a global — the same resolution
5066/// [`fn_return_struct_layout`] does for a returned struct, keyed on the register STORED rather
5067/// than the register returned. The declared type is authoritative: it carries the nested-composite
5068/// info (a Map field's value kind, an enum field's variants) that a nameless `Kind` cannot.
5069fn global_struct_layout(
5070    plan: &Plan,
5071    src: u16,
5072    struct_types: &[StructTypeDef],
5073    constants: &[Constant],
5074) -> Option<FieldLayout> {
5075    if let Some(name) = plan.structs.struct_name_of.get(&src) {
5076        if let Some(layout) = kind::resolve_named_layout(name, struct_types, constants) {
5077            return Some(layout);
5078        }
5079    }
5080    // A locally-built record whose declared type did not resolve: fall back to each field's kind
5081    // from its defining value register, exactly as a returned struct does.
5082    if let Some(layout) = plan.structs.reg_layout.get(&src) {
5083        return local_field_layout(plan, layout);
5084    }
5085    plan.structs.call_result.get(&src).cloned()
5086}
5087
5088/// A locally-built record's layout resolved from the registers that filled each slot — the fallback
5089/// for a record with no resolvable declaration. A field's inner shape comes from what the register
5090/// that filled it was declared as (`a new Seq of Note`, a typed parameter), else a struct-typed field
5091/// is named from the plan's `struct_name_of`; anything else stays [`FieldNested::None`], its inner
5092/// shape unrecoverable from a nameless `Kind`. `None` unless every slot was filled with a value of
5093/// known kind.
5094fn local_field_layout(plan: &Plan, layout: &kind::LocalLayout) -> Option<FieldLayout> {
5095    layout
5096        .iter()
5097        .map(|&(f, vr)| {
5098            let vr = vr?;
5099            let k = plan.kinds.get(vr as usize)?;
5100            let nested = match (
5101                k,
5102                plan.declared.get(&vr),
5103                plan.structs.struct_name_of.get(&vr),
5104            ) {
5105                (_, Some(t), _) => kind::nested_of(t),
5106                (Kind::Struct, None, Some(name)) => FieldNested::Struct(name.clone()),
5107                _ => FieldNested::None,
5108            };
5109            Some((f, k, nested))
5110        })
5111        .collect()
5112}
5113
5114fn fn_return_struct_layout(
5115    plan: &Plan,
5116    struct_types: &[StructTypeDef],
5117    constants: &[Constant],
5118) -> Option<FieldLayout> {
5119    for op in &plan.ops {
5120        if let Op::Return { src } = *op {
5121            if plan.kinds.get(src as usize) == Some(Kind::Struct) {
5122                // A locally-built struct with a KNOWN declared type: publish its DECLARED field layout
5123                // (from the struct type), which carries the full nested-composite info — a `Map`/`Enum`/
5124                // `Tuple` field's value kind / variant set / positional kinds. This is what lets a caller
5125                // resolve a `When V (binds)` on `f(…)'s enumfield` or `item k of (f(…)'s mapfield)`: the
5126                // returned struct's own value registers are in the callee's region (nameless `Kind` only),
5127                // so the DECLARED type is the authoritative source for the field's inner shape.
5128                if let Some(name) = plan.structs.struct_name_of.get(&src) {
5129                    if let Some(layout) = kind::resolve_named_layout(name, struct_types, constants)
5130                    {
5131                        return Some(layout);
5132                    }
5133                }
5134                // A LOCALLY-BUILT struct without a resolvable declared type: resolve each field's kind
5135                // from its defining value register ([`local_field_layout`]).
5136                if let Some(layout) = plan.structs.reg_layout.get(&src) {
5137                    return local_field_layout(plan, layout);
5138                }
5139                // A returned struct PARAMETER (or a cross-region call result passed straight through):
5140                // never built here, so it has no `reg_layout`, but its resolved field layout is in
5141                // `call_result` (seeded from the declared struct type / threaded from the callee).
5142                // Publish it verbatim so a caller resolves `f(p)'s field` exactly like a local struct.
5143                if let Some(resolved) = plan.structs.call_result.get(&src) {
5144                    return Some(resolved.clone());
5145                }
5146            }
5147        }
5148    }
5149    None
5150}
5151
5152/// The wasm result-type vector for a function/result kind (`[]` for void, else `[valtype]`).
5153fn result_valtypes(result: Option<Kind>) -> Vec<u8> {
5154    match result {
5155        Some(k) => vec![k.wasm_valtype()],
5156        None => vec![],
5157    }
5158}
5159
5160/// A function's wasm results: its declared result, then each `mutable` parameter's final value ([`Plan::inout`]).
5161fn plan_results(p: &Plan) -> Vec<u8> {
5162    let mut results = result_valtypes(p.result);
5163    results.extend(p.inout.iter().map(|r| p.kinds.valtype(*r as usize)));
5164    results
5165}
5166
5167/// Push each `mutable` parameter's final value, after the declared result, before a function returns.
5168fn push_inout_results(code: &mut Vec<u8>, plan: &Plan) {
5169    for p in &plan.inout {
5170        local_get(code, *p as u32);
5171    }
5172}
5173
5174/// Per-function emission context: the constant pool, how to resolve a host sink's import
5175/// index, and the wasm index of `program.functions[0]` (so `Op::Call { func }` →
5176/// `call (fn_base + func)`).
5177struct Ctx<'a> {
5178    absence_base: Option<u32>,
5179    constants: &'a [Constant],
5180    /// The display function of every composite value shape the module renders as Text.
5181    shown: &'a display::ShownTable,
5182    host_index: &'a dyn Fn(HostFn) -> Option<u32>,
5183    fn_base: u32,
5184    /// The wasm global index of the bump-allocator pointer `__heap_ptr` (the heap value model's
5185    /// linear-memory cursor); it follows the user globals.
5186    heap_global: u32,
5187    /// The wasm global index of the iterator-stack pointer `__iter_sp` (it follows `__heap_ptr`),
5188    /// for `Repeat` iteration. Grows *down* from the top of memory toward the up-growing heap;
5189    /// each live `Repeat` owns one 12-byte frame `[snapshot_ptr:i32][cursor:i32][len:i32]`.
5190    iter_global: u32,
5191    /// A monotonic replica identity independent of reusable heap addresses.
5192    replica_global: Option<u32>,
5193    /// Whether the module iterates at all — whether `__iter_sp` exists.
5194    uses_iter: bool,
5195    /// The wasm type index of each `program.functions[i]` (by function index), so a `CallValue`'s
5196    /// `call_indirect` can name the callee closure body's signature (= that function's own type).
5197    fn_type: &'a [u32],
5198    /// Each `program.functions[i]`'s ACTUAL emitted parameter value types (from its plan), so a direct
5199    /// `Call` matches the real signature — including a `Closure` parameter that lowers to i32, which the
5200    /// declared-type `function_param_seeds` cannot see (there is no `BoundaryType::Closure`).
5201    fn_param_valtypes: &'a [Vec<u8>],
5202    /// Each `program.functions[i]`'s parameter kinds (from its plan), so a direct `Call` hands a parameter that
5203    /// holds a value of the exact extension one ([`tower::push_argument`]).
5204    fn_param_kinds: &'a [Vec<Option<Kind>>],
5205    /// `fn_stubbed[i]` — whether `program.functions[i]` was dropped to a trap stub because it cannot
5206    /// run (`vm::reach`). A call into one sits in live code only where the reach analysis proved it
5207    /// never executes (a page entry's arm for a component nothing draws), so it lowers to a trap.
5208    fn_stubbed: &'a [bool],
5209    /// Each `program.functions[i]`'s result kind (`None` = void) — tells a `CallValue` whether the
5210    /// `call_indirect` leaves a value to bind into its destination.
5211    fn_results: &'a [Option<Kind>],
5212    /// Each function's `mutable` parameters ([`Plan::inout`]): results of the call after its declared one.
5213    fn_inout: &'a [Vec<u16>],
5214    /// Which parameters, results and globals hold tagged words ([`exact`]).
5215    exact: &'a exact::Signatures,
5216    /// The program's functions — `MakeClosure`/`CallValue` read the callee's `captures` (count and
5217    /// each capture's local-register-vs-global source) to fill / pass the closure object.
5218    functions: &'a [crate::vm::instruction::CompiledFunction],
5219    /// Each function's capture VALUE kinds (by function index, then capture index) — a captured
5220    /// global's kind, else `None` (a local capture, stored/loaded as Int). `MakeClosure` stores and
5221    /// `CallValue` loads each capture slot at this kind's width, matching the body's seeded signature.
5222    capture_kinds: &'a [Vec<Option<Kind>>],
5223    /// The program's enum type definitions (variant names + payload field types) — a whole-enum
5224    /// `Show` reads the variant set to emit its tag→name dispatch (`lower_show_enum`).
5225    enum_types: &'a [EnumTypeDef],
5226    /// The program's struct type definitions (field names in declaration order) — a `CheckPolicy`
5227    /// resolves a policy condition's `field` to its slot index via the subject's declared fields.
5228    struct_types: &'a [StructTypeDef],
5229    /// The `## Policy` registry (predicate + capability conditions) — `CheckPolicy` compiles the
5230    /// resolved condition inline (field access + `text_eq` + and/or), trapping when it is false.
5231    policies: &'a PolicyRegistry,
5232    /// The interner, to resolve a policy condition's `Symbol` field/value/predicate names to the
5233    /// strings the struct-field lookup + `text_eq` literal need.
5234    interner: &'a Interner,
5235    /// Every text literal, interned into the data section. `None` in LINKER MODE, where a fixed
5236    /// address would name someone else's bytes and literals are built at run time as before.
5237    text_pool: Option<&'a std::cell::RefCell<TextPool>>,
5238    /// The runtime functions the emitter writes itself — the allocator every allocation site calls,
5239    /// and in an interactive page the release protocol. `None` in LINKER MODE, where allocation goes
5240    /// to the runtime's `dlmalloc` instead.
5241    runtime: Option<&'a Runtime>,
5242    /// Each user global's emitted wasm value type, so a `GlobalSet` can tell a REAL store from the
5243    /// VM's ownership clear (which arrives carrying a different width) and spell the clear at the
5244    /// global's own width. Without it the clear stored an `i64` zero into an `i32` handle global and
5245    /// the module failed to VALIDATE — see the `Op::GlobalSet` arm.
5246    global_valtypes: &'a [u8],
5247    /// Each user global's kind, by global index: what a store into one converts a value to (a value of the exact
5248    /// extension, in linker mode, for a global any region stores one into).
5249    global_kinds: &'a [Option<Kind>],
5250    /// Whether the program builds a `SharedMap` (`NewCrdt` kind 6). Only then can a map carry
5251    /// [`SHARED_MAP_MARK`], so only then do copy-on-write and map insertion test for it.
5252    shared_maps: bool,
5253    /// Linker mode: an integer `Op::Pow` lowers to the `logos_rt_bigint_*` runtime (a `Text` handle)
5254    /// rather than the self-contained i64 exponentiation-by-squaring. Set only by
5255    /// [`assemble_program_linked`]; the standalone emitter leaves it `false`.
5256    linked: bool,
5257    /// Linker mode + emitter heap: the import index of `logos_rt_alloc`. When `Some`, [`emit_alloc`] draws
5258    /// each block straight from the runtime allocator (`dlmalloc`, growing linear memory on demand) rather
5259    /// than a fixed bump slab — so the emitter heap is UNBOUNDED. `None` = the standalone bump path.
5260    rt_alloc: Option<u32>,
5261    /// The wasm global index of the S8 turn-retained list's `data_ptr` (`+1` = `len`, `+2` = `cap`)
5262    /// — `Some` exactly on an interactive, self-contained, heap-using module (mirrors
5263    /// `Runtime::layout`'s `TurnRetain`/`Retain`/`Release`/`Safepoint` gate). [`emit_alloc`] and every
5264    /// true-count call site check `ctx.heap_counting()` (this being `Some`) before emitting anything.
5265    retain_base: Option<u32>,
5266    /// Whether the op being lowered sits inside a loop of its function's bytecode ([`loop_pcs`]).
5267    /// There a sequence read, write or push keeps its mechanism inline — the bounds check and the
5268    /// address, the push's room test, the copy-on-write test — and calls the runtime only for its
5269    /// slow path (a clone, a growth, a trap): measured on V8, a tight loop of calls to
5270    /// `__logos_seq_slot` runs 9–17% slower than the same loop inline. Everywhere else a site is
5271    /// the call.
5272    hot: std::cell::Cell<bool>,
5273    /// Batch loops may collect while user frames are suspended; those frames pin their live values.
5274    batch_reclaim: bool,
5275    /// Per function: whether a call to it can reach a safepoint ([`may_safepoint`]).
5276    may_safepoint: &'a [bool],
5277}
5278
5279impl<'a> Ctx<'a> {
5280    /// Whether this module carries S8's true-count machinery at all — the single gate every new
5281    /// retain/release/turn-list call site checks, so a non-interactive or linked module stays
5282    /// exactly as it was before S8 (batch programs "stay byte-identical", per the plan).
5283    fn heap_counting(&self) -> bool {
5284        self.retain_base.is_some()
5285    }
5286}
5287
5288/// Whether an op terminated its basic block (a branch / return), so the block emitter stops.
5289#[derive(PartialEq, Eq)]
5290enum Flow {
5291    Straight,
5292    Terminated,
5293}
5294
5295/// Per function: whether a call to it can reach a safepoint, the only place a batch module frees anything —
5296/// a loop's back edge in its body, a closure it calls, a builtin it hands a closure, or a call to a function
5297/// that can (a task runs to completion where it is started, so starting one is a call). A call that cannot
5298/// leaves its caller's roots as they are.
5299fn may_safepoint(fns: &[Plan]) -> Vec<bool> {
5300    let direct = |plan: &Plan| {
5301        plan.ops.iter().enumerate().any(|(pc, op)| match *op {
5302            Op::Jump { target }
5303            | Op::JumpIfFalse { target, .. }
5304            | Op::JumpIfTrue { target, .. } => target <= pc,
5305            Op::CallValue { .. } => true,
5306            Op::CallBuiltin {
5307                builtin: BuiltinId::TextFromBytes,
5308                ..
5309            } => true,
5310            Op::CallBuiltin {
5311                args_start,
5312                arg_count,
5313                ..
5314            } => (0..arg_count)
5315                .any(|a| plan.kinds.get((args_start + a) as usize) == Some(Kind::Closure)),
5316            _ => false,
5317        })
5318    };
5319    let mut may: Vec<bool> = fns.iter().map(|p| !p.stub && direct(p)).collect();
5320    loop {
5321        let reaches: Vec<usize> = (0..fns.len())
5322            .filter(|&fi| {
5323                !may[fi]
5324                    && fns[fi].ops.iter().any(|op| {
5325                        matches!(*op, Op::Call { func, .. } | Op::Spawn { func, .. }
5326                            | Op::SpawnHandle { func, .. }
5327                            if may.get(func as usize).copied().unwrap_or(true))
5328                    })
5329            })
5330            .collect();
5331        if reaches.is_empty() {
5332            break;
5333        }
5334        for fi in reaches {
5335            may[fi] = true;
5336        }
5337    }
5338    may
5339}
5340
5341/// Emit one function's complete Code-section entry (its locals declaration followed by the
5342/// dispatch-loop body), from a [`Plan`].
5343fn emit_body(plan: &Plan, _ctx: &Ctx) -> R<Vec<u8>> {
5344    // A dropped (unreachable-from-Main) function: no locals, a lone `unreachable` trap. It is never
5345    // called (that's why it was dropped), so its `() -> ()` type is inert — this just lets the module
5346    // link when an imported stdlib carries functions the AOT can't lower but the program never uses.
5347    if plan.stub {
5348        return Ok(vec![
5349            0x00, /* 0 local groups */
5350            0x00, /* unreachable */
5351            0x0B, /* end */
5352        ]);
5353    }
5354    let ctx = _ctx;
5355    let blocks = Blocks::new(&plan.ops).ok_or(WasmLowerError::Unsupported(
5356        "jump target escapes the function",
5357    ))?;
5358    let pc_local = plan.num_regs;
5359    let in_loop = loop_pcs(&plan.ops);
5360    let roots = ctx
5361        .batch_reclaim
5362        .then(|| roots::Frame::new(plan, ctx.functions, ctx.may_safepoint));
5363
5364    let mut blocks_code: Vec<Vec<u8>> = Vec::with_capacity(blocks.num_blocks());
5365    for k in 0..blocks.num_blocks() {
5366        // A statically-dead block (e.g. the monomorphized-out branch of an `and`/`or` runtime
5367        // type-dispatch) is never branched to — emit a lone `unreachable` rather than lower its
5368        // ops, which may reference registers whose kinds were (correctly) never inferred.
5369        if !plan.reachable_blocks.get(k).copied().unwrap_or(true) {
5370            blocks_code.push(vec![0x00]); // unreachable
5371            continue;
5372        }
5373        let mut code = Vec::new();
5374        let mut terminated = false;
5375        for pc in blocks.start(k)..blocks.end(k) {
5376            // Exact collections already share their representation and ownership machinery.
5377            // Keep the surrounding bounds/COW/word checks shared too: otherwise each
5378            // reconciliation loop repeats those mechanisms at every collection site.
5379            ctx.hot
5380                .set(in_loop[pc] && !ctx.exact.sequence_ints() && !ctx.exact.map_ints);
5381            if let Some(roots) = &roots {
5382                roots.before(&mut code, plan, ctx, pc);
5383            }
5384            let flow = tower::lower(pc, plan, ctx, &blocks, k, &mut code).inspect_err(|e| {
5385                if std::env::var_os("LOGOS_WASM_TRACE_FIELD").is_some() {
5386                    let (defs, uses) = crate::vm::instruction::op_def_uses(&plan.ops[pc], ctx.functions);
5387                    let kinds: Vec<String> = defs
5388                        .iter()
5389                        .chain(&uses)
5390                        .map(|r| format!("R{r} {:?}", plan.kinds.get(*r as usize)))
5391                        .collect();
5392                    eprintln!("[wasm] op {pc} `{:?}` refused: {e} ({})", plan.ops[pc], kinds.join(", "));
5393                }
5394            })?;
5395            if flow == Flow::Terminated {
5396                terminated = true;
5397                break;
5398            }
5399        }
5400        if !terminated {
5401            let end = blocks.end(k);
5402            if end >= plan.ops.len() {
5403                // Fell off the end of the function: void returns, a typed function cannot.
5404                match plan.result {
5405                    None => {
5406                        if let Some(roots) = &roots {
5407                            roots.leave(&mut code, ctx, end - 1);
5408                        }
5409                        emit_leave_loops(&mut code, plan, ctx);
5410                        exact::leave(&mut code, plan, ctx)?;
5411                        code.push(0x0F); // return
5412                    }
5413                    Some(_) => code.push(0x00), // unreachable
5414                }
5415            } else {
5416                goto_block(&mut code, pc_local, &blocks, k, blocks.block_of(end));
5417            }
5418        }
5419        blocks_code.push(code);
5420    }
5421    ctx.hot.set(false);
5422
5423    let mut body = Vec::new();
5424    if runs_loops(plan) {
5425        // The loops this call starts sit above the frame that was on top when it was entered;
5426        // every way out unwinds back to it (`emit_leave_loops`).
5427        global_get(&mut body, ctx.iter_global);
5428        local_set(&mut body, loop_base_local(plan));
5429    }
5430    exact::prologue(&mut body, plan, ctx)?;
5431    body.extend(assemble_dispatch_loop(pc_local, &blocks_code));
5432    if !plan_results(plan).is_empty() {
5433        body.push(0x00); // unreachable: a function with results always returns inside a block
5434    }
5435    body.push(0x0B); // end function
5436
5437    let mut entry = encode_locals(plan, roots.as_ref().map_or(0, roots::Frame::len));
5438    entry.extend(body);
5439    Ok(super::stackify::stackify(entry))
5440}
5441
5442/// Per pc of `ops`: whether it lies inside a loop — between a backward jump's target and the jump,
5443/// inclusive. The compiler lays every loop out contiguously (a `While`'s test, its body, the jump
5444/// back; a `Repeat`'s `IterNext`, its body, the jump back), so the span a back edge closes is the
5445/// loop, nested ones included.
5446fn loop_pcs(ops: &[Op]) -> Vec<bool> {
5447    let mut depth = vec![0i32; ops.len() + 1];
5448    for (pc, op) in ops.iter().enumerate() {
5449        if let Op::Jump { target }
5450        | Op::JumpIfFalse { target, .. }
5451        | Op::JumpIfTrue { target, .. } = *op
5452        {
5453            if target <= pc {
5454                depth[target] += 1;
5455                depth[pc + 1] -= 1;
5456            }
5457        }
5458    }
5459    let mut open = 0;
5460    depth[..ops.len()]
5461        .iter()
5462        .map(|d| {
5463            open += d;
5464            open > 0
5465        })
5466        .collect()
5467}
5468
5469/// Lower one op into the current block's code, returning whether it terminated the block.
5470fn lower_op(
5471    pc: usize,
5472    plan: &Plan,
5473    ctx: &Ctx,
5474    blocks: &Blocks,
5475    k: usize,
5476    code: &mut Vec<u8>,
5477) -> R<Flow> {
5478    let kinds = &plan.kinds;
5479    match plan.ops[pc] {
5480        Op::LoadConst { dst, idx } => {
5481            // A register the inference promoted to Float (an Int-initialized accumulator, `Let sum
5482            // be 0`) holds an `f64` local, so an Int/Bool literal flowing into it materializes as
5483            // `f64.const` — the exact promotion the VM performs at the first float op.
5484            let dst_float = kinds.get(dst as usize) == Some(Kind::Float);
5485            match ctx
5486                .constants
5487                .get(idx as usize)
5488                .ok_or(WasmLowerError::Unsupported("constant index out of range"))?
5489            {
5490                Constant::Int(v) if dst_float => {
5491                    code.push(0x44); // f64.const
5492                    code.extend_from_slice(&(*v as f64).to_le_bytes());
5493                }
5494                Constant::Int(v) => {
5495                    code.push(0x42); // i64.const
5496                    leb_i64(code, *v);
5497                }
5498                Constant::Bool(b) if dst_float => {
5499                    code.push(0x44); // f64.const
5500                    code.extend_from_slice(&(if *b { 1.0f64 } else { 0.0f64 }).to_le_bytes());
5501                }
5502                Constant::Bool(b) => {
5503                    code.push(0x42); // i64.const (truthy-Int boolean: 0/1)
5504                    leb_i64(code, i64::from(*b));
5505                }
5506                Constant::Char(c) => {
5507                    code.push(0x42); // i64.const — the Unicode code point (`char as u32`)
5508                    leb_i64(code, i64::from(*c as u32));
5509                }
5510                Constant::Nothing => {
5511                    // Observable absence has Kind::Nothing. An unobserved loan
5512                    // clear retains the payload local's physical type, and still
5513                    // clears the slot so it cannot keep a heap object rooted.
5514                    match kinds.valtype(dst as usize) {
5515                        F64 => {
5516                            code.push(0x44);
5517                            code.extend_from_slice(&0.0f64.to_le_bytes());
5518                        }
5519                        I32 => i32_const(code, 0),
5520                        _ => {
5521                            code.push(0x42);
5522                            leb_i64(code, 0);
5523                        }
5524                    }
5525                }
5526                Constant::Float(f) => {
5527                    code.push(0x44); // f64.const
5528                    code.extend_from_slice(&f.to_le_bytes());
5529                }
5530                // Temporal scalars ride a single i64 (tick/day count). A `select`'s `After N seconds`
5531                // ticks register is the only one the corpus loads — it is dead in the deterministic
5532                // model (`SelectArmTimeout` is a no-op; the timeout fires whenever no recv arm is ready)
5533                // but still materializes so its local declares.
5534                Constant::Duration(v) | Constant::Moment(v) | Constant::Time(v) => {
5535                    code.push(0x42); // i64.const
5536                    leb_i64(code, *v);
5537                }
5538                Constant::Date(v) => {
5539                    // A `Date` is days-since-epoch in an `i32` local (`Kind::Date` → i32, matching
5540                    // `LoadToday`'s i32 host result), so the literal materializes as `i32.const` — an
5541                    // `i64.const` would mismatch the declared local valtype. `i32_const` signs the LEB,
5542                    // so pre-1970 dates (negative days) encode correctly.
5543                    i32_const(code, *v);
5544                }
5545                // A `Span` packs its two i32 fields into one i64 local: `months` in the high word, `days`
5546                // in the low word (the calendar-arith lowering unpacks them for the runtime call).
5547                Constant::Span { months, days } => {
5548                    let packed = ((*months as i64) << 32) | ((*days as u32) as i64);
5549                    code.push(0x42); // i64.const
5550                    leb_i64(code, packed);
5551                }
5552                Constant::Text(s) => {
5553                    // Build a fresh Text object in linear memory; it leaves the handle on the
5554                    // stack for the `local_set` below.
5555                    lower_text_literal(code, ctx, plan.num_regs, s.as_bytes());
5556                }
5557            }
5558            local_set(code, dst as u32);
5559            Ok(Flow::Straight)
5560        }
5561        // unobservable (its source is dead). The RETAIN below is a harmless over-retain
5562        // (COW resolves it) — correctness identical to `Move`.
5563        // `EnsureOwned` is the interpreter's call-site COW barrier; the WASM AOT
5564        // enforces value semantics by copy-on-write at each element write, so the
5565        // barrier is a no-op here (correctness is preserved without it).
5566        Op::EnsureOwned { .. } => Ok(Flow::Straight),
5567        Op::Move { dst, src } => {
5568            // Moving an `i64` source into a Float-promoted destination converts (the VM's Int→Float
5569            // promotion); same-kind moves are a plain copy. Any OTHER valtype mismatch is refused
5570            // rather than mis-emitted — a bare `local_get`/`local_set` pair is only well-typed when
5571            // both locals share a wasm valtype (`Op::RevSwap`'s own guardrail, below, is the same
5572            // check for the same reason: an unresolved kind must never reach a raw stack copy).
5573            if kinds.get(dst as usize) == Some(Kind::Float)
5574                && kinds.get(src as usize) != Some(Kind::Float)
5575            {
5576                push_as_f64(code, src, kinds.get(src as usize))?;
5577            } else if kinds.valtype(dst as usize) != kinds.valtype(src as usize) {
5578                return Err(WasmLowerError::Unsupported(
5579                    "move between differently-typed registers",
5580                ));
5581            } else {
5582                local_get(code, src as u32);
5583            }
5584            local_set(code, dst as u32);
5585            // Aliasing a mutable heap object (`Let cs be c's items`) gains a second holder — RETAIN so
5586            // a later mutation of either copy-on-writes instead of clobbering the other.
5587            if counts_aliases(kinds.get(dst as usize)) {
5588                emit_retain(code, ctx, dst);
5589            }
5590            Ok(Flow::Straight)
5591        }
5592        // The zero-garbage reversible register exchange (`Swap a and b`): swap the two locals through the
5593        // wasm operand stack with no scratch local — `get b; get a; set b; set a` leaves `a`'s old value
5594        // in `b` and vice versa. The `set` order (`b` before `a`) is what makes it a swap, not two moves.
5595        // Both locals carry the same LOGOS kind (the compiler only emits `RevSwap` for two same-typed
5596        // locals; a promoted global falls back to a temp-mediated Move pair), so their wasm valtypes
5597        // match and the stack sequence is well-typed — a mismatch is refused rather than mis-emitted.
5598        Op::RevSwap { a, b } => {
5599            if kinds.valtype(a as usize) != kinds.valtype(b as usize) {
5600                return Err(WasmLowerError::Unsupported(
5601                    "swap of two differently-typed registers",
5602                ));
5603            }
5604            local_get(code, b as u32);
5605            local_get(code, a as u32);
5606            local_set(code, b as u32);
5607            local_set(code, a as u32);
5608            Ok(Flow::Straight)
5609        }
5610        // The delta-carrying reversible / adiabatic-core ops (the zero-garbage abelian group updates a
5611        // `Reversibly:` block emits). Their FORWARD semantics are the plain in-place update — `place +=
5612        // delta`, `place -= delta`, `place ^= delta`, `place = -place` — over the modular ring
5613        // (ℤ/2⁶⁴, +): the VM runs them with WRAPPING arithmetic (`i64::wrapping_add`/`wrapping_sub`/
5614        // `wrapping_neg`), so WASM lowers to the native wrapping `i64.add`/`i64.sub`/`i64.xor`
5615        // opcodes — NOT the checked `Op::Add` path (which traps to promote to BigInt) — keeping the
5616        // reversible group law exact and tape-free on every tier. `place != delta` holds by
5617        // construction (the compiler rides the delta on a fresh scratch register).
5618        Op::RevAdd { place, delta } => {
5619            arith(code, 0x7C, place, place, delta); // i64.add (wrapping)
5620            Ok(Flow::Straight)
5621        }
5622        Op::RevSub { place, delta } => {
5623            arith(code, 0x7D, place, place, delta); // i64.sub (wrapping)
5624            Ok(Flow::Straight)
5625        }
5626        Op::RevXor { place, delta } => {
5627            arith(code, 0x85, place, place, delta); // i64.xor
5628            Ok(Flow::Straight)
5629        }
5630        Op::RevNeg { place } => {
5631            // `place = 0 - place` — modular negation (`i64::wrapping_neg`), self-inverse.
5632            code.push(0x42); // i64.const 0
5633            leb_i64(code, 0);
5634            local_get(code, place as u32);
5635            code.push(0x7D); // i64.sub
5636            local_set(code, place as u32);
5637            Ok(Flow::Straight)
5638        }
5639        // A Text-typed `+` (`add_join` resolved the result to Text) is string concatenation — route to
5640        // `lower_concat`, which stringifies both operands and joins them. Everything else is numeric.
5641        // `+ - *` on a BigInt result (linker mode) are exact big-integer arithmetic via the runtime; an
5642        // `Int` operand promotes to a BigInt. Checked FIRST so a `BigInt` `+` never falls to the numeric
5643        // (or string-concat) path. The result kind is `BigInt` iff `op_kind_effect` saw a BigInt operand.
5644        Op::Add { dst, lhs, rhs }
5645            if ctx.linked && kinds.get(dst as usize) == Some(Kind::BigInt) =>
5646        {
5647            lower_bigint_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::BigintAdd)
5648        }
5649        Op::Sub { dst, lhs, rhs }
5650            if ctx.linked && kinds.get(dst as usize) == Some(Kind::BigInt) =>
5651        {
5652            lower_bigint_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::BigintSub)
5653        }
5654        Op::Mul { dst, lhs, rhs }
5655            if ctx.linked && kinds.get(dst as usize) == Some(Kind::BigInt) =>
5656        {
5657            lower_bigint_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::BigintMul)
5658        }
5659        Op::Div { dst, lhs, rhs }
5660            if ctx.linked && kinds.get(dst as usize) == Some(Kind::BigInt) =>
5661        {
5662            lower_bigint_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::BigintDiv)
5663        }
5664        Op::Mod { dst, lhs, rhs }
5665            if ctx.linked && kinds.get(dst as usize) == Some(Kind::BigInt) =>
5666        {
5667            lower_bigint_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::BigintMod)
5668        }
5669        Op::Add { dst, lhs, rhs }
5670            if ctx.linked && kinds.get(dst as usize) == Some(Kind::Complex) =>
5671        {
5672            lower_complex_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::ComplexAdd)
5673        }
5674        Op::Sub { dst, lhs, rhs }
5675            if ctx.linked && kinds.get(dst as usize) == Some(Kind::Complex) =>
5676        {
5677            lower_complex_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::ComplexSub)
5678        }
5679        Op::Mul { dst, lhs, rhs }
5680            if ctx.linked && kinds.get(dst as usize) == Some(Kind::Complex) =>
5681        {
5682            lower_complex_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::ComplexMul)
5683        }
5684        Op::Add { dst, lhs, rhs }
5685            if ctx.linked && kinds.get(dst as usize) == Some(Kind::Modular) =>
5686        {
5687            lower_modular_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::ModularAdd)
5688        }
5689        Op::Sub { dst, lhs, rhs }
5690            if ctx.linked && kinds.get(dst as usize) == Some(Kind::Modular) =>
5691        {
5692            lower_modular_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::ModularSub)
5693        }
5694        Op::Mul { dst, lhs, rhs }
5695            if ctx.linked && kinds.get(dst as usize) == Some(Kind::Modular) =>
5696        {
5697            lower_modular_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::ModularMul)
5698        }
5699        Op::Div { dst, lhs, rhs } | Op::ExactDiv { dst, lhs, rhs }
5700            if ctx.linked && kinds.get(dst as usize) == Some(Kind::Modular) =>
5701        {
5702            lower_modular_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::ModularDiv)
5703        }
5704        Op::Add { dst, lhs, rhs }
5705            if ctx.linked && kinds.get(dst as usize) == Some(Kind::Decimal) =>
5706        {
5707            lower_decimal_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::DecimalAdd)
5708        }
5709        Op::Sub { dst, lhs, rhs }
5710            if ctx.linked && kinds.get(dst as usize) == Some(Kind::Decimal) =>
5711        {
5712            lower_decimal_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::DecimalSub)
5713        }
5714        Op::Mul { dst, lhs, rhs }
5715            if ctx.linked && kinds.get(dst as usize) == Some(Kind::Decimal) =>
5716        {
5717            lower_decimal_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::DecimalMul)
5718        }
5719        Op::Add { dst, lhs, rhs } if ctx.linked && kinds.get(dst as usize) == Some(Kind::Money) => {
5720            lower_money_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::MoneyAdd)
5721        }
5722        Op::Sub { dst, lhs, rhs } if ctx.linked && kinds.get(dst as usize) == Some(Kind::Money) => {
5723            lower_money_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::MoneySub)
5724        }
5725        Op::Add { dst, lhs, rhs }
5726            if ctx.linked && kinds.get(dst as usize) == Some(Kind::Quantity) =>
5727        {
5728            lower_quantity_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::QuantityAdd)
5729        }
5730        Op::Sub { dst, lhs, rhs }
5731            if ctx.linked && kinds.get(dst as usize) == Some(Kind::Quantity) =>
5732        {
5733            lower_quantity_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::QuantitySub)
5734        }
5735        Op::Mul { dst, lhs, rhs }
5736            if ctx.linked && kinds.get(dst as usize) == Some(Kind::Quantity) =>
5737        {
5738            lower_quantity_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::QuantityMul)
5739        }
5740        Op::Div { dst, lhs, rhs }
5741            if ctx.linked && kinds.get(dst as usize) == Some(Kind::Quantity) =>
5742        {
5743            lower_quantity_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::QuantityDiv)
5744        }
5745        // `Moment/Date + Span` (calendar arithmetic, commutes): the Span operand carries the months/days,
5746        // the other is the base. Guarded on the SPAN operand (not dst) so it beats the `Moment + Duration`
5747        // i64-add arm above (whose result is also Moment).
5748        Op::Add { dst, lhs, rhs }
5749            if ctx.linked
5750                && (kinds.get(lhs as usize) == Some(Kind::Span)
5751                    || kinds.get(rhs as usize) == Some(Kind::Span)) =>
5752        {
5753            let (base, span) = if kinds.get(lhs as usize) == Some(Kind::Span) {
5754                (rhs, lhs)
5755            } else {
5756                (lhs, rhs)
5757            };
5758            let is_date = kinds.get(base as usize) == Some(Kind::Date);
5759            return lower_span_add(code, ctx, plan.num_regs, dst, base, span, is_date, false);
5760        }
5761        // `Moment/Date - Span` steps the calendar backward — the span (rhs) is negated.
5762        Op::Sub { dst, lhs, rhs } if ctx.linked && kinds.get(rhs as usize) == Some(Kind::Span) => {
5763            let is_date = kinds.get(lhs as usize) == Some(Kind::Date);
5764            return lower_span_add(code, ctx, plan.num_regs, dst, lhs, rhs, is_date, true);
5765        }
5766        // Lane-wise `Lanes + Lanes` (the SHA-1 block fold `st + abcdSave`) — a `logos_rt_lanes4_add` call.
5767        Op::Add { dst, lhs, rhs } if ctx.linked && kinds.get(dst as usize) == Some(Kind::Lanes) => {
5768            let idx = (ctx.host_index)(HostFn::Lanes4Add)
5769                .ok_or(WasmLowerError::Unsupported("lanes4_add not imported"))?;
5770            local_get(code, lhs as u32);
5771            local_get(code, rhs as u32);
5772            code.push(0x10);
5773            leb_u32(code, idx);
5774            local_set(code, dst as u32);
5775            Ok(Flow::Straight)
5776        }
5777        Op::Add { dst, lhs, rhs }
5778            if ctx.linked && kinds.get(dst as usize) == Some(Kind::Rational) =>
5779        {
5780            lower_rational_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::RationalAdd)
5781        }
5782        Op::Sub { dst, lhs, rhs }
5783            if ctx.linked && kinds.get(dst as usize) == Some(Kind::Rational) =>
5784        {
5785            lower_rational_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::RationalSub)
5786        }
5787        Op::Mul { dst, lhs, rhs }
5788            if ctx.linked && kinds.get(dst as usize) == Some(Kind::Rational) =>
5789        {
5790            lower_rational_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::RationalMul)
5791        }
5792        Op::Div { dst, lhs, rhs }
5793            if ctx.linked && kinds.get(dst as usize) == Some(Kind::Rational) =>
5794        {
5795            lower_rational_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::RationalQuotient)
5796        }
5797        Op::Mod { dst, lhs, rhs }
5798            if ctx.linked && kinds.get(dst as usize) == Some(Kind::Rational) =>
5799        {
5800            lower_rational_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::RationalRemainder)
5801        }
5802        Op::FloorDiv { dst, lhs, rhs }
5803            if ctx.linked && kinds.get(dst as usize) == Some(Kind::Rational) =>
5804        {
5805            lower_rational_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::RationalFloorQuotient)
5806        }
5807        Op::Pow { dst, lhs, rhs }
5808            if ctx.linked && kinds.get(dst as usize) == Some(Kind::Rational) =>
5809        {
5810            lower_rational_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::RationalPower)
5811        }
5812        Op::BitXor { dst, lhs, rhs } | Op::BitAnd { dst, lhs, rhs } | Op::BitOr { dst, lhs, rhs }
5813            if ctx.linked
5814                && (kinds.get(lhs as usize) == Some(Kind::Rational)
5815                    || kinds.get(rhs as usize) == Some(Kind::Rational)) =>
5816        {
5817            let which = match plan.ops[pc] {
5818                Op::BitAnd { .. } => 0,
5819                Op::BitOr { .. } => 1,
5820                _ => 2,
5821            };
5822            let idx = (ctx.host_index)(HostFn::RationalBitwise)
5823                .ok_or(WasmLowerError::Unsupported("rational_bitwise not imported"))?;
5824            push_rational_operand(code, kinds, ctx, lhs)?;
5825            push_rational_operand(code, kinds, ctx, rhs)?;
5826            i32_const(code, which);
5827            code.push(0x10);
5828            leb_u32(code, idx);
5829            local_set(code, dst as u32);
5830            Ok(Flow::Straight)
5831        }
5832        Op::Add { dst, lhs, rhs } => {
5833            if kinds.get(dst as usize) == Some(Kind::Text) {
5834                lower_concat(code, plan, ctx, dst, lhs, rhs)?;
5835                Ok(Flow::Straight)
5836            } else {
5837                lower_arith(code, ctx, kinds, dst, lhs, rhs, ArithOp::Add)
5838            }
5839        }
5840        Op::Sub { dst, lhs, rhs } => lower_arith(code, ctx, kinds, dst, lhs, rhs, ArithOp::Sub),
5841        Op::Mul { dst, lhs, rhs } => lower_arith(code, ctx, kinds, dst, lhs, rhs, ArithOp::Mul),
5842        Op::Div { dst, lhs, rhs } => lower_arith(code, ctx, kinds, dst, lhs, rhs, ArithOp::Div),
5843        Op::FloorDiv { dst, lhs, rhs } => {
5844            lower_floordiv_regs(code, kinds, plan.num_regs, dst, lhs, rhs)
5845        }
5846        Op::Mod { dst, lhs, rhs } => lower_arith(code, ctx, kinds, dst, lhs, rhs, ArithOp::Mod),
5847        // `a ** b` — exponentiation. Float-result cases use the host `pow_ff`/`pow_fi`; `Int^Int`
5848        // is the in-module overflow-trapping squaring loop (a `2**100`-style overflow traps, the
5849        // BigInt-promoting frontier, matching `Mul`). A negative Int exponent traps (VM → Float).
5850        Op::Pow { dst, lhs, rhs } => lower_pow_regs(code, kinds, ctx, plan.num_regs, dst, lhs, rhs),
5851        // `lhs / 2^k` (the Oracle's power-of-two division form) = a plain signed division by the
5852        // constant `1<<k` — `i64.div_s` matches the VM's `lhs.div(1<<k)` (truncate toward zero, and
5853        // `2^k > 0` so no INT_MIN/-1 trap). Emitted only for an Oracle-proven `Int` lhs (i64).
5854        Op::DivPow2 { dst, lhs, k } => {
5855            local_get(code, lhs as u32);
5856            code.push(0x42); // i64.const 2^k
5857            leb_i64(code, 1i64 << k);
5858            code.push(0x7F); // i64.div_s
5859            local_set(code, dst as u32);
5860            Ok(Flow::Straight)
5861        }
5862        // `lhs / c` or `lhs % c` by the precomputed magic reciprocal — mirror the VM's `magic_eval`
5863        // (Granlund–Montgomery mul-high + shift) bit-for-bit.
5864        Op::MagicDivU {
5865            dst,
5866            lhs,
5867            magic,
5868            more,
5869            mul_back,
5870            divisor: _,
5871            wrap: _,
5872        } => {
5873            lower_magic_div(code, plan.num_regs, dst, lhs, magic, more, mul_back);
5874            Ok(Flow::Straight)
5875        }
5876        // `a / b` in a `Rational` context → an exact reduced `Rational`. LINKER mode uses the
5877        // BigInt-backed runtime (`logos_rt_rational_div`, arbitrary precision, promoting Int/BigInt
5878        // operands to Rational first); self-contained mode uses the inline i64/i64 reduce.
5879        Op::ExactDiv { dst, lhs, rhs } if ctx.linked => {
5880            lower_rational_binop(code, kinds, ctx, dst, lhs, rhs, HostFn::RationalDiv)
5881        }
5882        Op::ExactDiv { dst, lhs, rhs } => {
5883            lower_exact_div(code, ctx, plan.num_regs, dst, lhs, rhs);
5884            Ok(Flow::Straight)
5885        }
5886        // Pure native-region metadata — the AOT's accesses are checked, so the bound guard is a no-op
5887        // (exactly as the VM, where `RegionBoundsGuard` is a `pc += 1`).
5888        Op::RegionBoundsGuard { .. } => Ok(Flow::Straight),
5889        Op::AddAssign { dst, src } => {
5890            if kinds.get(dst as usize) == Some(Kind::Text) {
5891                let (a, b) = (plan.num_regs + 8, plan.num_regs + 9);
5892                local_get(code, dst as u32);
5893                local_set(code, a);
5894                display::emit_display_of(code, plan, ctx, src, b)?;
5895                emit_text_append(code, ctx, plan.num_regs, a, b, dst as u32);
5896                Ok(Flow::Straight)
5897            } else if ctx.linked && kinds.get(dst as usize) == Some(Kind::Lanes) {
5898                // `lanes += lanes` (the SHA-1 `Set e0 to e0 + m0`) — lane-wise add into `dst`.
5899                let idx = (ctx.host_index)(HostFn::Lanes4Add)
5900                    .ok_or(WasmLowerError::Unsupported("lanes4_add not imported"))?;
5901                local_get(code, dst as u32);
5902                local_get(code, src as u32);
5903                code.push(0x10);
5904                leb_u32(code, idx);
5905                local_set(code, dst as u32);
5906                Ok(Flow::Straight)
5907            } else {
5908                lower_arith(code, ctx, kinds, dst, dst, src, ArithOp::Add)
5909            }
5910        }
5911        // `^ & |` scalar lowering only — a Set operand (set algebra) has no register-scalar
5912        // form here yet, so it fails loud rather than i64-punning a handle.
5913        // Bitwise `xor`/`&`/`|` also close over the Word ring (`Word32` → `i32.*`, `Word64` → `i64.*`),
5914        // so crypto written with the `xor` keyword compiles alongside the `word_and`/`word_or` builtins.
5915        Op::BitXor { dst, lhs, rhs } => match kinds.get(lhs as usize) {
5916            Some(Kind::Int) | Some(Kind::Word64) => {
5917                arith(code, 0x85, dst, lhs, rhs); // i64.xor
5918                Ok(Flow::Straight)
5919            }
5920            Some(Kind::Word32) => {
5921                arith(code, 0x73, dst, lhs, rhs); // i32.xor
5922                Ok(Flow::Straight)
5923            }
5924            // Lane-wise `Lanes xor Lanes` (the SHA-1 message-schedule fold) via the runtime.
5925            Some(Kind::Lanes) if ctx.linked => {
5926                let idx = (ctx.host_index)(HostFn::Lanes4Xor)
5927                    .ok_or(WasmLowerError::Unsupported("lanes4_xor not imported"))?;
5928                local_get(code, lhs as u32);
5929                local_get(code, rhs as u32);
5930                code.push(0x10);
5931                leb_u32(code, idx);
5932                local_set(code, dst as u32);
5933                Ok(Flow::Straight)
5934            }
5935            _ => Err(WasmLowerError::Unsupported("`^` of a non-Int/Word value")),
5936        },
5937        Op::BitAnd { dst, lhs, rhs } => match kinds.get(lhs as usize) {
5938            Some(Kind::Int) | Some(Kind::Bool) | Some(Kind::Word64) => {
5939                arith(code, 0x83, dst, lhs, rhs); // i64.and
5940                Ok(Flow::Straight)
5941            }
5942            Some(Kind::Word32) => {
5943                arith(code, 0x71, dst, lhs, rhs); // i32.and
5944                Ok(Flow::Straight)
5945            }
5946            _ => Err(WasmLowerError::Unsupported(
5947                "`&` of a non-Int/Bool/Word value",
5948            )),
5949        },
5950        Op::BitOr { dst, lhs, rhs } => match kinds.get(lhs as usize) {
5951            Some(Kind::Int) | Some(Kind::Bool) | Some(Kind::Word64) => {
5952                arith(code, 0x84, dst, lhs, rhs); // i64.or
5953                Ok(Flow::Straight)
5954            }
5955            Some(Kind::Word32) => {
5956                arith(code, 0x72, dst, lhs, rhs); // i32.or
5957                Ok(Flow::Straight)
5958            }
5959            _ => Err(WasmLowerError::Unsupported(
5960                "`|` of a non-Int/Bool/Word value",
5961            )),
5962        },
5963        Op::Shl { dst, lhs, rhs } => {
5964            arith(code, 0x86, dst, lhs, rhs); // i64.shl
5965            Ok(Flow::Straight)
5966        }
5967        Op::Shr { dst, lhs, rhs } => {
5968            arith(code, 0x87, dst, lhs, rhs); // i64.shr_s
5969            Ok(Flow::Straight)
5970        }
5971        Op::Not { dst, src } => {
5972            // `not` is LOGICAL — truthiness in, Bool out (`~` lowers to `x ^ -1`
5973            // in the parser, never through here). Bool and Int share the zero
5974            // test: `x == 0` (i64.eqz → i32) widened back to i64 0/1.
5975            match kinds.get(src as usize) {
5976                Some(Kind::Bool) | Some(Kind::Int) => {
5977                    local_get(code, src as u32);
5978                    code.push(0x50); // i64.eqz
5979                    code.push(0xAD); // i64.extend_i32_u
5980                    local_set(code, dst as u32);
5981                }
5982                _ => return Err(WasmLowerError::Unsupported("Not of a non-Int/Bool value")),
5983            }
5984            Ok(Flow::Straight)
5985        }
5986        Op::Lt { dst, lhs, rhs } => lower_compare(code, ctx, kinds, dst, lhs, rhs, Cmp::Lt),
5987        Op::Gt { dst, lhs, rhs } => lower_compare(code, ctx, kinds, dst, lhs, rhs, Cmp::Gt),
5988        Op::LtEq { dst, lhs, rhs } => lower_compare(code, ctx, kinds, dst, lhs, rhs, Cmp::Le),
5989        Op::GtEq { dst, lhs, rhs } => lower_compare(code, ctx, kinds, dst, lhs, rhs, Cmp::Ge),
5990        Op::ApproxEq { dst, lhs, rhs } => lower_approx_eq(code, kinds, dst, lhs, rhs),
5991        Op::Eq { dst, lhs, rhs } => {
5992            if kinds.get(lhs as usize) == Some(Kind::Text)
5993                && kinds.get(rhs as usize) == Some(Kind::Text)
5994            {
5995                lower_text_eq(code, ctx, plan.num_regs, dst, lhs, rhs, false);
5996                Ok(Flow::Straight)
5997            } else if ctx.linked
5998                && kinds.get(lhs as usize) == Some(Kind::Uuid)
5999                && kinds.get(rhs as usize) == Some(Kind::Uuid)
6000            {
6001                lower_uuid_eq(code, ctx, dst, lhs, rhs, false)
6002            } else {
6003                lower_compare(code, ctx, kinds, dst, lhs, rhs, Cmp::Eq)
6004            }
6005        }
6006        Op::NotEq { dst, lhs, rhs } => {
6007            if kinds.get(lhs as usize) == Some(Kind::Text)
6008                && kinds.get(rhs as usize) == Some(Kind::Text)
6009            {
6010                lower_text_eq(code, ctx, plan.num_regs, dst, lhs, rhs, true);
6011                Ok(Flow::Straight)
6012            } else if ctx.linked
6013                && kinds.get(lhs as usize) == Some(Kind::Uuid)
6014                && kinds.get(rhs as usize) == Some(Kind::Uuid)
6015            {
6016                lower_uuid_eq(code, ctx, dst, lhs, rhs, true)
6017            } else {
6018                lower_compare(code, ctx, kinds, dst, lhs, rhs, Cmp::Ne)
6019            }
6020        }
6021        Op::Jump { target } => {
6022            goto_block(code, plan.num_regs, blocks, k, blocks.block_of(target));
6023            Ok(Flow::Terminated)
6024        }
6025        Op::JumpIfFalse { cond, target } => {
6026            emit_cond_jump(
6027                code,
6028                cond,
6029                true,
6030                blocks.block_of(target),
6031                blocks.block_of(pc + 1),
6032                plan.num_regs,
6033                blocks.br_loop(k),
6034            );
6035            Ok(Flow::Terminated)
6036        }
6037        Op::JumpIfTrue { cond, target } => {
6038            emit_cond_jump(
6039                code,
6040                cond,
6041                false,
6042                blocks.block_of(target),
6043                blocks.block_of(pc + 1),
6044                plan.num_regs,
6045                blocks.br_loop(k),
6046            );
6047            Ok(Flow::Terminated)
6048        }
6049        Op::GlobalGet { dst, idx } => {
6050            code.push(0x23); // global.get
6051            leb_u32(code, idx as u32);
6052            local_set(code, dst as u32);
6053            // Reading a global heap handle aliases the global's object — RETAIN so a mutation of the
6054            // read copy copy-on-writes instead of clobbering the global. A transient read keeps
6055            // nothing ([`transient_reads`]), and a take moves the global's own hold ([`PlaceSites`]).
6056            let aliases = !plan.place.take.get(pc).copied().unwrap_or(false)
6057                && !plan.transient.get(dst as usize).copied().unwrap_or(false);
6058            if counts_aliases(kinds.get(dst as usize)) && aliases {
6059                emit_retain(code, ctx, dst);
6060            }
6061            Ok(Flow::Straight)
6062        }
6063        Op::LoadToday { dst } => {
6064            let idx = (ctx.host_index)(HostFn::Today)
6065                .ok_or(WasmLowerError::Unsupported("today not imported"))?;
6066            code.push(0x10); // call today -> i32 (Date)
6067            leb_u32(code, idx);
6068            local_set(code, dst as u32);
6069            Ok(Flow::Straight)
6070        }
6071        // A new empty sequence: bump-allocate a 16-byte header `[len=0][cap=0][data_ptr=0]` and
6072        // hand back its (stable) pointer. Growth on push reallocs the data buffer, not the header,
6073        // so the register holding this handle never needs updating.
6074        // A new empty sequence or map — both are a zeroed 16-byte header `[len/num=0][cap=0]
6075        // [data_ptr=0]`; the element/entry shape differs only at use.
6076        Op::NewEmptyListFixed { dst, capacity } => {
6077            emit_fixed_header(
6078                code,
6079                ctx,
6080                plan.num_regs,
6081                dst as u32,
6082                empty_collection_class(kinds.get(dst as usize)),
6083                capacity as u32,
6084            );
6085            Ok(Flow::Straight)
6086        }
6087        Op::NewEmptyListWithCapacity { dst, capacity } => {
6088            emit_capacity_header(
6089                code,
6090                ctx,
6091                plan.num_regs,
6092                dst as u32,
6093                capacity as u32,
6094                empty_collection_class(kinds.get(dst as usize)),
6095                8,
6096            );
6097            Ok(Flow::Straight)
6098        }
6099        Op::NewEmptyMapWithCapacity { dst, capacity } => {
6100            emit_capacity_header(
6101                code,
6102                ctx,
6103                plan.num_regs,
6104                dst as u32,
6105                capacity as u32,
6106                empty_collection_class(kinds.get(dst as usize)),
6107                16,
6108            );
6109            Ok(Flow::Straight)
6110        }
6111        Op::NewEmptyList { dst }
6112        | Op::NewEmptyListI32 { dst }
6113        | Op::NewEmptyMap { dst }
6114        | Op::NewEmptySet { dst } => {
6115            emit_empty_header(
6116                code,
6117                ctx,
6118                plan.num_regs,
6119                dst as u32,
6120                empty_collection_class(kinds.get(dst as usize)),
6121            );
6122            Ok(Flow::Straight)
6123        }
6124        // `length of seq` = the header's `len` field (an Int).
6125        Op::Length { dst, collection } => {
6126            local_get(code, collection as u32);
6127            i32_load(code, 0); // header len (i32)
6128            code.push(0xAD); // i64.extend_i32_u → Int
6129            local_set(code, dst as u32);
6130            Ok(Flow::Straight)
6131        }
6132        Op::ListPush { list, value } => {
6133            emit_cow(code, kinds, &plan.structs, ctx, plan.num_regs, list)?;
6134            lower_list_push(code, kinds, ctx, plan.num_regs, list, value)?;
6135            // Pushing a mutable heap VALUE stores it as an element (a second holder) — RETAIN so a
6136            // later mutation of the original copy-on-writes instead of mutating the stored element.
6137            if counts_aliases(kinds.get(value as usize)) {
6138                emit_retain(code, ctx, value);
6139            }
6140            // S8's true-count RETAIN — a push never overwrites anything, so there is no matching
6141            // release to pair here (only a later `ListPop`/the container's own eventual free ends
6142            // this hold; see `lower_remove_from`'s doc for why nothing else in this session's scope
6143            // removes a single interior element of a `Seq`).
6144            if counted_kind(kinds.get(value as usize)) {
6145                emit_true_retain(code, ctx, value);
6146            }
6147            Ok(Flow::Straight)
6148        }
6149        Op::ListPushField { obj, field, src } => {
6150            let cow = plan.cow_inserts.get(pc).copied().unwrap_or(true);
6151            lower_list_push_field(code, plan, kinds, ctx, cow, obj, field, src)?;
6152            if counts_aliases(kinds.get(src as usize)) {
6153                emit_retain(code, ctx, src);
6154            }
6155            if counted_kind(kinds.get(src as usize)) {
6156                emit_true_retain(code, ctx, src);
6157            }
6158            Ok(Flow::Straight)
6159        }
6160        Op::ListPop { list, dst } => {
6161            emit_cow(code, kinds, &plan.structs, ctx, plan.num_regs, list)?;
6162            lower_list_pop(code, kinds, dst, list)?;
6163            // S8's true count: the list no longer holds what it popped; the register it went to is no
6164            // holder, so a value nothing else keeps is freed at the next safepoint.
6165            if counted_kind(kinds.get(list as usize).and_then(Kind::seq_elem)) {
6166                emit_true_release(code, ctx, |c| local_get(c, dst as u32));
6167            }
6168            // The popped element's slot stays physically in the (now-shorter) buffer, so `dst`
6169            // aliases it until a later push overwrites it — RETAIN a clonable handle so mutating
6170            // `dst` copy-on-writes (same discipline as an `Index` extract).
6171            if counts_aliases(kinds.get(dst as usize)) {
6172                emit_retain(code, ctx, dst);
6173            }
6174            Ok(Flow::Straight)
6175        }
6176        // `IndexUnchecked` (the Oracle-proven-in-bounds optimizer form) executes IDENTICALLY to `Index`
6177        // in the VM — the "unchecked" only drops the bounds branch inside a native region. The AOT keeps
6178        // its bounds check (a safe superset), so the two lower to the same code.
6179        Op::Index {
6180            dst,
6181            collection,
6182            index,
6183        }
6184        | Op::IndexUnchecked {
6185            dst,
6186            collection,
6187            index,
6188        } => {
6189            match kinds.get(collection as usize) {
6190                Some(Kind::Map) => {
6191                    lower_map_get(code, kinds, ctx, plan.num_regs, dst, collection, index)?
6192                }
6193                Some(Kind::Text) => {
6194                    lower_text_index(code, ctx, plan.num_regs, dst, collection, index)?
6195                }
6196                _ => lower_index(code, ctx, kinds, dst, collection, index)?,
6197            }
6198            // `Let row be item k of matrix` extracts a handle that aliases the element in the
6199            // container — RETAIN so mutating the extracted row copy-on-writes. An item the place
6200            // lowering TAKES out, or a transient read ([`transient_reads`]), is no new alias.
6201            let aliases = !plan.place.take.get(pc).copied().unwrap_or(false)
6202                && !plan.transient.get(dst as usize).copied().unwrap_or(false);
6203            if counts_aliases(kinds.get(dst as usize)) && aliases {
6204                emit_retain(code, ctx, dst);
6205            }
6206            Ok(Flow::Straight)
6207        }
6208        // `SetIndexUnchecked` is the Oracle-proven-in-bounds form of `SetIndex` (identical in the VM);
6209        // lowered the same (the AOT keeps its bounds check).
6210        Op::SetIndex {
6211            collection,
6212            index,
6213            value,
6214        }
6215        | Op::SetIndexUnchecked {
6216            collection,
6217            index,
6218            value,
6219        } => {
6220            emit_cow(code, kinds, &plan.structs, ctx, plan.num_regs, collection)?;
6221            if kinds.get(collection as usize) == Some(Kind::Struct) {
6222                let cow = plan.cow_inserts.get(pc).copied().unwrap_or(true);
6223                lower_record_field_set(code, plan, kinds, ctx, pc, cow, collection, value)?;
6224            } else if plan.place.clear.get(pc).copied().unwrap_or(false) {
6225                // The place lowering's clear of an item it took out stores nothing ([`PlaceSites`]).
6226                return Ok(Flow::Straight);
6227            } else if kinds.get(collection as usize) == Some(Kind::Map) {
6228                lower_map_insert(code, kinds, ctx, plan.num_regs, collection, index, value)?;
6229            } else {
6230                lower_set_index(code, ctx, kinds, plan.num_regs, collection, index, value)?;
6231            }
6232            // A clear stored nothing: the slot still holds what the take read, in both counts.
6233            if plan.place.clear.get(pc).copied().unwrap_or(false) {
6234                return Ok(Flow::Straight);
6235            }
6236            // Storing a mutable heap VALUE as an element/map-value (a second holder) — RETAIN so a
6237            // later mutation of the original copy-on-writes instead of mutating the stored one. A
6238            // level put back where the place lowering took it from is the same holder, not a second.
6239            if counts_aliases(kinds.get(value as usize))
6240                && !plan.place.put_back.get(pc).copied().unwrap_or(false)
6241            {
6242                emit_retain(code, ctx, value);
6243            }
6244            // S8's true count: every store holds what it stores. A put-back is such a store — what
6245            // comes back may be the copy a mutation in between made, not the value the take read —
6246            // and the store released what it overwrote.
6247            if counted_kind(kinds.get(value as usize)) {
6248                emit_true_retain(code, ctx, value);
6249            }
6250            Ok(Flow::Straight)
6251        }
6252        Op::NewRange { dst, start, end } => {
6253            if ctx.linked || !plan.range_loops.contains_key(&dst) {
6254                lower_new_range(code, ctx, plan.num_regs, dst, start, end);
6255            } else {
6256                // Capture the bounds here, while exact::on_words has narrowed them. The
6257                // immediately following IterPrepare is this constructor's only use and
6258                // has no other predecessor (range_loop_registers).
6259                lower_range_iter_prepare(code, ctx, plan.num_regs, start, end);
6260            }
6261            Ok(Flow::Straight)
6262        }
6263        // A list literal `[…]` and a homogeneous tuple `(…)` allocate the same buffer via
6264        // `lower_new_list`; a heterogeneous tuple (inferred `Kind::Tuple`) stores each element at
6265        // its own width via `lower_new_tuple_het`.
6266        Op::NewList { dst, start, count } => {
6267            lower_new_list(code, kinds, ctx, plan.num_regs, dst, start, count)?;
6268            Ok(Flow::Straight)
6269        }
6270        Op::NewTuple { dst, start, count } => {
6271            if kinds.get(dst as usize) == Some(Kind::Tuple) {
6272                lower_new_tuple_het(code, kinds, ctx, plan.num_regs, dst, start, count)?;
6273                // S8's true count: the tuple holds each counted value it was built from.
6274                for i in 0..count {
6275                    if counted_kind(kinds.get((start + i) as usize)) {
6276                        emit_true_retain(code, ctx, start + i);
6277                    }
6278                }
6279            } else {
6280                lower_new_list(code, kinds, ctx, plan.num_regs, dst, start, count)?;
6281            }
6282            Ok(Flow::Straight)
6283        }
6284        Op::DestructureTuple { src, start, count } => {
6285            lower_destructure_tuple(code, kinds, src, start, count)?;
6286            Ok(Flow::Straight)
6287        }
6288        Op::IterPrepare { iterable } => {
6289            if ctx.linked || !plan.range_loops.contains_key(&iterable) {
6290                lower_iter_prepare(code, kinds, ctx, plan.num_regs, iterable)?;
6291            }
6292            Ok(Flow::Straight)
6293        }
6294        Op::IterNext { dst, exit } => {
6295            lower_iter_next(code, plan, ctx, blocks, k, dst, exit, pc)?;
6296            Ok(Flow::Terminated)
6297        }
6298        Op::SetAdd { set, value } => {
6299            emit_cow(code, kinds, &plan.structs, ctx, plan.num_regs, set)?;
6300            lower_set_add(code, kinds, ctx, plan.num_regs, set, value)?;
6301            Ok(Flow::Straight)
6302        }
6303        Op::RemoveFrom { collection, value } => {
6304            emit_cow(code, kinds, &plan.structs, ctx, plan.num_regs, collection)?;
6305            lower_remove_from(code, kinds, ctx, plan.num_regs, collection, value)?;
6306            Ok(Flow::Straight)
6307        }
6308        Op::UnionOp { dst, lhs, rhs } => {
6309            lower_union(code, kinds, ctx, plan.num_regs, dst, lhs, rhs)?;
6310            Ok(Flow::Straight)
6311        }
6312        Op::IntersectOp { dst, lhs, rhs } => {
6313            lower_intersect(code, kinds, ctx, plan.num_regs, dst, lhs, rhs)?;
6314            Ok(Flow::Straight)
6315        }
6316        Op::Contains {
6317            dst,
6318            collection,
6319            value,
6320        } => {
6321            if kinds.get(collection as usize) == Some(Kind::Map) {
6322                lower_map_contains(code, kinds, ctx, plan.num_regs, dst, collection, value)?;
6323            } else {
6324                lower_contains(code, kinds, ctx, plan.num_regs, dst, collection, value)?;
6325            }
6326            Ok(Flow::Straight)
6327        }
6328        Op::SliceOp {
6329            dst,
6330            collection,
6331            start,
6332            end,
6333        } => {
6334            lower_slice(code, kinds, ctx, plan.num_regs, dst, collection, start, end)?;
6335            Ok(Flow::Straight)
6336        }
6337        Op::SeqConcat { dst, lhs, rhs } => {
6338            lower_seq_concat(code, kinds, ctx, plan.num_regs, dst, lhs, rhs)?;
6339            Ok(Flow::Straight)
6340        }
6341        Op::Concat { dst, lhs, rhs } => {
6342            // ★ `"" ++ x` IS JUST `x` RENDERED, and every interpolation begins with one. An
6343            // interpolated string compiles to `LoadConst "" -> dst` followed by a `Concat` per
6344            // piece, so `{i}` — the most common thing a view contains — became a concat whose left
6345            // side is empty. `lower_concat` stringifies BOTH sides and then allocates a third Text
6346            // to copy them into, so a one-piece hole cost four allocations, two of them garbage the
6347            // instant they were made. Measured at 80 bytes of heap per hole per row per turn.
6348            //
6349            // Recognised as the ADJACENT PAIR the compiler emits, and only when this `Concat` is not
6350            // a block leader — if it were, some branch could land on it and the preceding op would
6351            // not be its only predecessor. `is_leader` makes that a proof rather than an assumption
6352            // about how interpolations happen to be emitted.
6353            // ★ NOT `lhs == dst`. The accumulator starts as the destination, but copy-propagation
6354            // rewrites it, so the pair arrives as `Concat { dst: 98, lhs: 43 }` after a
6355            // `LoadConst { dst: 43 }`. Requiring the two to be equal made this fold silently never
6356            // fire — the trace said `-> false` on the one site it was written for. The fold does not
6357            // need them equal: `"" ++ x` is `x` rendered, whichever register holds the empty side.
6358            let folds = pc > 0
6359                && !blocks.is_leader(pc)
6360                && matches!(
6361                    plan.ops.get(pc - 1),
6362                    Some(Op::LoadConst { dst: d, idx })
6363                        if *d == lhs
6364                            && matches!(
6365                                ctx.constants.get(*idx as usize),
6366                                Some(Constant::Text(t)) if t.is_empty()
6367                            )
6368                );
6369            if folds {
6370                display::emit_display_of(code, plan, ctx, rhs, dst as u32)?;
6371                return Ok(Flow::Straight);
6372            }
6373            lower_concat(code, plan, ctx, dst, lhs, rhs)?;
6374            Ok(Flow::Straight)
6375        }
6376        Op::FormatValue {
6377            dst,
6378            src,
6379            spec,
6380            debug_prefix,
6381        } => {
6382            lower_format_value(code, plan, ctx, dst, src, spec, debug_prefix)?;
6383            Ok(Flow::Straight)
6384        }
6385        Op::DeepClone { dst, src } => {
6386            lower_deep_clone(code, kinds, &plan.structs, ctx, plan.num_regs, dst, src)?;
6387            Ok(Flow::Straight)
6388        }
6389        // `copy(x)` — the builtin form of a deep clone (an independent copy of a heap value; the value
6390        // itself for a scalar), the same lowering as `Op::DeepClone`.
6391        Op::CallBuiltin {
6392            dst,
6393            builtin: BuiltinId::Copy,
6394            args_start,
6395            ..
6396        } => {
6397            lower_deep_clone(
6398                code,
6399                kinds,
6400                &plan.structs,
6401                ctx,
6402                plan.num_regs,
6403                dst,
6404                args_start,
6405            )?;
6406            Ok(Flow::Straight)
6407        }
6408        Op::NewStruct { dst, .. } => {
6409            let count = plan.structs.count.get(pc).copied().flatten().unwrap_or(0);
6410            lower_new_struct(code, ctx, plan.num_regs, count, dst);
6411            Ok(Flow::Straight)
6412        }
6413        Op::StructInsert { obj, value, .. } => {
6414            let slot =
6415                plan.structs
6416                    .slot
6417                    .get(pc)
6418                    .copied()
6419                    .flatten()
6420                    .ok_or(WasmLowerError::Unsupported(
6421                        "struct insert with no static slot",
6422                    ))?;
6423            let cow = plan.cow_inserts.get(pc).copied().unwrap_or(true);
6424            let held = tower::field_value(code, plan, ctx, obj, usize::from(slot), value)?;
6425            lower_struct_insert(
6426                code,
6427                kinds,
6428                &plan.structs,
6429                ctx,
6430                plan.num_regs,
6431                slot,
6432                obj,
6433                value,
6434                cow,
6435                held,
6436            )?;
6437            // The field is a second holder of a value that counts its holders — RETAIN, so a later
6438            // write through the register that built it copies first.
6439            if counts_aliases(kinds.get(value as usize)) {
6440                emit_retain(code, ctx, value);
6441            }
6442            // The record owns its field independently of the register that supplied it.
6443            // Replacement and record reclamation release this ownership.
6444            if counted_kind(kinds.get(value as usize)) {
6445                emit_true_retain(code, ctx, value);
6446            }
6447            Ok(Flow::Straight)
6448        }
6449        Op::GetField { dst, obj, field } => {
6450            // A refusal here names the backend's internals, not the author's code. `LOGOS_WASM_TRACE_FIELD`
6451            // prints WHICH access could not resolve, which is the difference between a bisect and a look.
6452            if plan.structs.slot.get(pc).copied().flatten().is_none()
6453                && std::env::var_os("LOGOS_WASM_TRACE_FIELD").is_some()
6454            {
6455                let name = match ctx.constants.get(field as usize) {
6456                    Some(Constant::Text(t)) => t.clone(),
6457                    other => format!("{other:?}"),
6458                };
6459                eprintln!(
6460                    "[wasm] unresolved field access: '{name}' (pc {pc}, obj reg {obj}, kind {:?})",
6461                    kinds.get(obj as usize)
6462                );
6463            }
6464            let slot =
6465                plan.structs
6466                    .slot
6467                    .get(pc)
6468                    .copied()
6469                    .flatten()
6470                    .ok_or(WasmLowerError::Unsupported(
6471                        "field access with no static slot",
6472                    ))?;
6473            // A `ConvergentCount`/`Tally` counter field stores a per-replica counter OBJECT, but reads
6474            // as its Int total (`Σinc − Σdec`): project it here rather than raw-loading the pointer.
6475            let is_counter = plan
6476                .structs
6477                .field_value
6478                .get(pc)
6479                .copied()
6480                .flatten()
6481                .map_or(false, |vr| {
6482                    kinds.get(vr as usize) == Some(Kind::CrdtCounter)
6483                });
6484            if is_counter {
6485                lower_get_counter_total(code, plan, slot, dst, obj)?;
6486            } else {
6487                lower_get_field(code, kinds, slot, dst, obj)?;
6488                // `Let cs be c's items` aliases the field's mutable heap object — RETAIN so a mutation of
6489                // the extracted handle copy-on-writes rather than mutating the field in place. A field
6490                // the place lowering TAKES out, or a transient read ([`transient_reads`]), is no new alias.
6491                let aliases = !plan.place.take.get(pc).copied().unwrap_or(false)
6492                    && !plan.transient.get(dst as usize).copied().unwrap_or(false);
6493                if counts_aliases(kinds.get(dst as usize)) && aliases {
6494                    emit_retain(code, ctx, dst);
6495                }
6496            }
6497            Ok(Flow::Straight)
6498        }
6499        Op::CheckPolicy {
6500            subject,
6501            predicate,
6502            is_capability,
6503            object,
6504            ..
6505        } => {
6506            lower_check_policy(code, plan, ctx, subject, predicate, is_capability, object)?;
6507            Ok(Flow::Straight)
6508        }
6509        Op::CrdtBump {
6510            obj,
6511            field,
6512            amount,
6513            negate,
6514        } => {
6515            lower_crdt_bump(code, plan, ctx, obj, field, amount, negate)?;
6516            Ok(Flow::Straight)
6517        }
6518        // `Merge`/`Converge` of two same-typed counter-CRDT structs. The WASM tier only supports counter
6519        // (`ConvergentCount`/`Tally`) fields, whose merge IS the per-replica-MAX lattice join — so `CrdtJoin`
6520        // (the idempotent join) and `CrdtMerge` are identical here and share `lower_crdt_merge`. A bare-`Int`
6521        // field (where they would differ, MAX vs ADD) is soundly refused by `lower_crdt_merge` for both.
6522        Op::CrdtMerge { target, source } | Op::CrdtJoin { target, source } => {
6523            lower_crdt_merge(code, plan, ctx, target, source)?;
6524            Ok(Flow::Straight)
6525        }
6526        Op::NewCrdt { dst, kind } => {
6527            // A fresh CRDT is empty, and single-replica it IS its underlying collection: an OR-Set
6528            // (0/3) and an RGA sequence (1) are a `[0][0][0]` header, a divergent register (2) an
6529            // empty `Text`, a counter (4/5) a per-replica record object, and a map (6) a map header
6530            // marked SHARED, which keeps it sorted by key and exempt from copy-on-write.
6531            match kind {
6532                0 | 1 | 3 => emit_empty_header(
6533                    code,
6534                    ctx,
6535                    plan.num_regs,
6536                    dst as u32,
6537                    empty_collection_class(kinds.get(dst as usize)),
6538                ),
6539                2 => {
6540                    lower_text_literal(code, ctx, plan.num_regs, b"");
6541                    local_set(code, dst as u32);
6542                }
6543                // A `ConvergentCount` (4) / `Tally` (5) is a STATE-BASED per-replica counter object,
6544                // idempotent under merge (see `emit_new_counter`). Both allocate the same shape (a
6545                // G-Counter is a PN-counter whose `dec` never moves), so a single arm serves both.
6546                4 | 5 => emit_new_counter(code, ctx, plan.num_regs, dst as u32),
6547                6 => {
6548                    // A shared map has the same owned entries and true count as an ordinary map.
6549                    // The sign controls sharing; its low byte still identifies the heap layout.
6550                    emit_empty_header(
6551                        code,
6552                        ctx,
6553                        plan.num_regs,
6554                        dst as u32,
6555                        AllocClass::MapScalarScalar,
6556                    );
6557                    local_get(code, dst as u32);
6558                    i32_const(
6559                        code,
6560                        SHARED_MAP_MARK | i32::from(AllocClass::MapScalarScalar.code()),
6561                    );
6562                    i32_store(code, 12);
6563                }
6564                _ => {
6565                    return Err(WasmLowerError::Unsupported(
6566                        "a CRDT kind this backend does not know",
6567                    ))
6568                }
6569            }
6570            Ok(Flow::Straight)
6571        }
6572        Op::CrdtResolve { obj, field, value } => {
6573            lower_crdt_resolve(code, plan, kinds, obj, field, value)?;
6574            Ok(Flow::Straight)
6575        }
6576        Op::CrdtAppend { seq, value } => {
6577            lower_crdt_append(code, plan, kinds, ctx, seq, value)?;
6578            Ok(Flow::Straight)
6579        }
6580        // ── DETERMINISTIC SINGLE-THREAD CONCURRENCY (matches the seeded cooperative scheduler for the
6581        //    non-blocking guide shapes; the corpus lock proves tw == VM(driven) == AOT). ──
6582        // A `Pipe`/channel is a FIFO queue: `new Pipe` → empty seq, `Send` → append (in place,
6583        // mutable-shared, no COW), `Receive` → pop the FRONT.
6584        Op::ChanNew { dst, .. } => {
6585            emit_empty_header(
6586                code,
6587                ctx,
6588                plan.num_regs,
6589                dst as u32,
6590                empty_collection_class(kinds.get(dst as usize)),
6591            );
6592            Ok(Flow::Straight)
6593        }
6594        Op::ChanSend { chan, val } => {
6595            lower_list_push(code, kinds, ctx, plan.num_regs, chan, val)?;
6596            // S8's true count: the pipe holds the value until it is received.
6597            if counted_kind(kinds.get(val as usize)) {
6598                emit_true_retain(code, ctx, val);
6599            }
6600            Ok(Flow::Straight)
6601        }
6602        Op::ChanRecv { dst, chan } => {
6603            lower_chan_recv(code, kinds, plan.num_regs, dst, chan)?;
6604            // The pipe no longer holds what it handed over.
6605            if counted_kind(kinds.get(chan as usize).and_then(Kind::seq_elem)) {
6606                emit_true_release(code, ctx, |c| local_get(c, dst as u32));
6607            }
6608            Ok(Flow::Straight)
6609        }
6610        // Non-blocking `Try to receive`: a non-empty pipe pops its front value into a fresh Optional
6611        // box (`Some`, handle != 0); an empty pipe yields `Nothing` (handle 0). The single-task
6612        // scheduler never parks a try-recv, so there is no blocking/trap path (unlike `ChanRecv`).
6613        Op::ChanTryRecv { dst, chan } => {
6614            lower_chan_try_recv(code, kinds, ctx, plan.num_regs, dst, chan)?;
6615            Ok(Flow::Straight)
6616        }
6617        // Non-blocking `Try to send`: the unbounded FIFO always has room, so the value is appended (a
6618        // plain queue push) and the success result is `Bool(true)` (an i64 `1`), matching the
6619        // scheduler's `do_try_send`.
6620        Op::ChanTrySend { dst, chan, val } => {
6621            lower_list_push(code, kinds, ctx, plan.num_regs, chan, val)?;
6622            if counted_kind(kinds.get(val as usize)) {
6623                emit_true_retain(code, ctx, val);
6624            }
6625            code.push(0x42); // i64.const 1 — Bool(true) rides an i64 local (0/1)
6626            leb_i64(code, 1);
6627            local_set(code, dst as u32);
6628            Ok(Flow::Straight)
6629        }
6630        // `Close` a pipe: the scheduler's close resumes the closer with `Nothing` and never mutates the
6631        // queue (a closed-and-empty recv still just yields `Nothing`). With no result register and no
6632        // observable queue effect in the deterministic single-task model, it lowers to nothing.
6633        Op::ChanClose { .. } => Ok(Flow::Straight),
6634        // `Launch a task to f(args)` — a fire-and-forget task runs SYNCHRONOUSLY (the deterministic
6635        // scheduler runs each launched task to completion in launch order, which for these
6636        // non-blocking bodies is exactly a call). `SpawnHandle` also yields a dead `Int` dummy handle.
6637        Op::Spawn {
6638            func,
6639            args_start,
6640            arg_count,
6641        } => {
6642            if emit_sync_call(code, plan, ctx, func, args_start, arg_count)? {
6643                code.push(0x1A); // drop the (discarded) result
6644            }
6645            Ok(Flow::Straight)
6646        }
6647        Op::SpawnHandle {
6648            dst,
6649            func,
6650            args_start,
6651            arg_count,
6652        } => {
6653            if emit_sync_call(code, plan, ctx, func, args_start, arg_count)? {
6654                code.push(0x1A); // drop
6655            }
6656            code.push(0x42); // i64.const 0 — the dummy handle
6657            leb_i64(code, 0);
6658            local_set(code, dst as u32);
6659            Ok(Flow::Straight)
6660        }
6661        // `Stop <job>` — the task already ran to completion synchronously, so cancelling is a no-op.
6662        Op::TaskAbort { .. } => Ok(Flow::Straight),
6663        // `Await <task>` for its value — the task ran to completion synchronously at its `SpawnHandle`, so
6664        // awaiting is just reading its handle register (`SpawnHandle` leaves an i64 handle there). No
6665        // compiler emit site produces this today (the language's `Await` lowers to `Select`/`Net` await),
6666        // so it is never exercised — but the emitter handles it (a pass-through), never refuses it.
6667        Op::TaskAwait { dst, handle } => {
6668            local_get(code, handle as u32);
6669            local_set(code, dst as u32);
6670            Ok(Flow::Straight)
6671        }
6672        // `Sleep N` — under the deterministic scheduler a sleep advances VIRTUAL time only (like a
6673        // `Select` `After` arm's tick), with no observable output effect on the non-racing shapes, so
6674        // the AOT lowers it to a no-op — matching the seeded scheduler that drives `vm_outcome_concurrent`.
6675        Op::Sleep { .. } => Ok(Flow::Straight),
6676        // ── DETERMINISTIC `select` (`Await the first of: …`). Each arm registers via a
6677        //    `SelectArm*` op (no code — the winning `SelectWait` reads them back); `SelectWait`
6678        //    resolves the winner exactly as the seeded scheduler does for the non-racing shapes: a
6679        //    recv arm whose queue is non-empty wins (pop-front into its var); otherwise the timeout
6680        //    arm fires. The following per-arm `Eq`/jump dispatch (emitted by the compiler) runs the
6681        //    winning branch's body. ──
6682        Op::SelectArmRecv { .. } | Op::SelectArmTimeout { .. } => Ok(Flow::Straight),
6683        Op::SelectWait { dst_arm } => {
6684            lower_select_wait(code, plan, kinds, blocks, k, pc, dst_arm)?;
6685            Ok(Flow::Straight)
6686        }
6687        // ── DETERMINISTIC OFFLINE NETWORKING with LOOPBACK delivery (matches the interpreter/VM offline
6688        //    `NetInbox` loopback: with no relay, a `Send`/`Stream` delivers into our OWN local inbox and
6689        //    a matching `Await` reads it back — the oracle output is transport-independent). The AOT
6690        //    models the inbox as ONE local FIFO queue whose handle lives in a reserved memory slot
6691        //    (`NET_INBOX_ADDR`, inside the null-reserved low-16 region): `Listen` creates it, `Send`/
6692        //    `Stream` push, `Await` pops. `Connect`/`Sync` remain single-node no-ops. ──
6693        Op::NetConnect { .. } | Op::NetSync { .. } => Ok(Flow::Straight),
6694        Op::NetListen { .. } => {
6695            // Create the empty local inbox FIFO; stash its handle at the reserved slot. A compiler
6696            // scratch slot, not a normally-kinded register — `Raw` (its element kind is not tracked
6697            // the way a declared `Seq`/`Pipe` register's is).
6698            emit_empty_header(code, ctx, plan.num_regs, plan.num_regs + 8, AllocClass::Raw);
6699            i32_const(code, NET_INBOX_ADDR);
6700            local_get(code, plan.num_regs + 8);
6701            i32_store(code, 0);
6702            Ok(Flow::Straight)
6703        }
6704        Op::NetSend { msg, .. } => {
6705            let elem = kinds.get(msg as usize).ok_or(WasmLowerError::Unsupported(
6706                "Send of an unknown-kind message",
6707            ))?;
6708            i32_const(code, NET_INBOX_ADDR);
6709            i32_load(code, 0);
6710            local_set(code, plan.num_regs + 8);
6711            lower_list_push_at(code, elem, ctx, plan.num_regs, plan.num_regs + 8, msg)?;
6712            if counts_aliases(kinds.get(msg as usize)) {
6713                emit_retain(code, ctx, msg);
6714            }
6715            // S8's true count: the inbox holds the message until it is received.
6716            if counted_kind(kinds.get(msg as usize)) {
6717                emit_true_retain(code, ctx, msg);
6718            }
6719            Ok(Flow::Straight)
6720        }
6721        Op::NetStream { values, .. } => {
6722            // A batch STREAM delivers the whole list; loopback pushes the list HANDLE (single-node, no
6723            // framing) so `Await stream` pops the same list — byte-faithful to the frame/deframe round-trip.
6724            let elem = kinds
6725                .get(values as usize)
6726                .ok_or(WasmLowerError::Unsupported(
6727                    "Stream of an unknown-kind list",
6728                ))?;
6729            i32_const(code, NET_INBOX_ADDR);
6730            i32_load(code, 0);
6731            local_set(code, plan.num_regs + 8);
6732            lower_list_push_at(code, elem, ctx, plan.num_regs, plan.num_regs + 8, values)?;
6733            if counts_aliases(kinds.get(values as usize)) {
6734                emit_retain(code, ctx, values);
6735            }
6736            if counted_kind(kinds.get(values as usize)) {
6737                emit_true_retain(code, ctx, values);
6738            }
6739            Ok(Flow::Straight)
6740        }
6741        Op::NetAwait { dst, .. } => {
6742            let elem = kinds.get(dst as usize).ok_or(WasmLowerError::Unsupported(
6743                "Await of an unknown-kind message",
6744            ))?;
6745            i32_const(code, NET_INBOX_ADDR);
6746            i32_load(code, 0);
6747            local_set(code, plan.num_regs + 8);
6748            emit_pop_front(code, elem, plan.num_regs + 8, plan.num_regs + 5, dst as u32)?;
6749            if counts_aliases(kinds.get(dst as usize)) {
6750                emit_retain(code, ctx, dst);
6751            }
6752            Ok(Flow::Straight)
6753        }
6754        Op::NetMakePeer { dst, addr } => {
6755            local_get(code, addr as u32);
6756            local_set(code, dst as u32);
6757            Ok(Flow::Straight)
6758        }
6759        Op::NewInductive {
6760            dst,
6761            ctor,
6762            args_start,
6763            count,
6764            ..
6765        } => {
6766            lower_new_inductive(
6767                code,
6768                kinds,
6769                ctx,
6770                plan.num_regs,
6771                dst,
6772                ctor,
6773                args_start,
6774                count,
6775            )?;
6776            // S8's true count: the variant holds each counted payload value it was built from.
6777            for i in 0..count {
6778                if counted_kind(kinds.get((args_start + i) as usize)) {
6779                    emit_true_retain(code, ctx, args_start + i);
6780                }
6781            }
6782            Ok(Flow::Straight)
6783        }
6784        Op::TestArm {
6785            dst,
6786            target,
6787            variant,
6788        } => {
6789            lower_test_arm(code, kinds, ctx, dst, target, variant)?;
6790            Ok(Flow::Straight)
6791        }
6792        Op::BindArm {
6793            dst, target, index, ..
6794        } => {
6795            lower_bind_arm(code, kinds, ctx, dst, target, index)?;
6796            Ok(Flow::Straight)
6797        }
6798        Op::MakeClosure {
6799            dst,
6800            func,
6801            locals_start,
6802        } => {
6803            lower_make_closure(code, ctx, plan.num_regs, dst, func, locals_start)?;
6804            Ok(Flow::Straight)
6805        }
6806        Op::CallValue {
6807            dst,
6808            callee,
6809            args_start,
6810            arg_count,
6811            ..
6812        } => {
6813            // A heap argument to a closure call gains the closure body's parameter as a second holder
6814            // — RETAIN, like a direct `Call` (value semantics across the closure boundary).
6815            for a in 0..arg_count {
6816                let arg = args_start + a;
6817                if counts_aliases(kinds.get(arg as usize)) {
6818                    emit_retain(code, ctx, arg);
6819                }
6820            }
6821            lower_call_value(code, plan, ctx, pc, dst, callee, args_start, arg_count)?;
6822            Ok(Flow::Straight)
6823        }
6824        Op::IterPop => {
6825            // Unwind exactly this frame, including its snapshot's owned handles.
6826            global_get(code, ctx.iter_global);
6827            i32_load(code, FRAME_PREV);
6828            if let Some(unwind) = ctx.runtime.and_then(|r| r.index(RuntimeFn::IterUnwind)) {
6829                code.push(0x10);
6830                leb_u32(code, unwind);
6831            } else {
6832                global_set(code, ctx.iter_global);
6833            }
6834            Ok(Flow::Straight)
6835        }
6836        Op::LoadNow { dst } => {
6837            let idx = (ctx.host_index)(HostFn::Now)
6838                .ok_or(WasmLowerError::Unsupported("now not imported"))?;
6839            code.push(0x10); // call now -> i64 (Moment)
6840            leb_u32(code, idx);
6841            local_set(code, dst as u32);
6842            Ok(Flow::Straight)
6843        }
6844        Op::GlobalSet { idx, src } => {
6845            // A width mismatch here is the VM's ownership clear: writing one element of a global
6846            // collection compiles to TAKE, MUTATE, PUT BACK, and the take's `nothing` arrives as an
6847            // `i64` zero aimed at the global's own width. It stores a null handle at that width, and
6848            // the global stops being a holder: its true count (S8) drops here and the put-back
6849            // restores it. The copy-on-write counter (word 12) is untouched by a recognised take
6850            // ([`PlaceSites`]) — the hold moves to the taken register and back, so a mutation between
6851            // them sees only real holders; a clear with no recognised take releases the retain its
6852            // read made.
6853            let want = ctx
6854                .global_valtypes
6855                .get(idx as usize)
6856                .copied()
6857                .unwrap_or(I64);
6858            if kinds.valtype(src as usize) != want {
6859                if want == I32 {
6860                    if !plan.place.clear.get(pc).copied().unwrap_or(false) {
6861                        // `if (g != 0) g.extra_refs -= 1` — a null global holds nothing to release, and
6862                        // word 12 of address 0 is not ours to write.
6863                        code.push(0x23); // global.get
6864                        leb_u32(code, idx as u32);
6865                        i32_const(code, 0);
6866                        code.push(0x47); // i32.ne
6867                        code.push(0x04); // if
6868                        code.push(0x40); // void
6869                        code.push(0x23);
6870                        leb_u32(code, idx as u32);
6871                        code.push(0x23);
6872                        leb_u32(code, idx as u32);
6873                        i32_load(code, 12);
6874                        i32_const(code, 0x100); // extra_refs occupies bits 8-31; class (bits 0-7) untouched
6875                        code.push(0x6B); // i32.sub
6876                        i32_store(code, 12);
6877                        code.push(0x0B); // end
6878                    }
6879                    emit_true_release(code, ctx, |c| {
6880                        c.push(0x23); // global.get idx
6881                        leb_u32(c, idx as u32);
6882                    });
6883                    i32_const(code, 0);
6884                } else if want == F64 {
6885                    code.push(0x44);
6886                    code.extend_from_slice(&0f64.to_le_bytes());
6887                } else {
6888                    code.push(0x42); // i64.const 0
6889                    code.push(0x00);
6890                }
6891                code.push(0x24); // global.set
6892                leb_u32(code, idx as u32);
6893                return Ok(Flow::Straight);
6894            }
6895            // Storing a heap handle into a global makes the global a second holder — RETAIN so a later
6896            // mutation through another register copy-on-writes rather than clobbering the global. A
6897            // put-back of what a take moved out is the same holder returning ([`PlaceSites`]).
6898            if counts_aliases(kinds.get(src as usize))
6899                && !plan.place.put_back.get(pc).copied().unwrap_or(false)
6900            {
6901                emit_retain(code, ctx, src);
6902            }
6903            // S8's true count: a DIRECT overwrite (`Set g to newValue`, no preceding take/mutate/
6904            // put-back null) never goes through the width-mismatch branch above, so its OWN release
6905            // of whatever `g` held lives here instead — before the store, so it reads the value
6906            // ABOUT to be replaced, not the new one.
6907            if want == I32 && counted_kind(kinds.get(src as usize)) {
6908                emit_true_release(code, ctx, |c| {
6909                    c.push(0x23);
6910                    leb_u32(c, idx as u32);
6911                });
6912            }
6913            local_get(code, src as u32);
6914            code.push(0x24); // global.set
6915            leb_u32(code, idx as u32);
6916            if counted_kind(kinds.get(src as usize)) {
6917                emit_true_retain(code, ctx, src);
6918            }
6919            Ok(Flow::Straight)
6920        }
6921        Op::Call {
6922            dst,
6923            func,
6924            args_start,
6925            arg_count,
6926        } => {
6927            if ctx.fn_stubbed.get(func as usize).copied().unwrap_or(false) {
6928                code.push(0x00); // unreachable — the reach analysis proved this call never runs
6929                return Ok(Flow::Straight);
6930            }
6931            // Value semantics: a heap argument gains the callee's parameter as a SECOND holder, so
6932            // RETAIN it (bump word 12) before the call. A mutation inside the callee then copy-on-writes
6933            // instead of clobbering the caller's value — the VM's `Rc`-clone-on-argument-bind. A `mutable`
6934            // parameter is no second holder: it is the caller's variable, lent for the call.
6935            let inout = ctx.fn_inout.get(func as usize).cloned().unwrap_or_default();
6936            for a in 0..arg_count {
6937                let arg = args_start + a;
6938                if shares_argument(plan, ctx, func, a, arg) && !inout.contains(&a) {
6939                    emit_retain(code, ctx, arg);
6940                }
6941            }
6942            let pvts = ctx
6943                .fn_param_valtypes
6944                .get(func as usize)
6945                .ok_or(WasmLowerError::Unsupported("call of unknown function"))?;
6946            for a in 0..arg_count {
6947                push_call_argument(code, plan, ctx, func, a, args_start + a)?;
6948            }
6949            code.push(0x10); // call
6950            leb_u32(code, ctx.fn_base + func as u32);
6951            // Each `mutable` parameter's final value sits above the declared result: it goes back into the
6952            // argument register it was lent from, last first.
6953            for p in inout.iter().rev() {
6954                let arg = args_start + p;
6955                if kinds.valtype(arg as usize) != pvts.get(*p as usize).copied().unwrap_or(I64) {
6956                    return Err(WasmLowerError::Unsupported(
6957                        "a `mutable` argument of another type than its parameter",
6958                    ));
6959                }
6960                local_set(code, arg as u32);
6961            }
6962            // A void callee leaves nothing on the stack; only bind a result when it returns one.
6963            if ctx
6964                .fn_results
6965                .get(func as usize)
6966                .copied()
6967                .flatten()
6968                .is_some()
6969            {
6970                local_set(code, dst as u32);
6971            }
6972            Ok(Flow::Straight)
6973        }
6974        Op::CallBuiltin {
6975            dst,
6976            builtin: BuiltinId::Pow,
6977            args_start,
6978            arg_count,
6979        } => lower_pow(code, kinds, ctx, plan.num_regs, dst, args_start, arg_count),
6980        // `parseInt(text)` — a host call: push the Text handle, `call parse_int` → i64.
6981        Op::CallBuiltin {
6982            dst,
6983            builtin: BuiltinId::ParseInt,
6984            args_start,
6985            ..
6986        } => {
6987            let idx = (ctx.host_index)(HostFn::ParseInt)
6988                .ok_or(WasmLowerError::Unsupported("parse_int host not imported"))?;
6989            local_get(code, args_start as u32);
6990            code.push(0x10); // call parse_int
6991            leb_u32(code, idx);
6992            local_set(code, dst as u32);
6993            Ok(Flow::Straight)
6994        }
6995        // `contains(haystack, needle)` — push both Text handles (i32), `call text_contains` → i32 (0/1).
6996        Op::CallBuiltin {
6997            dst,
6998            builtin: BuiltinId::Contains,
6999            args_start,
7000            ..
7001        } => lower_dom_call(code, ctx, dst, HostFn::TextContains, args_start, 2, true),
7002        // DOM: push the arg registers (Element handles i64, Text handles i32) and
7003        // call the `dom_*` host. Creators/getters return a value into `dst`; effect
7004        // ops set `dst` to Nothing (0).
7005        Op::CallBuiltin {
7006            dst,
7007            builtin: BuiltinId::DomBody,
7008            ..
7009        } => lower_dom_call(code, ctx, dst, HostFn::DomBody, 0, 0, true),
7010        Op::CallBuiltin {
7011            dst,
7012            builtin: BuiltinId::DomCreateElement,
7013            args_start,
7014            ..
7015        } => lower_dom_call(
7016            code,
7017            ctx,
7018            dst,
7019            HostFn::DomCreateElement,
7020            args_start,
7021            1,
7022            true,
7023        ),
7024        Op::CallBuiltin {
7025            dst,
7026            builtin: BuiltinId::DomCreateTextNode,
7027            args_start,
7028            ..
7029        } => lower_dom_call(
7030            code,
7031            ctx,
7032            dst,
7033            HostFn::DomCreateTextNode,
7034            args_start,
7035            1,
7036            true,
7037        ),
7038        Op::CallBuiltin {
7039            dst,
7040            builtin: BuiltinId::DomQuerySelector,
7041            args_start,
7042            ..
7043        } => lower_dom_call(
7044            code,
7045            ctx,
7046            dst,
7047            HostFn::DomQuerySelector,
7048            args_start,
7049            1,
7050            true,
7051        ),
7052        Op::CallBuiltin {
7053            dst,
7054            builtin: BuiltinId::DomGetText,
7055            args_start,
7056            ..
7057        } => lower_dom_call(code, ctx, dst, HostFn::DomGetText, args_start, 1, true),
7058        Op::CallBuiltin {
7059            dst,
7060            builtin: BuiltinId::DomGetValue,
7061            args_start,
7062            ..
7063        } => lower_dom_call(code, ctx, dst, HostFn::DomGetValue, args_start, 1, true),
7064        Op::CallBuiltin {
7065            dst,
7066            builtin: BuiltinId::DomSetText,
7067            args_start,
7068            ..
7069        } => lower_dom_call(code, ctx, dst, HostFn::DomSetText, args_start, 2, false),
7070        Op::CallBuiltin {
7071            dst,
7072            builtin: BuiltinId::DomSetHtml,
7073            args_start,
7074            ..
7075        } => lower_dom_call(code, ctx, dst, HostFn::DomSetHtml, args_start, 2, false),
7076        Op::CallBuiltin {
7077            dst,
7078            builtin: BuiltinId::DomClearChildren,
7079            args_start,
7080            ..
7081        } => lower_dom_call(
7082            code,
7083            ctx,
7084            dst,
7085            HostFn::DomClearChildren,
7086            args_start,
7087            1,
7088            false,
7089        ),
7090        Op::CallBuiltin {
7091            dst,
7092            builtin: BuiltinId::DomOnMessage,
7093            args_start,
7094            ..
7095        } => lower_dom_call(code, ctx, dst, HostFn::DomOnMessage, args_start, 2, false),
7096        // `beginPaint` and `moveChildren` are retired: the front end refuses a call to either before
7097        // anything lowers, and their host imports are gone.
7098        Op::CallBuiltin {
7099            builtin: BuiltinId::DomBeginPaint,
7100            ..
7101        } => Err(WasmLowerError::Unsupported("beginPaint is retired")),
7102        Op::CallBuiltin {
7103            builtin: BuiltinId::DomMoveChildren,
7104            ..
7105        } => Err(WasmLowerError::Unsupported("moveChildren is retired")),
7106        Op::CallBuiltin {
7107            dst,
7108            builtin: BuiltinId::DomAppendChild,
7109            args_start,
7110            ..
7111        } => lower_dom_call(code, ctx, dst, HostFn::DomAppendChild, args_start, 2, false),
7112        Op::CallBuiltin {
7113            dst,
7114            builtin: BuiltinId::DomSetValue,
7115            args_start,
7116            ..
7117        } => lower_dom_call(code, ctx, dst, HostFn::DomSetValue, args_start, 2, false),
7118        Op::CallBuiltin {
7119            dst,
7120            builtin: BuiltinId::DomSetChecked,
7121            args_start,
7122            ..
7123        } => lower_dom_call(code, ctx, dst, HostFn::DomSetChecked, args_start, 2, false),
7124        Op::CallBuiltin {
7125            dst,
7126            builtin: BuiltinId::DomPreventDefault,
7127            args_start,
7128            ..
7129        } => lower_dom_call(
7130            code,
7131            ctx,
7132            dst,
7133            HostFn::DomPreventDefault,
7134            args_start,
7135            2,
7136            false,
7137        ),
7138        Op::CallBuiltin {
7139            dst,
7140            builtin: BuiltinId::StorageSet,
7141            args_start,
7142            ..
7143        } => lower_dom_call(code, ctx, dst, HostFn::StorageSet, args_start, 3, false),
7144        Op::CallBuiltin {
7145            dst,
7146            builtin: BuiltinId::StorageRemove,
7147            args_start,
7148            ..
7149        } => lower_dom_call(code, ctx, dst, HostFn::StorageRemove, args_start, 2, false),
7150        Op::CallBuiltin {
7151            dst,
7152            builtin: BuiltinId::StorageGet,
7153            args_start,
7154            ..
7155        } => lower_storage_get(code, ctx, plan.num_regs, dst, args_start),
7156        Op::CallBuiltin {
7157            dst,
7158            builtin: BuiltinId::StorageGetOr,
7159            args_start,
7160            ..
7161        } => lower_storage_get_or(code, ctx, plan.num_regs, dst, args_start),
7162        Op::CallBuiltin {
7163            dst,
7164            builtin: BuiltinId::DomApplyPatches,
7165            args_start,
7166            ..
7167        } => lower_dom_call(code, ctx, dst, HostFn::DomApply, args_start, 1, false),
7168        Op::CallBuiltin {
7169            dst,
7170            builtin: BuiltinId::DomApplyWords,
7171            args_start,
7172            ..
7173        } => lower_dom_call(code, ctx, dst, HostFn::DomApplyWords, args_start, 4, true),
7174        Op::CallBuiltin {
7175            dst,
7176            builtin: BuiltinId::DomSetAttribute,
7177            args_start,
7178            ..
7179        } => {
7180            // A boolean HTML attribute (`disabled={not formValid}`) hands its raw `Bool` value
7181            // straight to this SAME builtin by design (`lgx_lower.rs`'s own comment) — `Bool` is
7182            // `i64` here, and `dom_set_attribute`'s ABI is fixed at `i32 Text`, so that specific
7183            // shape routes to `DomSetBoolAttribute` instead. See its own doc for why.
7184            let host = if kinds.get(args_start as usize + 2) == Some(Kind::Bool) {
7185                HostFn::DomSetBoolAttribute
7186            } else {
7187                HostFn::DomSetAttribute
7188            };
7189            lower_dom_call(code, ctx, dst, host, args_start, 3, false)
7190        }
7191        Op::CallBuiltin {
7192            dst,
7193            builtin: BuiltinId::DomAddEventListener,
7194            args_start,
7195            ..
7196        } => lower_dom_call(
7197            code,
7198            ctx,
7199            dst,
7200            HostFn::DomAddEventListener,
7201            args_start,
7202            3,
7203            false,
7204        ),
7205        Op::CallBuiltin {
7206            dst,
7207            builtin: BuiltinId::DomListenFlags,
7208            args_start,
7209            ..
7210        } => lower_dom_call(code, ctx, dst, HostFn::DomListenFlags, args_start, 3, false),
7211        Op::CallBuiltin {
7212            dst,
7213            builtin: BuiltinId::DomEnterValue,
7214            args_start,
7215            ..
7216        } => lower_dom_call(code, ctx, dst, HostFn::DomEnterValue, args_start, 3, true),
7217        Op::CallBuiltin {
7218            dst,
7219            builtin: BuiltinId::DomDispatchEntry,
7220            args_start,
7221            ..
7222        } => lower_dispatch_entry(code, ctx, plan.num_regs, dst, args_start),
7223        Op::CallBuiltin {
7224            dst,
7225            builtin: BuiltinId::DomEventValue,
7226            args_start,
7227            ..
7228        } => lower_dom_call(code, ctx, dst, HostFn::DomEventValue, args_start, 1, true),
7229        Op::CallBuiltin {
7230            dst,
7231            builtin: BuiltinId::DomEventKey,
7232            args_start,
7233            ..
7234        } => lower_dom_call(code, ctx, dst, HostFn::DomEventKey, args_start, 1, true),
7235        Op::CallBuiltin {
7236            dst,
7237            builtin: BuiltinId::DomEventTarget,
7238            args_start,
7239            ..
7240        } => lower_dom_call(code, ctx, dst, HostFn::DomEventTarget, args_start, 1, true),
7241        Op::CallBuiltin {
7242            dst,
7243            builtin: BuiltinId::DomFetchText,
7244            args_start,
7245            ..
7246        } => lower_dom_call(code, ctx, dst, HostFn::DomFetchStart, args_start, 2, false),
7247        Op::CallBuiltin {
7248            dst,
7249            builtin: BuiltinId::DomResponseText,
7250            ..
7251        } => lower_dom_call(code, ctx, dst, HostFn::DomResponseText, 0, 0, true),
7252        // The correlated fetch contract — the same push-args-and-call shape.
7253        Op::CallBuiltin {
7254            dst,
7255            builtin: BuiltinId::DomFetchSend,
7256            args_start,
7257            ..
7258        } => lower_dom_call(code, ctx, dst, HostFn::DomFetchSend, args_start, 5, true),
7259        Op::CallBuiltin {
7260            dst,
7261            builtin: BuiltinId::DomResponseStatus,
7262            args_start,
7263            ..
7264        } => lower_dom_call(
7265            code,
7266            ctx,
7267            dst,
7268            HostFn::DomResponseStatus,
7269            args_start,
7270            1,
7271            true,
7272        ),
7273        Op::CallBuiltin {
7274            dst,
7275            builtin: BuiltinId::DomResponseBody,
7276            args_start,
7277            ..
7278        } => lower_dom_call(code, ctx, dst, HostFn::DomResponseBody, args_start, 1, true),
7279        Op::CallBuiltin {
7280            dst,
7281            builtin: BuiltinId::DomResponseHeader,
7282            args_start,
7283            ..
7284        } => lower_dom_call(
7285            code,
7286            ctx,
7287            dst,
7288            HostFn::DomResponseHeader,
7289            args_start,
7290            2,
7291            true,
7292        ),
7293        Op::CallBuiltin {
7294            dst,
7295            builtin: BuiltinId::DomResponseError,
7296            args_start,
7297            ..
7298        } => lower_dom_call(
7299            code,
7300            ctx,
7301            dst,
7302            HostFn::DomResponseError,
7303            args_start,
7304            1,
7305            true,
7306        ),
7307        Op::CallBuiltin {
7308            dst,
7309            builtin: BuiltinId::DomFetchAbort,
7310            args_start,
7311            ..
7312        } => lower_dom_call(code, ctx, dst, HostFn::DomFetchAbort, args_start, 1, false),
7313        Op::CallBuiltin {
7314            dst,
7315            builtin: BuiltinId::DomFetchSetTimeout,
7316            args_start,
7317            ..
7318        } => lower_dom_call(
7319            code,
7320            ctx,
7321            dst,
7322            HostFn::DomFetchSetTimeout,
7323            args_start,
7324            2,
7325            false,
7326        ),
7327        // The history/location router — the same push-args-and-call shape. path/query
7328        // return a Text handle into `dst`; navigate/replace/on_route are effects.
7329        Op::CallBuiltin {
7330            dst,
7331            builtin: BuiltinId::DomRoutePath,
7332            ..
7333        } => lower_dom_call(code, ctx, dst, HostFn::DomRoutePath, 0, 0, true),
7334        Op::CallBuiltin {
7335            dst,
7336            builtin: BuiltinId::DomRouteQuery,
7337            args_start,
7338            ..
7339        } => lower_dom_call(code, ctx, dst, HostFn::DomRouteQuery, args_start, 1, true),
7340        Op::CallBuiltin {
7341            dst,
7342            builtin: BuiltinId::DomNavigate,
7343            args_start,
7344            ..
7345        } => lower_dom_call(code, ctx, dst, HostFn::DomNavigate, args_start, 1, false),
7346        Op::CallBuiltin {
7347            dst,
7348            builtin: BuiltinId::DomAssignLocation,
7349            args_start,
7350            ..
7351        } => lower_dom_call(
7352            code,
7353            ctx,
7354            dst,
7355            HostFn::DomAssignLocation,
7356            args_start,
7357            1,
7358            false,
7359        ),
7360        // ★ THE USED-WALK ARM ABOVE AND THIS ONE MUST NAME THE SAME `HostFn`. A copy-paste that
7361        // notes one import and lowers another is invisible to every lock and calls the wrong host.
7362        Op::CallBuiltin {
7363            dst,
7364            builtin: BuiltinId::DomSetTitle,
7365            args_start,
7366            ..
7367        } => lower_dom_call(code, ctx, dst, HostFn::DomSetTitle, args_start, 1, false),
7368        Op::CallBuiltin {
7369            dst,
7370            builtin: BuiltinId::DomSetHeadHtml,
7371            args_start,
7372            ..
7373        } => lower_dom_call(code, ctx, dst, HostFn::DomSetHeadHtml, args_start, 1, false),
7374        Op::CallBuiltin {
7375            dst,
7376            builtin: BuiltinId::DomReload,
7377            args_start,
7378            ..
7379        } => lower_dom_call(code, ctx, dst, HostFn::DomReload, args_start, 0, false),
7380        Op::CallBuiltin {
7381            dst,
7382            builtin: BuiltinId::DomGoBack,
7383            args_start,
7384            ..
7385        } => lower_dom_call(code, ctx, dst, HostFn::DomGoBack, args_start, 0, false),
7386        // RETURNS A VALUE — the `true` here and `Kind::Text` in `kind.rs` must agree, or the
7387        // destination local is typed for a handle the call never leaves on the stack.
7388        Op::CallBuiltin {
7389            dst,
7390            builtin: BuiltinId::DomGetAttribute,
7391            args_start,
7392            ..
7393        } => lower_dom_call(code, ctx, dst, HostFn::DomGetAttribute, args_start, 2, true),
7394        Op::CallBuiltin {
7395            dst,
7396            builtin: BuiltinId::DomOnWindowEvent,
7397            args_start,
7398            ..
7399        } => lower_dom_call(
7400            code,
7401            ctx,
7402            dst,
7403            HostFn::DomOnWindowEvent,
7404            args_start,
7405            2,
7406            false,
7407        ),
7408        Op::CallBuiltin {
7409            dst,
7410            builtin: BuiltinId::DomScrollGap,
7411            args_start,
7412            ..
7413        } => lower_dom_call(code, ctx, dst, HostFn::DomScrollGap, args_start, 1, true),
7414        Op::CallBuiltin {
7415            dst,
7416            builtin: BuiltinId::DomSetInterval,
7417            args_start,
7418            ..
7419        } => lower_dom_call(code, ctx, dst, HostFn::DomSetInterval, args_start, 2, false),
7420        Op::CallBuiltin {
7421            dst,
7422            builtin: BuiltinId::DomEventFileName,
7423            args_start,
7424            ..
7425        } => lower_dom_call(
7426            code,
7427            ctx,
7428            dst,
7429            HostFn::DomEventFileName,
7430            args_start,
7431            1,
7432            true,
7433        ),
7434        Op::CallBuiltin {
7435            dst,
7436            builtin: BuiltinId::DomEventFileSize,
7437            args_start,
7438            ..
7439        } => lower_dom_call(
7440            code,
7441            ctx,
7442            dst,
7443            HostFn::DomEventFileSize,
7444            args_start,
7445            1,
7446            true,
7447        ),
7448        Op::CallBuiltin {
7449            dst,
7450            builtin: BuiltinId::DomEventFileType,
7451            args_start,
7452            ..
7453        } => lower_dom_call(
7454            code,
7455            ctx,
7456            dst,
7457            HostFn::DomEventFileType,
7458            args_start,
7459            1,
7460            true,
7461        ),
7462        Op::CallBuiltin {
7463            dst,
7464            builtin: BuiltinId::DomEventFileBytes,
7465            args_start,
7466            ..
7467        } => lower_dom_call(
7468            code,
7469            ctx,
7470            dst,
7471            HostFn::DomEventFileBytes,
7472            args_start,
7473            1,
7474            true,
7475        ),
7476        Op::CallBuiltin {
7477            dst,
7478            builtin: BuiltinId::DomElementCommand,
7479            args_start,
7480            ..
7481        } => lower_dom_call(
7482            code,
7483            ctx,
7484            dst,
7485            HostFn::DomElementCommand,
7486            args_start,
7487            2,
7488            false,
7489        ),
7490        Op::CallBuiltin {
7491            dst,
7492            builtin: BuiltinId::DomClipboardWrite,
7493            args_start,
7494            ..
7495        } => lower_dom_call(
7496            code,
7497            ctx,
7498            dst,
7499            HostFn::DomClipboardWrite,
7500            args_start,
7501            1,
7502            false,
7503        ),
7504        Op::CallBuiltin {
7505            dst,
7506            builtin: BuiltinId::DomDownloadFile,
7507            args_start,
7508            ..
7509        } => lower_dom_call(
7510            code,
7511            ctx,
7512            dst,
7513            HostFn::DomDownloadFile,
7514            args_start,
7515            2,
7516            false,
7517        ),
7518        Op::CallBuiltin {
7519            dst,
7520            builtin: BuiltinId::DomNotify,
7521            args_start,
7522            ..
7523        } => lower_dom_call(code, ctx, dst, HostFn::DomNotify, args_start, 2, false),
7524        Op::CallBuiltin {
7525            dst,
7526            builtin: BuiltinId::DomPublish,
7527            args_start,
7528            ..
7529        } => lower_dom_call(code, ctx, dst, HostFn::DomPublish, args_start, 2, false),
7530        Op::CallBuiltin {
7531            dst,
7532            builtin: BuiltinId::NoteTurn,
7533            args_start,
7534            ..
7535        } => lower_dom_call(code, ctx, dst, HostFn::DomNoteTurn, args_start, 4, false),
7536        Op::CallBuiltin {
7537            dst,
7538            builtin: BuiltinId::DomJournalDetail,
7539            args_start,
7540            ..
7541        } => lower_dom_call(
7542            code,
7543            ctx,
7544            dst,
7545            HostFn::DomJournalDetail,
7546            args_start,
7547            0,
7548            true,
7549        ),
7550        Op::CallBuiltin {
7551            dst,
7552            builtin: BuiltinId::DomWakeAfter,
7553            args_start,
7554            ..
7555        } => lower_dom_call(code, ctx, dst, HostFn::DomWakeAfter, args_start, 1, false),
7556        Op::CallBuiltin {
7557            dst,
7558            builtin: BuiltinId::RandomInt,
7559            args_start,
7560            ..
7561        } => lower_dom_call(code, ctx, dst, HostFn::RandomInt, args_start, 2, true),
7562        Op::CallBuiltin {
7563            dst,
7564            builtin: BuiltinId::EnvHas,
7565            args_start,
7566            ..
7567        } => lower_env_has(code, ctx, dst, args_start),
7568        Op::CallBuiltin {
7569            dst,
7570            builtin: BuiltinId::EnvValue,
7571            args_start,
7572            ..
7573        } => lower_env_value(code, ctx, plan.num_regs, dst, args_start),
7574        Op::CallBuiltin {
7575            dst,
7576            builtin: BuiltinId::TimeNow,
7577            args_start,
7578            ..
7579        } => lower_dom_call(code, ctx, dst, HostFn::TimeNow, args_start, 0, true),
7580        Op::CallBuiltin {
7581            dst,
7582            builtin: BuiltinId::DomReplaceRoute,
7583            args_start,
7584            ..
7585        } => lower_dom_call(
7586            code,
7587            ctx,
7588            dst,
7589            HostFn::DomReplaceRoute,
7590            args_start,
7591            1,
7592            false,
7593        ),
7594        Op::CallBuiltin {
7595            dst,
7596            builtin: BuiltinId::DomOnRoute,
7597            args_start,
7598            ..
7599        } => lower_dom_call(code, ctx, dst, HostFn::DomOnRoute, args_start, 1, false),
7600        // The reactive-signal dialect is retired: these fifteen `BuiltinId`s are unreachable from
7601        // any program written today (`builtin_from_name` maps no spelling to them), kept only so
7602        // bincode does not renumber every `BuiltinId` after them (`builtin_wire_id_lock`). Their
7603        // WASM host imports are gone too, so lowering one refuses rather than looking one up.
7604        Op::CallBuiltin {
7605            builtin:
7606                BuiltinId::SignalNew
7607                | BuiltinId::SignalSet
7608                | BuiltinId::SignalGetInt
7609                | BuiltinId::SignalGetText
7610                | BuiltinId::SignalBeginRender
7611                | BuiltinId::SignalNewText
7612                | BuiltinId::SignalSetText
7613                | BuiltinId::SignalEnterComponent
7614                | BuiltinId::SignalExitComponent
7615                | BuiltinId::SignalNewSeq
7616                | BuiltinId::SignalGetSeq
7617                | BuiltinId::SignalSetSeq
7618                | BuiltinId::SignalNewFloat
7619                | BuiltinId::SignalGetFloat
7620                | BuiltinId::SignalSetFloat,
7621            ..
7622        } => Err(WasmLowerError::Unsupported(
7623            "the reactive-signal dialect is retired",
7624        )),
7625        // `parseFloat(text) -> Float` — the host parses the `Text` handle (`str::parse::<f64>` after a
7626        // trim, matching the VM), returning the f64 directly.
7627        Op::CallBuiltin {
7628            dst,
7629            builtin: BuiltinId::ParseFloat,
7630            args_start,
7631            ..
7632        } => {
7633            let idx = (ctx.host_index)(HostFn::ParseFloat)
7634                .ok_or(WasmLowerError::Unsupported("parse_float host not imported"))?;
7635            local_get(code, args_start as u32);
7636            code.push(0x10); // call parse_float
7637            leb_u32(code, idx);
7638            local_set(code, dst as u32);
7639            Ok(Flow::Straight)
7640        }
7641        // `readReals(path) -> Seq of Real` — the host reads the file and returns the sequence's handle.
7642        Op::CallBuiltin {
7643            dst,
7644            builtin: BuiltinId::ReadReals,
7645            args_start,
7646            ..
7647        } => {
7648            let idx = (ctx.host_index)(HostFn::ReadReals)
7649                .ok_or(WasmLowerError::Unsupported("read_reals host not imported"))?;
7650            local_get(code, args_start as u32);
7651            code.push(0x10); // call read_reals
7652            leb_u32(code, idx);
7653            local_set(code, dst as u32);
7654            Ok(Flow::Straight)
7655        }
7656        // `chr(code) -> Text` — a one-character Text built inline from the Unicode scalar value
7657        // (`lower_chr`: UTF-8 encode + a fresh Text object), trapping on an invalid code point.
7658        Op::CallBuiltin {
7659            dst,
7660            builtin: BuiltinId::Chr,
7661            args_start,
7662            ..
7663        } => {
7664            lower_chr(code, ctx, plan.num_regs, dst, args_start);
7665            Ok(Flow::Straight)
7666        }
7667        // `parse_timestamp(text) -> Moment` — the host parses the RFC-3339 `Text` handle to nanoseconds.
7668        Op::CallBuiltin {
7669            dst,
7670            builtin: BuiltinId::ParseTimestamp,
7671            args_start,
7672            ..
7673        } => {
7674            let idx = (ctx.host_index)(HostFn::ParseTimestamp).ok_or(
7675                WasmLowerError::Unsupported("parse_timestamp host not imported"),
7676            )?;
7677            local_get(code, args_start as u32);
7678            code.push(0x10); // call parse_timestamp
7679            leb_u32(code, idx);
7680            local_set(code, dst as u32);
7681            Ok(Flow::Straight)
7682        }
7683        // `writeWireResidual(text) -> Int` — frame the Text's bytes (`[len:u32][bytes]`) out to the host
7684        // wire sink (`write_wire_residual(data_ptr, len)`, returning the byte count), the residual-emit
7685        // half of the wire-program protocol. Requires a `Text` argument (its `[len@0][…][data_ptr@8]`
7686        // header is read in place); a non-Text is refused, never mis-lowered.
7687        Op::CallBuiltin {
7688            dst,
7689            builtin: BuiltinId::WriteWireResidual,
7690            args_start,
7691            ..
7692        } => {
7693            if kinds.get(args_start as usize) != Some(Kind::Text) {
7694                return Err(WasmLowerError::Unsupported(
7695                    "writeWireResidual requires a Text argument",
7696                ));
7697            }
7698            let idx = (ctx.host_index)(HostFn::WriteWireResidual).ok_or(
7699                WasmLowerError::Unsupported("write_wire_residual host not imported"),
7700            )?;
7701            local_get(code, args_start as u32);
7702            i32_load(code, 8); // the Text's data_ptr
7703            local_get(code, args_start as u32);
7704            i32_load(code, 0); // the Text's byte length
7705            code.push(0x10); // call write_wire_residual → the byte count
7706            leb_u32(code, idx);
7707            local_set(code, dst as u32);
7708            Ok(Flow::Straight)
7709        }
7710        // Calendar/clock component extractors on a `Moment` (`the year of m`, …) → the single
7711        // `temporal_component(nanos, which)` host. Each builtin passes a distinct `which` selector; the
7712        // host computes via the same `temporal::*` the VM uses. A `Date` argument (whose hour/min/sec
7713        // error and whose others need a days→civil path) is not yet lowered — it is refused, not
7714        // mis-lowered, so the corpus biconditional stays sound.
7715        Op::CallBuiltin {
7716            dst,
7717            builtin:
7718                b @ (BuiltinId::YearOf
7719                | BuiltinId::MonthOf
7720                | BuiltinId::DayOf
7721                | BuiltinId::WeekdayOf
7722                | BuiltinId::HourOf
7723                | BuiltinId::MinuteOf
7724                | BuiltinId::SecondOf
7725                | BuiltinId::WeekOf
7726                | BuiltinId::QuarterOf),
7727            args_start,
7728            ..
7729        } => {
7730            let which: i32 = match b {
7731                BuiltinId::YearOf => 0,
7732                BuiltinId::MonthOf => 1,
7733                BuiltinId::DayOf => 2,
7734                BuiltinId::HourOf => 3,
7735                BuiltinId::MinuteOf => 4,
7736                BuiltinId::SecondOf => 5,
7737                BuiltinId::WeekdayOf => 6,
7738                BuiltinId::WeekOf => 7,
7739                BuiltinId::QuarterOf => 8,
7740                _ => unreachable!(),
7741            };
7742            match kinds.get(args_start as usize) {
7743                Some(Kind::Moment) => {
7744                    let idx = (ctx.host_index)(HostFn::TemporalComponent).ok_or(
7745                        WasmLowerError::Unsupported("temporal_component host not imported"),
7746                    )?;
7747                    local_get(code, args_start as u32); // the Moment (i64 nanoseconds)
7748                    i32_const(code, which);
7749                    code.push(0x10); // call temporal_component
7750                    leb_u32(code, idx);
7751                    local_set(code, dst as u32);
7752                }
7753                // A `Date` (days since epoch): the day-based components go through
7754                // `temporal_component_date`; hour/minute/second have no meaning on a Date (the VM
7755                // errors), so they are refused rather than mis-lowered.
7756                Some(Kind::Date) => {
7757                    if matches!(
7758                        b,
7759                        BuiltinId::HourOf | BuiltinId::MinuteOf | BuiltinId::SecondOf
7760                    ) {
7761                        return Err(WasmLowerError::Unsupported("clock component (hour/minute/second) of a Date — a Date has no time-of-day"));
7762                    }
7763                    let idx = (ctx.host_index)(HostFn::TemporalComponentDate).ok_or(
7764                        WasmLowerError::Unsupported("temporal_component_date host not imported"),
7765                    )?;
7766                    local_get(code, args_start as u32); // the Date (i32 days since epoch)
7767                    i32_const(code, which);
7768                    code.push(0x10); // call temporal_component_date
7769                    leb_u32(code, idx);
7770                    local_set(code, dst as u32);
7771                }
7772                _ => {
7773                    return Err(WasmLowerError::Unsupported(
7774                        "temporal component of a non-temporal value",
7775                    ));
7776                }
7777            }
7778            Ok(Flow::Straight)
7779        }
7780        // Moment arithmetic + calendar/clock extraction — SELF-CONTAINED i64/i32, matching the VM's
7781        // `builtins.rs` exactly (no host, no runtime):
7782        //   `seconds_between(a, b) = (b - a) / 1e9`             (truncating i64 div) -> Int
7783        //   `add_seconds(m, n)     = m + n * 1e9`                                    -> Moment
7784        //   `date_of(m)            = m.div_euclid(NANOS_PER_DAY) as i32`  (FLOOR div) -> Date
7785        //   `time_of(m)            = m.rem_euclid(NANOS_PER_DAY)`  (non-neg remainder) -> Time
7786        // Each requires a `Moment` first argument (the VM errors otherwise), so a non-Moment is refused,
7787        // never mis-lowered. `div_euclid`/`rem_euclid` are open-coded branchlessly (the divisor is the
7788        // positive constant `NANOS_PER_DAY`): `floor = trunc - (rem < 0)`, `euclid_rem = rem + D·(rem < 0)`.
7789        Op::CallBuiltin {
7790            dst,
7791            builtin:
7792                b @ (BuiltinId::SecondsBetween
7793                | BuiltinId::AddSeconds
7794                | BuiltinId::DateOf
7795                | BuiltinId::TimeOf),
7796            args_start,
7797            ..
7798        } => {
7799            const NANOS_PER_DAY: i64 = 86_400_000_000_000;
7800            const NANOS_PER_SEC: i64 = 1_000_000_000;
7801            if kinds.get(args_start as usize) != Some(Kind::Moment) {
7802                return Err(WasmLowerError::Unsupported(
7803                    "temporal arithmetic requires a Moment argument",
7804                ));
7805            }
7806            let i64c = |code: &mut Vec<u8>, v: i64| {
7807                code.push(0x42); // i64.const
7808                leb_i64(code, v);
7809            };
7810            match b {
7811                BuiltinId::SecondsBetween => {
7812                    local_get(code, (args_start + 1) as u32); // b
7813                    local_get(code, args_start as u32); // a
7814                    code.push(0x7D); // i64.sub  → b - a
7815                    i64c(code, NANOS_PER_SEC);
7816                    code.push(0x7F); // i64.div_s → (b - a) / 1e9
7817                }
7818                BuiltinId::AddSeconds => {
7819                    local_get(code, args_start as u32); // m
7820                    local_get(code, (args_start + 1) as u32); // n
7821                    i64c(code, NANOS_PER_SEC);
7822                    code.push(0x7E); // i64.mul → n * 1e9
7823                    code.push(0x7C); // i64.add → m + n*1e9
7824                }
7825                BuiltinId::DateOf => {
7826                    local_get(code, args_start as u32);
7827                    i64c(code, NANOS_PER_DAY);
7828                    code.push(0x7F); // i64.div_s → q_trunc
7829                    local_get(code, args_start as u32);
7830                    i64c(code, NANOS_PER_DAY);
7831                    code.push(0x81); // i64.rem_s → r_trunc
7832                    i64c(code, 0);
7833                    code.push(0x53); // i64.lt_s → (r_trunc < 0):i32
7834                    code.push(0xAD); // i64.extend_i32_u → 0/1 : i64
7835                    code.push(0x7D); // i64.sub → q_trunc - (r_trunc<0) = floor(m/D)
7836                    code.push(0xA7); // i32.wrap_i64 → i32 days-since-epoch (Date)
7837                }
7838                BuiltinId::TimeOf => {
7839                    local_get(code, args_start as u32);
7840                    i64c(code, NANOS_PER_DAY);
7841                    code.push(0x81); // i64.rem_s → r_trunc
7842                    local_get(code, args_start as u32);
7843                    i64c(code, NANOS_PER_DAY);
7844                    code.push(0x81); // i64.rem_s → r_trunc (again, as the addend base)
7845                    i64c(code, 0);
7846                    code.push(0x53); // i64.lt_s → (r_trunc < 0):i32
7847                    code.push(0xAD); // i64.extend_i32_u → 0/1 : i64
7848                    i64c(code, NANOS_PER_DAY);
7849                    code.push(0x7E); // i64.mul → D·(r_trunc<0)
7850                    code.push(0x7C); // i64.add → r_trunc + D·(r_trunc<0) = rem_euclid
7851                }
7852                _ => unreachable!(),
7853            }
7854            local_set(code, dst as u32);
7855            Ok(Flow::Straight)
7856        }
7857        // LINKER-mode extended temporal — the calendar logic lives in `base::temporal`, so these
7858        // delegate to it via a runtime call (guaranteeing bit-identity with the VM): `format_timestamp(m)`
7859        // → a `Text` handle (RFC-3339 UTC), `months_between`/`years_between`(a, b) → an `Int`. Each needs a
7860        // `Moment` argument and the linker; a self-contained module refuses them rather than mis-lowering.
7861        Op::CallBuiltin {
7862            dst,
7863            builtin:
7864                b @ (BuiltinId::FormatTimestamp
7865                | BuiltinId::MonthsBetween
7866                | BuiltinId::YearsBetween
7867                | BuiltinId::InZone
7868                | BuiltinId::LocalInstant),
7869            args_start,
7870            ..
7871        } => {
7872            if !ctx.linked {
7873                return Err(WasmLowerError::Unsupported("format_timestamp/months_between/years_between/in_zone/local_instant need the linked runtime (base::temporal)"));
7874            }
7875            if kinds.get(args_start as usize) != Some(Kind::Moment) {
7876                return Err(WasmLowerError::Unsupported(
7877                    "extended temporal requires a Moment argument",
7878                ));
7879            }
7880            let (rt, two_args) = match b {
7881                BuiltinId::FormatTimestamp => (HostFn::FormatTimestampRt, false),
7882                BuiltinId::MonthsBetween => (HostFn::MonthsBetweenRt, true),
7883                BuiltinId::YearsBetween => (HostFn::YearsBetweenRt, true),
7884                // `in_zone`/`local_instant` take a Moment + a zone-name Text (the runtime reads the Text
7885                // handle from the shared memory), so the 2nd argument must be a `Text`.
7886                BuiltinId::InZone => (HostFn::InZoneRt, true),
7887                BuiltinId::LocalInstant => (HostFn::LocalInstantRt, true),
7888                _ => unreachable!(),
7889            };
7890            if matches!(b, BuiltinId::InZone | BuiltinId::LocalInstant)
7891                && kinds.get((args_start + 1) as usize) != Some(Kind::Text)
7892            {
7893                return Err(WasmLowerError::Unsupported(
7894                    "in_zone/local_instant require a Text zone name",
7895                ));
7896            }
7897            let idx = (ctx.host_index)(rt).ok_or(WasmLowerError::Unsupported(
7898                "extended temporal runtime fn not imported",
7899            ))?;
7900            local_get(code, args_start as u32);
7901            if two_args {
7902                local_get(code, (args_start + 1) as u32);
7903            }
7904            code.push(0x10); // call the logos_rt_* runtime fn
7905            leb_u32(code, idx);
7906            local_set(code, dst as u32);
7907            Ok(Flow::Straight)
7908        }
7909        // Civil-component constructors (LINKER MODE): `makeDate(y,m,d)`→a `Date`, `makeMoment(y,m,d,h,mi,s)`
7910        // →a `Moment`. All arguments are `Int`s; the calendar core (`days_from_civil`) lives in
7911        // `base::temporal`, so a self-contained module refuses them (like `format_timestamp`/`months_between`),
7912        // never mis-lowering. Each is a single `logos_rt_make_*` call, so the tiers cannot drift.
7913        Op::CallBuiltin {
7914            dst,
7915            builtin: b @ (BuiltinId::MakeDate | BuiltinId::MakeMoment),
7916            args_start,
7917            ..
7918        } => {
7919            if !ctx.linked {
7920                return Err(WasmLowerError::Unsupported(
7921                    "makeDate/makeMoment need the linked runtime (base::temporal)",
7922                ));
7923            }
7924            let (rt, argc) = match b {
7925                BuiltinId::MakeDate => (HostFn::MakeDateRt, 3u32),
7926                BuiltinId::MakeMoment => (HostFn::MakeMomentRt, 6u32),
7927                _ => unreachable!(),
7928            };
7929            let idx = (ctx.host_index)(rt).ok_or(WasmLowerError::Unsupported(
7930                "date constructor runtime fn not imported",
7931            ))?;
7932            for i in 0..argc {
7933                local_get(code, args_start as u32 + i);
7934            }
7935            code.push(0x10); // call the logos_rt_make_* runtime fn
7936            leb_u32(code, idx);
7937            local_set(code, dst as u32);
7938            Ok(Flow::Straight)
7939        }
7940        // The general SIMD lane vocabulary (`base::LanesVal`, LINKER MODE): constructors (`lanes16Word8`/
7941        // `lanes8Word32`/`lanes4Word64` from a `Seq`, `splat16Word8`/`splat8Word32` from an `Int`) and the
7942        // extractors (`seqOfLanes16W8`/`seqOfLanes8` → a `Seq`) take one argument; the byte/word-lane ops
7943        // (`shuffle16`/`interleave*`/`byteAdd16`/`maddubs16`/`packus16`) and `shrBytes16` take two. Each is
7944        // a single `logos_rt_lanes_*` call delegating to the pure-Rust `base::word` spec.
7945        Op::CallBuiltin {
7946            dst,
7947            builtin: b,
7948            args_start,
7949            ..
7950        } if ctx.linked && lanes_v_host_fn(b).is_some() => {
7951            let rt = lanes_v_host_fn(b).expect("guarded by lanes_v_host_fn(b).is_some()");
7952            let idx = (ctx.host_index)(rt).ok_or(WasmLowerError::Unsupported(
7953                "lane-vector runtime fn not imported",
7954            ))?;
7955            let two = matches!(
7956                b,
7957                BuiltinId::Shuffle16
7958                    | BuiltinId::InterleaveLo16
7959                    | BuiltinId::InterleaveHi16
7960                    | BuiltinId::ByteAdd16
7961                    | BuiltinId::Maddubs16
7962                    | BuiltinId::Packus16
7963                    | BuiltinId::ShrBytes16
7964            );
7965            local_get(code, args_start as u32);
7966            if two {
7967                local_get(code, (args_start + 1) as u32);
7968            }
7969            code.push(0x10); // call the logos_rt_lanes_* runtime fn
7970            leb_u32(code, idx);
7971            local_set(code, dst as u32);
7972            Ok(Flow::Straight)
7973        }
7974        // Money FX (LINKER MODE, over `base::money`'s ambient rate table): `set_rate(code, rate)` installs
7975        // one rate (coercing the rate arg to a `Rational` handle IN-PLACE by kind — `Int`→`rational_from_i64`,
7976        // `Decimal`→`decimal_to_rational`, `Rational`→as-is), returning the `Nothing` handle (0).
7977        Op::CallBuiltin {
7978            dst,
7979            builtin: BuiltinId::SetRate,
7980            args_start,
7981            ..
7982        } if ctx.linked => {
7983            let set_idx = (ctx.host_index)(HostFn::MoneySetRate).ok_or(
7984                WasmLowerError::Unsupported("set_rate runtime fn not imported"),
7985            )?;
7986            local_get(code, args_start as u32); // the currency-code Text handle
7987            match kinds.get((args_start + 1) as usize) {
7988                Some(Kind::Rational) => local_get(code, (args_start + 1) as u32),
7989                Some(Kind::Int) => {
7990                    let c = (ctx.host_index)(HostFn::RationalFromI64).ok_or(
7991                        WasmLowerError::Unsupported("rational_from_i64 not imported"),
7992                    )?;
7993                    local_get(code, (args_start + 1) as u32);
7994                    code.push(0x10);
7995                    leb_u32(code, c);
7996                }
7997                Some(Kind::Decimal) => {
7998                    let c = (ctx.host_index)(HostFn::DecimalToRational).ok_or(
7999                        WasmLowerError::Unsupported("decimal_to_rational not imported"),
8000                    )?;
8001                    local_get(code, (args_start + 1) as u32);
8002                    code.push(0x10);
8003                    leb_u32(code, c);
8004                }
8005                _ => {
8006                    return Err(WasmLowerError::Unsupported(
8007                        "set_rate rate must be an Int, Decimal, or Rational",
8008                    ))
8009                }
8010            }
8011            code.push(0x10); // call set_rate → 0 (Nothing)
8012            leb_u32(code, set_idx);
8013            local_set(code, dst as u32);
8014            Ok(Flow::Straight)
8015        }
8016        // `to_currency(money, code)` — convert a `Money` into the named currency via the ambient rates.
8017        Op::CallBuiltin {
8018            dst,
8019            builtin: BuiltinId::ToCurrency,
8020            args_start,
8021            ..
8022        } if ctx.linked => {
8023            let idx = (ctx.host_index)(HostFn::MoneyToCurrency).ok_or(
8024                WasmLowerError::Unsupported("to_currency runtime fn not imported"),
8025            )?;
8026            local_get(code, args_start as u32); // the Money handle
8027            local_get(code, (args_start + 1) as u32); // the currency-code Text handle
8028            code.push(0x10);
8029            leb_u32(code, idx);
8030            local_set(code, dst as u32);
8031            Ok(Flow::Straight)
8032        }
8033        // `set_rates(map)` — install a whole `Map of <code> to <rate>`, dispatched on the map's VALUE kind
8034        // (resolved by scanning the region for the `SetIndex` that populated it), returning `Nothing` (0).
8035        Op::CallBuiltin {
8036            dst,
8037            builtin: BuiltinId::SetRates,
8038            args_start,
8039            ..
8040        } if ctx.linked => {
8041            let vk = set_rates_value_kind(&plan.ops, args_start, kinds);
8042            let rt = match vk {
8043                Some(Kind::Int) => HostFn::MoneySetRatesInt,
8044                Some(Kind::Rational) => HostFn::MoneySetRatesRational,
8045                Some(Kind::Decimal) => HostFn::MoneySetRatesDecimal,
8046                _ => return Err(WasmLowerError::Unsupported("set_rates needs a Map of currency code to an Int/Decimal/Rational rate whose value kind is statically known")),
8047            };
8048            let idx = (ctx.host_index)(rt).ok_or(WasmLowerError::Unsupported(
8049                "set_rates runtime fn not imported",
8050            ))?;
8051            local_get(code, args_start as u32); // the Map handle
8052            code.push(0x10);
8053            leb_u32(code, idx);
8054            local_set(code, dst as u32);
8055            Ok(Flow::Straight)
8056        }
8057        // `wireBytes(value) -> Seq of Int` (LINKER MODE) — marshal the value to its wire bytes via the REAL
8058        // `logicaffeine_compile::concurrency::marshal::encode_value_raw` (a `logos_rt_wire_bytes_*` runtime
8059        // fn reconstructs the `RuntimeValue` from the AOT value, by kind, and encodes), byte-identical to
8060        // the VM's `bytes_to_seq(encode_value_raw(v))`. A composite value's reconstruction is not yet wired
8061        // (soundly refused). `gc-sections` keeps the compiler out of any module that never calls this.
8062        Op::CallBuiltin {
8063            dst,
8064            builtin: BuiltinId::WireBytes,
8065            args_start,
8066            ..
8067        } if ctx.linked => {
8068            let h = wire_bytes_host_fn(kinds.get(args_start as usize)).ok_or(
8069                WasmLowerError::Unsupported(
8070                    "wireBytes of this value kind is not yet reconstructed for the wire codec",
8071                ),
8072            )?;
8073            let idx = (ctx.host_index)(h).ok_or(WasmLowerError::Unsupported(
8074                "wire_bytes runtime fn not imported",
8075            ))?;
8076            local_get(code, args_start as u32); // the value (i64 / f64 / i32 Text handle by kind)
8077            code.push(0x10);
8078            leb_u32(code, idx);
8079            local_set(code, dst as u32);
8080            Ok(Flow::Straight)
8081        }
8082        // `readWireProgram() -> a DYNAMIC value` (LINKER MODE) — alloc a scratch buffer, have the host
8083        // (`read_wire_frame`) write the wire frame into it (returning the byte length), then DECODE it via
8084        // the REAL `decode_value_raw` to a leaked `Box<RuntimeValue>` (Kind::Dynamic). The buffer size caps
8085        // the received program. The result's concrete type is only known at runtime — that's why it's boxed.
8086        Op::CallBuiltin {
8087            dst,
8088            builtin: BuiltinId::ReadWireProgram,
8089            ..
8090        } if ctx.linked => {
8091            const WIRE_BUF: i32 = 1 << 16;
8092            let frame = (ctx.host_index)(HostFn::ReadWireFrame).ok_or(
8093                WasmLowerError::Unsupported("read_wire_frame host not imported"),
8094            )?;
8095            let decode = (ctx.host_index)(HostFn::ReadWireProgramRt).ok_or(
8096                WasmLowerError::Unsupported("read_wire_program runtime fn not imported"),
8097            )?;
8098            let buf = plan.num_regs + 8; // an i32 heap scratch local (num_regs+5..+11)
8099            i32_const(code, WIRE_BUF);
8100            emit_alloc(code, ctx, buf, AllocClass::Raw); // buf = bump-alloc(WIRE_BUF)
8101            local_get(code, buf); // decode's 1st arg
8102            local_get(code, buf);
8103            i32_const(code, WIRE_BUF);
8104            code.push(0x10); // read_wire_frame(buf, WIRE_BUF) -> len
8105            leb_u32(code, frame);
8106            code.push(0x10); // logos_rt_read_wire_program(buf, len) -> dynamic handle
8107            leb_u32(code, decode);
8108            local_set(code, dst as u32);
8109            Ok(Flow::Straight)
8110        }
8111        // `run_accepted(fn, arg, lo, hi) -> Int` (LINKER MODE) — sandbox-eval a wire-received SHIPPED
8112        // function through `AcceptanceContract::apply`. `fn` MUST be a `Dynamic` (a `readWireProgram`
8113        // result holding a `Function{generated}`); an ordinary compiled closure is not a shipped function,
8114        // so a non-Dynamic first arg is refused (the VM refuses ordinary closures at runtime, likewise).
8115        Op::CallBuiltin {
8116            dst,
8117            builtin: BuiltinId::RunAccepted,
8118            args_start,
8119            ..
8120        } if ctx.linked => {
8121            if kinds.get(args_start as usize) != Some(Kind::Dynamic) {
8122                return Err(WasmLowerError::Unsupported(
8123                    "run_accepted requires a wire-received (dynamic) shipped function",
8124                ));
8125            }
8126            let idx = (ctx.host_index)(HostFn::RunAccepted).ok_or(WasmLowerError::Unsupported(
8127                "run_accepted runtime fn not imported",
8128            ))?;
8129            local_get(code, args_start as u32); // the dynamic function handle (i32)
8130            local_get(code, (args_start + 1) as u32); // arg (i64)
8131            local_get(code, (args_start + 2) as u32); // lo (i64)
8132            local_get(code, (args_start + 3) as u32); // hi (i64)
8133            code.push(0x10); // logos_rt_run_accepted(fn, arg, lo, hi) -> i64
8134            leb_u32(code, idx);
8135            local_set(code, dst as u32);
8136            Ok(Flow::Straight)
8137        }
8138        // `format(x) -> Text` — `x.to_display_string()` as a Text, the SAME materialization a `+`
8139        // concat performs on a non-Text operand (an empty `format()` yields an empty Text).
8140        Op::CallBuiltin {
8141            dst,
8142            builtin: BuiltinId::Format,
8143            args_start,
8144            arg_count,
8145        } => {
8146            if arg_count == 0 {
8147                lower_text_literal(code, ctx, plan.num_regs, b""); // leaves the handle on the stack
8148                local_set(code, dst as u32);
8149            } else {
8150                // `emit_stringify` writes the Text handle straight into the `dst` local.
8151                display::emit_display_of(code, plan, ctx, args_start, dst as u32)?;
8152            }
8153            Ok(Flow::Straight)
8154        }
8155        // `Fail with <value>.` / a broken contract's `, otherwise <reason>`: hand the host the reason as
8156        // Text, then trap — the report every other tier gives. A Text reason goes as-is; `Fail with`
8157        // stringifies any other value exactly as `format` would; a contract reason that is not Text is
8158        // refused with the same sentence the other tiers use (`semantics::builtins::contract_reason_text`).
8159        Op::CallBuiltin {
8160            builtin: b @ (BuiltinId::Fail | BuiltinId::FailReason),
8161            args_start,
8162            ..
8163        } => {
8164            let fail = (ctx.host_index)(HostFn::LogosRtFail).ok_or(WasmLowerError::Unsupported(
8165                "logos_rt_fail host not imported",
8166            ))?;
8167            let kind = kinds.get(args_start as usize);
8168            if kind == Some(Kind::Text) {
8169                local_get(code, args_start as u32);
8170            } else if b == BuiltinId::Fail {
8171                // The handle is an i32; `dst` is typed by its own kind, so the rendering goes through an
8172                // i32 heap scratch local (+8 — `emit_stringify` itself uses +5..+7).
8173                let text = plan.num_regs + 8;
8174                display::emit_display_of(code, plan, ctx, args_start, text)?;
8175                local_get(code, text);
8176            } else {
8177                let type_name = match kind {
8178                    Some(Kind::Int) => "Int",
8179                    Some(Kind::Float) => "Real",
8180                    Some(Kind::Bool) => "Bool",
8181                    _ => {
8182                        return Err(WasmLowerError::Unsupported(
8183                            "a contract reason of this kind",
8184                        ))
8185                    }
8186                };
8187                let refusal =
8188                    format!("The reason after `otherwise` must be Text, but it was {type_name}.");
8189                lower_text_literal(code, ctx, plan.num_regs, refusal.as_bytes());
8190            }
8191            code.push(0x10); // call logos_rt_fail
8192            leb_u32(code, fail);
8193            code.push(0x00); // unreachable → trap
8194            Ok(Flow::Terminated)
8195        }
8196        // `Mount … at …` / `Write … to file …`: the tree-walker and the VM run them against the sandboxed
8197        // virtual file system; a page in the browser has none, so the turn fails with the sentence that
8198        // names what is missing (`VFS_IN_THE_BROWSER`), and the program still builds.
8199        Op::CallBuiltin {
8200            builtin: BuiltinId::VfsMount | BuiltinId::VfsWriteFile,
8201            ..
8202        } => {
8203            let fail = (ctx.host_index)(HostFn::LogosRtFail).ok_or(WasmLowerError::Unsupported(
8204                "logos_rt_fail host not imported",
8205            ))?;
8206            lower_text_literal(code, ctx, plan.num_regs, VFS_IN_THE_BROWSER.as_bytes());
8207            code.push(0x10); // call logos_rt_fail
8208            leb_u32(code, fail);
8209            code.push(0x00); // unreachable → trap
8210            Ok(Flow::Terminated)
8211        }
8212        // `repeatSeq(x, n)` — a fresh `n`-element sequence of the scalar `x` (`[x] * n`).
8213        Op::CallBuiltin {
8214            dst,
8215            builtin: BuiltinId::RepeatSeq,
8216            args_start,
8217            arg_count,
8218        } => {
8219            if arg_count != 2 {
8220                return Err(WasmLowerError::Unsupported("repeatSeq arity"));
8221            }
8222            lower_repeat_seq(code, kinds, ctx, plan.num_regs, dst, args_start)?;
8223            Ok(Flow::Straight)
8224        }
8225        // `money(amount, "USD")` — build an EXACT Money handle. `amount` is a Decimal handle or an
8226        // Int (whole units); the currency is a Text code resolved by `currency::by_code` in the runtime.
8227        Op::CallBuiltin {
8228            dst,
8229            builtin: BuiltinId::Money,
8230            args_start,
8231            arg_count,
8232        } if ctx.linked && arg_count == 2 => {
8233            if kinds.get((args_start + 1) as usize) != Some(Kind::Text) {
8234                return Err(WasmLowerError::Unsupported(
8235                    "money(amount, currency) with a non-Text currency",
8236                ));
8237            }
8238            let host = match kinds.get(args_start as usize) {
8239                Some(Kind::Decimal) => HostFn::MoneyFromDecimal,
8240                Some(Kind::Int) => HostFn::MoneyFromI64,
8241                _ => {
8242                    return Err(WasmLowerError::Unsupported(
8243                        "money amount must be an Int or Decimal",
8244                    ))
8245                }
8246            };
8247            let make = (ctx.host_index)(host).ok_or(WasmLowerError::Unsupported(
8248                "money constructor not imported",
8249            ))?;
8250            local_get(code, args_start as u32);
8251            local_get(code, (args_start + 1) as u32);
8252            code.push(0x10);
8253            leb_u32(code, make);
8254            local_set(code, dst as u32);
8255            return Ok(Flow::Straight);
8256        }
8257        // `quantity(v, "unit")` — build an EXACT Quantity handle: an Int magnitude + a unit name Text
8258        // resolved by `units::by_name` in the runtime (the `5 meters` literal lowers to this too).
8259        Op::CallBuiltin {
8260            dst,
8261            builtin: BuiltinId::Quantity,
8262            args_start,
8263            arg_count,
8264        } if ctx.linked && arg_count == 2 => {
8265            if kinds.get((args_start + 1) as usize) != Some(Kind::Text) {
8266                return Err(WasmLowerError::Unsupported(
8267                    "quantity(value, unit) with a non-Text unit",
8268                ));
8269            }
8270            if kinds.get(args_start as usize) != Some(Kind::Int) {
8271                return Err(WasmLowerError::Unsupported(
8272                    "quantity magnitude must be an Int",
8273                ));
8274            }
8275            let make = (ctx.host_index)(HostFn::QuantityOfI64).ok_or(
8276                WasmLowerError::Unsupported("quantity constructor not imported"),
8277            )?;
8278            local_get(code, args_start as u32);
8279            local_get(code, (args_start + 1) as u32);
8280            code.push(0x10);
8281            leb_u32(code, make);
8282            local_set(code, dst as u32);
8283            return Ok(Flow::Straight);
8284        }
8285        // `convert(q, "unit")` (the surface `X in <unit>`) — re-express a Quantity in a new display unit
8286        // of the SAME dimension (dimension-checked at compile time); the runtime keeps the SI magnitude.
8287        Op::CallBuiltin {
8288            dst,
8289            builtin: BuiltinId::Convert,
8290            args_start,
8291            arg_count,
8292        } if ctx.linked && arg_count == 2 => {
8293            if kinds.get(args_start as usize) != Some(Kind::Quantity) {
8294                return Err(WasmLowerError::Unsupported("convert() requires a Quantity"));
8295            }
8296            if kinds.get((args_start + 1) as usize) != Some(Kind::Text) {
8297                return Err(WasmLowerError::Unsupported(
8298                    "convert(q, unit) with a non-Text unit",
8299                ));
8300            }
8301            let make = (ctx.host_index)(HostFn::QuantityConvert)
8302                .ok_or(WasmLowerError::Unsupported("quantity convert not imported"))?;
8303            local_get(code, args_start as u32);
8304            local_get(code, (args_start + 1) as u32);
8305            code.push(0x10);
8306            leb_u32(code, make);
8307            local_set(code, dst as u32);
8308            return Ok(Flow::Straight);
8309        }
8310        // `decimal("…")` — parse a Text arg into an exact Decimal via the runtime.
8311        Op::CallBuiltin {
8312            dst,
8313            builtin: BuiltinId::Decimal,
8314            args_start,
8315            arg_count,
8316        } if ctx.linked && arg_count == 1 => {
8317            if kinds.get(args_start as usize) != Some(Kind::Text) {
8318                return Err(WasmLowerError::Unsupported(
8319                    "decimal(x) with a non-Text argument",
8320                ));
8321            }
8322            let from = (ctx.host_index)(HostFn::DecimalFromText).ok_or(
8323                WasmLowerError::Unsupported("decimal_from_text not imported"),
8324            )?;
8325            local_get(code, args_start as u32);
8326            code.push(0x10);
8327            leb_u32(code, from);
8328            local_set(code, dst as u32);
8329            return Ok(Flow::Straight);
8330        }
8331        // `complex(re, im)` — build an EXACT Complex handle from two Int components via the runtime.
8332        Op::CallBuiltin {
8333            dst,
8334            builtin: BuiltinId::Modular,
8335            args_start,
8336            arg_count,
8337        } if ctx.linked && arg_count == 2 => {
8338            if kinds.get(args_start as usize) != Some(Kind::Int)
8339                || kinds.get((args_start + 1) as usize) != Some(Kind::Int)
8340            {
8341                return Err(WasmLowerError::Unsupported(
8342                    "modular(v, n) with non-Int components",
8343                ));
8344            }
8345            let from = (ctx.host_index)(HostFn::ModularFromI64)
8346                .ok_or(WasmLowerError::Unsupported("modular_from_i64 not imported"))?;
8347            local_get(code, args_start as u32);
8348            local_get(code, (args_start + 1) as u32);
8349            code.push(0x10);
8350            leb_u32(code, from);
8351            local_set(code, dst as u32);
8352            return Ok(Flow::Straight);
8353        }
8354        Op::CallBuiltin {
8355            dst,
8356            builtin: BuiltinId::Complex,
8357            args_start,
8358            arg_count,
8359        } if ctx.linked && arg_count == 2 => {
8360            let re_k = kinds.get(args_start as usize);
8361            let im_k = kinds.get((args_start + 1) as usize);
8362            if re_k == Some(Kind::Int) && im_k == Some(Kind::Int) {
8363                let from = (ctx.host_index)(HostFn::ComplexFromI64)
8364                    .ok_or(WasmLowerError::Unsupported("complex_from_i64 not imported"))?;
8365                local_get(code, args_start as u32);
8366                local_get(code, (args_start + 1) as u32);
8367                code.push(0x10); // call logos_rt_complex_from_i64
8368                leb_u32(code, from);
8369                local_set(code, dst as u32);
8370                return Ok(Flow::Straight);
8371            }
8372            // Float-part complex (a `ComplexF`) → a dyadic-Rational handle via `logos_rt_complex_from_f64`.
8373            // Each part is loaded as an f64: a Float part directly, an Int part converted (`f64.convert_i64_s`).
8374            if !matches!(re_k, Some(Kind::Int) | Some(Kind::Float))
8375                || !matches!(im_k, Some(Kind::Int) | Some(Kind::Float))
8376            {
8377                return Err(WasmLowerError::Unsupported(
8378                    "complex(re, im) with non-numeric components",
8379                ));
8380            }
8381            let from = (ctx.host_index)(HostFn::ComplexFromF64)
8382                .ok_or(WasmLowerError::Unsupported("complex_from_f64 not imported"))?;
8383            local_get(code, args_start as u32);
8384            if re_k == Some(Kind::Int) {
8385                code.push(0xB9);
8386            } // f64.convert_i64_s
8387            local_get(code, (args_start + 1) as u32);
8388            if im_k == Some(Kind::Int) {
8389                code.push(0xB9);
8390            } // f64.convert_i64_s
8391            code.push(0x10); // call logos_rt_complex_from_f64
8392            leb_u32(code, from);
8393            local_set(code, dst as u32);
8394            Ok(Flow::Straight)
8395        }
8396        // `abs` of a LINKED `Complex`: its `f64` modulus `|z|` via `logos_rt_complex_abs` (the one
8397        // complex op returning a Float, not a handle). Handled here (not `lower_builtin`) for `ctx`.
8398        Op::CallBuiltin {
8399            dst,
8400            builtin: BuiltinId::Abs,
8401            args_start,
8402            ..
8403        } if ctx.linked && kinds.get(args_start as usize) == Some(Kind::Complex) => {
8404            let host = (ctx.host_index)(HostFn::ComplexAbs)
8405                .ok_or(WasmLowerError::Unsupported("complex_abs not imported"))?;
8406            local_get(code, args_start as u32);
8407            code.push(0x10); // call logos_rt_complex_abs
8408            leb_u32(code, host);
8409            local_set(code, dst as u32);
8410            Ok(Flow::Straight)
8411        }
8412        // `re(z)` / `im(z)` of a LINKED Complex → its real / imaginary part as an `f64` (the dyadic
8413        // parts round-trip). The float-complex tier's extraction; both return a Float, not a handle.
8414        Op::CallBuiltin {
8415            dst,
8416            builtin: BuiltinId::RealPart,
8417            args_start,
8418            ..
8419        } if ctx.linked && kinds.get(args_start as usize) == Some(Kind::Complex) => {
8420            let host = (ctx.host_index)(HostFn::ComplexReF64)
8421                .ok_or(WasmLowerError::Unsupported("complex_re_f64 not imported"))?;
8422            local_get(code, args_start as u32);
8423            code.push(0x10); // call logos_rt_complex_re_f64
8424            leb_u32(code, host);
8425            local_set(code, dst as u32);
8426            Ok(Flow::Straight)
8427        }
8428        Op::CallBuiltin {
8429            dst,
8430            builtin: BuiltinId::ImagPart,
8431            args_start,
8432            ..
8433        } if ctx.linked && kinds.get(args_start as usize) == Some(Kind::Complex) => {
8434            let host = (ctx.host_index)(HostFn::ComplexImF64)
8435                .ok_or(WasmLowerError::Unsupported("complex_im_f64 not imported"))?;
8436            local_get(code, args_start as u32);
8437            code.push(0x10); // call logos_rt_complex_im_f64
8438            leb_u32(code, host);
8439            local_set(code, dst as u32);
8440            Ok(Flow::Straight)
8441        }
8442        // `floor`/`ceil`/`round`/`abs` of a LINKED `Rational`: EXACT rounding on the BigInt-backed
8443        // fraction (`logos_rt_rational_*`) — floor/ceil/round yield a BigInt handle, abs a Rational one —
8444        // never the lossy `f64` path. Handled here (not `lower_builtin`) for the `ctx` host table.
8445        Op::CallBuiltin {
8446            dst,
8447            builtin: b @ (BuiltinId::Floor | BuiltinId::Ceil | BuiltinId::Round | BuiltinId::Abs),
8448            args_start,
8449            ..
8450        } if ctx.linked && kinds.get(args_start as usize) == Some(Kind::Rational) => {
8451            let host = match b {
8452                BuiltinId::Floor => HostFn::RationalFloor,
8453                BuiltinId::Ceil => HostFn::RationalCeil,
8454                BuiltinId::Round => HostFn::RationalRound,
8455                _ => HostFn::RationalAbs,
8456            };
8457            lower_rational_unary(code, ctx, dst, args_start, host)
8458        }
8459        // The LINKED `Uuid` builtins: `uuid("…")` parse + `uuid_version` take one arg; the `uuid_nil`/
8460        // `uuid_max`/`uuid_dns`/… constants take none. Each is a direct `logos_rt_uuid_*` call.
8461        Op::CallBuiltin {
8462            dst,
8463            builtin:
8464                b @ (BuiltinId::Uuid
8465                | BuiltinId::UuidNil
8466                | BuiltinId::UuidMax
8467                | BuiltinId::UuidDns
8468                | BuiltinId::UuidUrl
8469                | BuiltinId::UuidOid
8470                | BuiltinId::UuidX500
8471                | BuiltinId::UuidVersion),
8472            args_start,
8473            ..
8474        } if ctx.linked => {
8475            let host = match b {
8476                BuiltinId::Uuid => HostFn::UuidParse,
8477                BuiltinId::UuidNil => HostFn::UuidNil,
8478                BuiltinId::UuidMax => HostFn::UuidMax,
8479                BuiltinId::UuidDns => HostFn::UuidDns,
8480                BuiltinId::UuidUrl => HostFn::UuidUrl,
8481                BuiltinId::UuidOid => HostFn::UuidOid,
8482                BuiltinId::UuidX500 => HostFn::UuidX500,
8483                _ => HostFn::UuidVersion,
8484            };
8485            let idx = (ctx.host_index)(host)
8486                .ok_or(WasmLowerError::Unsupported("uuid builtin not imported"))?;
8487            // `uuid(text)` and `uuid_version(u)` consume the one arg; the constants take none.
8488            if matches!(b, BuiltinId::Uuid | BuiltinId::UuidVersion) {
8489                local_get(code, args_start as u32);
8490            }
8491            code.push(0x10);
8492            leb_u32(code, idx);
8493            local_set(code, dst as u32);
8494            return Ok(Flow::Straight);
8495        }
8496        // Byte interop: `text_bytes`/`uuid_bytes` build a `Seq of Int` of raw bytes; `text_from_bytes`
8497        // rebuilds a `Text`; `uuid_from_bytes` packs 16 bytes and boxes a `Uuid` (linker). Emitter-heap
8498        // seq/Text construction — no host except `uuid_from_bytes`'s `logos_rt_uuid_from_ptr`.
8499        Op::CallBuiltin {
8500            dst,
8501            builtin: BuiltinId::TextBytes,
8502            args_start,
8503            ..
8504        } => {
8505            lower_text_bytes(code, ctx, plan.num_regs, dst, args_start);
8506            return Ok(Flow::Straight);
8507        }
8508        Op::CallBuiltin {
8509            dst,
8510            builtin: BuiltinId::UuidBytes,
8511            args_start,
8512            ..
8513        } if ctx.linked => {
8514            lower_uuid_bytes(code, ctx, plan.num_regs, dst, args_start);
8515            return Ok(Flow::Straight);
8516        }
8517        Op::CallBuiltin {
8518            dst,
8519            builtin: BuiltinId::TextFromBytes,
8520            args_start,
8521            ..
8522        } => {
8523            lower_text_from_bytes(code, ctx, plan.num_regs, dst, args_start)?;
8524            return Ok(Flow::Straight);
8525        }
8526        Op::CallBuiltin {
8527            dst,
8528            builtin: BuiltinId::UuidFromBytes,
8529            args_start,
8530            ..
8531        } if ctx.linked => {
8532            return lower_uuid_from_bytes(code, ctx, plan.num_regs, dst, args_start);
8533        }
8534        // The SHA-1 SHA-NI lane vocabulary (linker): construction/unpack are inline, the four rounds call
8535        // the `logos_rt_sha1*` runtime (which delegates to `base::sha_ops`).
8536        Op::CallBuiltin {
8537            dst,
8538            builtin: BuiltinId::Lanes4Of,
8539            args_start,
8540            ..
8541        } if ctx.linked => {
8542            lower_lanes4_of(
8543                code,
8544                ctx,
8545                plan.num_regs,
8546                dst,
8547                [args_start, args_start + 1, args_start + 2, args_start + 3],
8548            );
8549            return Ok(Flow::Straight);
8550        }
8551        Op::CallBuiltin {
8552            dst,
8553            builtin: BuiltinId::Lanes4Word32Make,
8554            args_start,
8555            ..
8556        } if ctx.linked => {
8557            lower_lanes4_word32(code, ctx, plan.num_regs, dst, args_start);
8558            return Ok(Flow::Straight);
8559        }
8560        Op::CallBuiltin {
8561            dst,
8562            builtin: BuiltinId::SeqOfLanes4W32,
8563            args_start,
8564            ..
8565        } if ctx.linked => {
8566            lower_seq_of_lanes4(code, ctx, plan.num_regs, dst, args_start);
8567            return Ok(Flow::Straight);
8568        }
8569        Op::CallBuiltin {
8570            dst,
8571            builtin:
8572                b @ (BuiltinId::Sha1Rnds4
8573                | BuiltinId::Sha1Msg1
8574                | BuiltinId::Sha1Msg2
8575                | BuiltinId::Sha1Nexte),
8576            args_start,
8577            ..
8578        } if ctx.linked => {
8579            let (host, ternary) = match b {
8580                BuiltinId::Sha1Rnds4 => (HostFn::Sha1Rnds4, true),
8581                BuiltinId::Sha1Msg1 => (HostFn::Sha1Msg1, false),
8582                BuiltinId::Sha1Msg2 => (HostFn::Sha1Msg2, false),
8583                _ => (HostFn::Sha1Nexte, false),
8584            };
8585            return lower_sha1_op(code, ctx, dst, args_start, host, ternary);
8586        }
8587        Op::CallBuiltin {
8588            dst,
8589            builtin,
8590            args_start,
8591            arg_count,
8592        } => lower_builtin(code, kinds, dst, builtin, args_start, arg_count),
8593        // `args()` — the host returns the argv `Seq of Text` handle (built in this module's memory).
8594        Op::Args { dst } => {
8595            let idx = (ctx.host_index)(HostFn::Args)
8596                .ok_or(WasmLowerError::Unsupported("args host not imported"))?;
8597            code.push(0x10); // call args
8598            leb_u32(code, idx);
8599            local_set(code, dst as u32);
8600            Ok(Flow::Straight)
8601        }
8602        Op::Show { src } => {
8603            // A whole tuple assembles its `(e0, e1, …)` display inline from the static layout
8604            // (deterministic order), then prints it — no per-kind host sink exists for it. This is
8605            // keyed on the tuple LAYOUT (populated by `NewTuple`), not the Kind: a HOMOGENEOUS tuple
8606            // like `(10, 20)` collapses to `Kind::SeqInt` for its element machinery yet must still
8607            // display with tuple parens `(10, 20)`, not list brackets `[10, 20]`. A real list literal
8608            // (`NewList`) is absent from `tuple_layouts`, so it keeps its `[…]` sink.
8609            if plan.structs.tuple_layouts.contains_key(&src) {
8610                lower_show_tuple(code, plan, ctx, src)?;
8611                return Ok(Flow::Straight);
8612            }
8613            let kind = kinds
8614                .get(src as usize)
8615                .ok_or(WasmLowerError::Unsupported("Show of an unknown-kind value"))?;
8616            // A whole enum (`North`, `Ctor`) prints its variant name via a tag→name dispatch built
8617            // from the enum type's variant set — no per-kind host sink exists for it.
8618            if kind == Kind::Enum {
8619                lower_show_enum(code, plan, ctx, src)?;
8620                return Ok(Flow::Straight);
8621            }
8622            // A whole struct (`Point { x: 1, y: 2 }`) — fields in deterministic alphabetical order,
8623            // matching the VM's now-sorted `HashMap` display.
8624            if kind == Kind::Struct {
8625                lower_show_struct(code, plan, ctx, src)?;
8626                return Ok(Flow::Straight);
8627            }
8628            // A whole `Seq of Struct` (`[Point { x: 1, y: 2 }, …]`) — each element struct rendered in
8629            // the same deterministic field order, concatenated into the `[…]` list display.
8630            if kind == Kind::SeqStruct {
8631                lower_show_seqstruct(code, plan, ctx, src)?;
8632                return Ok(Flow::Straight);
8633            }
8634            // A whole Map assembles its `{k0: v0, k1: v1, …}` display inline by iterating its entries
8635            // in stored order — which is INSERTION order, matching the VM's `IndexMap` (they share the
8636            // same `MapStorage`), so the rendering is byte-identical.
8637            // A NESTED int sequence (`[[1, 2], [3, 4]]`) assembles `[[…], […]]` by iterating the outer
8638            // seq and rendering each inner `Seq of Int` with the scalar seq formatter — deterministic
8639            // (both tiers store lists in insertion order).
8640            if kind == Kind::SeqSeqInt {
8641                lower_show_seqseq(code, ctx, plan.num_regs, src)?;
8642                return Ok(Flow::Straight);
8643            }
8644            // A whole `Seq of Enum` (`[North, South]`, `[Circle(5), Dot]`) renders `[e0, e1, …]`, each
8645            // element by the enum's tag→name dispatch (nullary name or `Ctor(fields)`), insertion order.
8646            if kind == Kind::SeqEnum {
8647                lower_show_seqenum(code, plan, ctx, src)?;
8648                return Ok(Flow::Straight);
8649            }
8650            if kind == Kind::Map {
8651                lower_show_map(code, plan, kinds, ctx, src)?;
8652                return Ok(Flow::Straight);
8653            }
8654            // A `Rational`: LINKER mode renders the BigInt-backed handle via `logos_rt_rational_to_text`
8655            // (`num/den`, or `num` when whole — exactly the VM's `Rational::to_string`) then prints it;
8656            // the self-contained value loads its scalar buffer (num@0, den@8) and hands it to the
8657            // `print_rational` host, which renders `num/den` (or `num` when `den == 1`).
8658            if kind == Kind::Rational {
8659                if ctx.linked {
8660                    let to_text = (ctx.host_index)(HostFn::RationalToText)
8661                        .ok_or(WasmLowerError::Unsupported("rational_to_text not imported"))?;
8662                    let print_text = (ctx.host_index)(HostFn::PrintText)
8663                        .ok_or(WasmLowerError::Unsupported("print_text not imported"))?;
8664                    local_get(code, src as u32);
8665                    code.push(0x10);
8666                    leb_u32(code, to_text);
8667                    code.push(0x10);
8668                    leb_u32(code, print_text);
8669                    return Ok(Flow::Straight);
8670                }
8671                let idx = (ctx.host_index)(HostFn::PrintRational)
8672                    .ok_or(WasmLowerError::Unsupported("Show sink not imported"))?;
8673                local_get(code, src as u32);
8674                i32_load(code, 8);
8675                i64_load(code, 0);
8676                local_get(code, src as u32);
8677                i32_load(code, 8);
8678                i64_load(code, 8);
8679                code.push(0x10); // call print_rational
8680                leb_u32(code, idx);
8681                return Ok(Flow::Straight);
8682            }
8683            // A `BigInt` handle (linker mode): render it to a decimal `Text` now
8684            // (`logos_rt_bigint_to_text` — deferred until here so a Pow/`*` chain could keep computing on
8685            // real BigInts) and print that Text.
8686            if kind == Kind::BigInt {
8687                let to_text = (ctx.host_index)(HostFn::BigintToText)
8688                    .ok_or(WasmLowerError::Unsupported("bigint_to_text not imported"))?;
8689                let print_text = (ctx.host_index)(HostFn::PrintText)
8690                    .ok_or(WasmLowerError::Unsupported("print_text not imported"))?;
8691                local_get(code, src as u32); // i32 BigInt handle
8692                code.push(0x10);
8693                leb_u32(code, to_text); // -> i32 Text handle
8694                code.push(0x10);
8695                leb_u32(code, print_text); // print the decimal
8696                return Ok(Flow::Straight);
8697            }
8698            // A `Complex` handle: render `re±imi` to a Text via the runtime, then print it.
8699            if kind == Kind::Complex {
8700                let to_text = (ctx.host_index)(HostFn::ComplexToText)
8701                    .ok_or(WasmLowerError::Unsupported("complex_to_text not imported"))?;
8702                let print_text = (ctx.host_index)(HostFn::PrintText)
8703                    .ok_or(WasmLowerError::Unsupported("print_text not imported"))?;
8704                local_get(code, src as u32); // i32 Complex handle
8705                code.push(0x10);
8706                leb_u32(code, to_text); // -> i32 Text handle
8707                code.push(0x10);
8708                leb_u32(code, print_text);
8709                return Ok(Flow::Straight);
8710            }
8711            // A `Modular` handle: render `v (mod n)` via the runtime, then print it.
8712            if kind == Kind::Modular {
8713                let to_text = (ctx.host_index)(HostFn::ModularToText)
8714                    .ok_or(WasmLowerError::Unsupported("modular_to_text not imported"))?;
8715                let print_text = (ctx.host_index)(HostFn::PrintText)
8716                    .ok_or(WasmLowerError::Unsupported("print_text not imported"))?;
8717                local_get(code, src as u32);
8718                code.push(0x10);
8719                leb_u32(code, to_text);
8720                code.push(0x10);
8721                leb_u32(code, print_text);
8722                return Ok(Flow::Straight);
8723            }
8724            if kind == Kind::Decimal {
8725                let to_text = (ctx.host_index)(HostFn::DecimalToText)
8726                    .ok_or(WasmLowerError::Unsupported("decimal_to_text not imported"))?;
8727                let print_text = (ctx.host_index)(HostFn::PrintText)
8728                    .ok_or(WasmLowerError::Unsupported("print_text not imported"))?;
8729                local_get(code, src as u32);
8730                code.push(0x10);
8731                leb_u32(code, to_text);
8732                code.push(0x10);
8733                leb_u32(code, print_text);
8734                return Ok(Flow::Straight);
8735            }
8736            if kind == Kind::Money {
8737                let to_text = (ctx.host_index)(HostFn::MoneyToText)
8738                    .ok_or(WasmLowerError::Unsupported("money_to_text not imported"))?;
8739                let print_text = (ctx.host_index)(HostFn::PrintText)
8740                    .ok_or(WasmLowerError::Unsupported("print_text not imported"))?;
8741                local_get(code, src as u32);
8742                code.push(0x10);
8743                leb_u32(code, to_text);
8744                code.push(0x10);
8745                leb_u32(code, print_text);
8746                return Ok(Flow::Straight);
8747            }
8748            // A `Quantity` handle: render `<magnitude> <symbol>` (or the dimension signature) via the
8749            // runtime, mirroring the interpreter's `QuantityValue::display`, then print it.
8750            if kind == Kind::Quantity {
8751                let to_text = (ctx.host_index)(HostFn::QuantityToText)
8752                    .ok_or(WasmLowerError::Unsupported("quantity_to_text not imported"))?;
8753                let print_text = (ctx.host_index)(HostFn::PrintText)
8754                    .ok_or(WasmLowerError::Unsupported("print_text not imported"))?;
8755                local_get(code, src as u32);
8756                code.push(0x10);
8757                leb_u32(code, to_text);
8758                code.push(0x10);
8759                leb_u32(code, print_text);
8760                return Ok(Flow::Straight);
8761            }
8762            // A `Uuid` handle: render the canonical lowercase form via `logos_rt_uuid_to_text`, then print.
8763            if kind == Kind::Uuid {
8764                let to_text = (ctx.host_index)(HostFn::UuidToText)
8765                    .ok_or(WasmLowerError::Unsupported("uuid_to_text not imported"))?;
8766                let print_text = (ctx.host_index)(HostFn::PrintText)
8767                    .ok_or(WasmLowerError::Unsupported("print_text not imported"))?;
8768                local_get(code, src as u32);
8769                code.push(0x10);
8770                leb_u32(code, to_text);
8771                code.push(0x10);
8772                leb_u32(code, print_text);
8773                return Ok(Flow::Straight);
8774            }
8775            // A wire-decoded DYNAMIC value: render its boxed `RuntimeValue` via `to_display_string`, print.
8776            if kind == Kind::Dynamic {
8777                let to_text = (ctx.host_index)(HostFn::DynamicToText)
8778                    .ok_or(WasmLowerError::Unsupported("dynamic_to_text not imported"))?;
8779                let print_text = (ctx.host_index)(HostFn::PrintText)
8780                    .ok_or(WasmLowerError::Unsupported("print_text not imported"))?;
8781                local_get(code, src as u32);
8782                code.push(0x10);
8783                leb_u32(code, to_text);
8784                code.push(0x10);
8785                leb_u32(code, print_text);
8786                return Ok(Flow::Straight);
8787            }
8788            // An `Optional` handle: a null (`0`) handle prints "nothing"; otherwise the boxed inner
8789            // scalar (`box[0]`) is loaded at its own width and printed via its own sink. The present
8790            // inner kind comes from `opt_inner` (the producing channel's element kind).
8791            if kind == Kind::Optional {
8792                let nothing = (ctx.host_index)(HostFn::PrintNothing)
8793                    .ok_or(WasmLowerError::Unsupported("Show sink not imported"))?;
8794                let inner = plan
8795                    .structs
8796                    .opt_inner
8797                    .get(&src)
8798                    .copied()
8799                    .unwrap_or(Kind::Int);
8800                let some_host = HostFn::for_show(inner).ok_or(WasmLowerError::Unsupported(
8801                    "Show of an optional with a non-scalar inner",
8802                ))?;
8803                let some_idx = (ctx.host_index)(some_host)
8804                    .ok_or(WasmLowerError::Unsupported("Show sink not imported"))?;
8805                local_get(code, src as u32);
8806                code.push(0x45); // i32.eqz → is the handle null (Nothing)?
8807                code.push(0x04);
8808                code.push(0x40); // if (void)
8809                code.push(0x10); // call print_nothing
8810                leb_u32(code, nothing);
8811                code.push(0x05); // else (Some)
8812                local_get(code, src as u32);
8813                emit_slot_load(code, Some(inner), 0)?; // box[0] → the inner value at its width
8814                if inner == Kind::Bool {
8815                    code.push(0xA7); // i32.wrap_i64 — print_bool takes an i32
8816                }
8817                code.push(0x10); // call print_<inner>
8818                leb_u32(code, some_idx);
8819                code.push(0x0B); // end if
8820                return Ok(Flow::Straight);
8821            }
8822            // A `Word32`/`Word64` Shows as its UNSIGNED value via `print_word` — a `Word32` is
8823            // zero-extended to `i64` first so the host's `u64` reading equals the `u32` value.
8824            if kind == Kind::Word32 || kind == Kind::Word64 {
8825                let idx = (ctx.host_index)(HostFn::PrintWord)
8826                    .ok_or(WasmLowerError::Unsupported("Show sink not imported"))?;
8827                local_get(code, src as u32);
8828                if kind == Kind::Word32 {
8829                    code.push(0xAD); // i64.extend_i32_u
8830                }
8831                code.push(0x10); // call print_word
8832                leb_u32(code, idx);
8833                return Ok(Flow::Straight);
8834            }
8835            let host = HostFn::for_show(kind)
8836                .ok_or(WasmLowerError::Unsupported("Show of a non-scalar value"))?;
8837            let idx = (ctx.host_index)(host)
8838                .ok_or(WasmLowerError::Unsupported("Show sink not imported"))?;
8839            if kind != Kind::Nothing {
8840                local_get(code, src as u32);
8841            }
8842            if kind == Kind::Bool {
8843                code.push(0xA7); // i32.wrap_i64 — print_bool takes an i32
8844            }
8845            code.push(0x10); // call print_*
8846            leb_u32(code, idx);
8847            Ok(Flow::Straight)
8848        }
8849        Op::Return { src } => {
8850            if plan.result.is_none() {
8851                return Err(WasmLowerError::Unsupported(
8852                    "value return from a void function",
8853                ));
8854            }
8855            emit_leave_loops(code, plan, ctx);
8856            local_get(code, src as u32);
8857            push_inout_results(code, plan);
8858            code.push(0x0F); // return
8859            Ok(Flow::Terminated)
8860        }
8861        Op::ReturnNothing => {
8862            match plan.result {
8863                None => {
8864                    emit_leave_loops(code, plan, ctx);
8865                    push_inout_results(code, plan);
8866                    code.push(0x0F); // return (void)
8867                }
8868                Some(_) => code.push(0x00), // unreachable (typed function: never returns nothing)
8869            }
8870            Ok(Flow::Terminated)
8871        }
8872        Op::Halt => {
8873            emit_leave_loops(code, plan, ctx);
8874            if ctx.batch_reclaim {
8875                code.push(0x10);
8876                leb_u32(
8877                    code,
8878                    ctx.runtime
8879                        .and_then(|r| r.index(RuntimeFn::Safepoint))
8880                        .expect("batch safepoint"),
8881                );
8882            }
8883            code.push(0x0F); // return — Main is void
8884            Ok(Flow::Terminated)
8885        }
8886        // A runtime failure (`FailWith`, e.g. a bad index or an explicit fail). The module still
8887        // TRAPS — that is the documented error contract, and `wasm_traps_where_treewalker_errors`
8888        // proves tw-errors ⟺ wasm-traps — but it now hands the host the message FIRST.
8889        //
8890        // ★ THE MESSAGE WAS AUTHORED AND THEN THROWN AWAY. The compiler writes real prose for
8891        // these ("no element matches that selector. Create the mount point before mounting…"),
8892        // interns it as a `Constant::Text`, and names it in the op. The tree-walker prints it and
8893        // the VM returns it verbatim; this backend used to drop it, so on the one tier a visitor
8894        // actually runs, every failure surfaced as `RuntimeError: unreachable` — no message, no
8895        // line, no source.
8896        //
8897        // The call goes BEFORE the `unreachable`, never instead of it: a host that returned
8898        // normally where the trap used to be would turn a failed `Check` into a program that
8899        // silently runs on.
8900        Op::FailWith { msg } => {
8901            if let Some(Constant::Text(text)) = ctx.constants.get(msg as usize) {
8902                let idx = (ctx.host_index)(HostFn::LogosRtFail).ok_or(
8903                    WasmLowerError::Unsupported("logos_rt_fail host not imported"),
8904                )?;
8905                lower_text_literal(code, ctx, plan.num_regs, text.as_bytes());
8906                code.push(0x10); // call logos_rt_fail
8907                leb_u32(code, idx);
8908            }
8909            code.push(0x00); // unreachable → trap
8910            Ok(Flow::Terminated)
8911        }
8912        // Observation (Wave 13, OBSERVED profile): call
8913        // `obs(site_id, p0, p1, p2)`. The host has the module's
8914        // `observation_sites`, so it resolves the category / message / span kind
8915        // from the site index; the three i64 args carry the observation's scalar
8916        // Int payload VALUES (a non-Int or absent slot is a zero placeholder —
8917        // rich-type payload rendering across the WASM FFI is a follow-up, and
8918        // those payloads emit in full on the tree-walker / VM / AOT tiers).
8919        Op::Obs {
8920            site,
8921            args_start,
8922            args_count,
8923        } => {
8924            let idx = (ctx.host_index)(HostFn::Obs)
8925                .ok_or(WasmLowerError::Unsupported("obs host import not present"))?;
8926            i32_const(
8927                code,
8928                i32::try_from(site).expect("an observation site index fits an i32"),
8929            );
8930            for slot in 0..3usize {
8931                let reg = args_start as usize + slot;
8932                if slot < args_count as usize && kinds.get(reg) == Some(Kind::Int) {
8933                    local_get(code, reg as u32); // the payload's i64 value
8934                } else {
8935                    code.push(0x42); // i64.const 0 (absent / non-scalar slot)
8936                    code.push(0x00);
8937                }
8938            }
8939            code.push(0x10); // call obs
8940            leb_u32(code, idx);
8941            Ok(Flow::Straight)
8942        }
8943        other => Err(unsupported_op(&other)),
8944    }
8945}
8946
8947#[derive(Clone, Copy)]
8948enum ArithOp {
8949    Add,
8950    Sub,
8951    Mul,
8952    Div,
8953    Mod,
8954}
8955
8956/// Lower a binary arithmetic op, dispatching on the result kind: checked `i64` for `Int`
8957/// (traps on signed overflow, matching the VM's exact-int → BigInt contract), native `f64` for
8958/// `Float`.
8959fn lower_arith(
8960    code: &mut Vec<u8>,
8961    ctx: &Ctx,
8962    kinds: &KindTable,
8963    dst: u16,
8964    lhs: u16,
8965    rhs: u16,
8966    op: ArithOp,
8967) -> R<Flow> {
8968    match kinds.get(dst as usize) {
8969        Some(Kind::Int) => {
8970            // Integer arithmetic needs two `i64` operands; a Float operand with an `Int` result is a
8971            // kind inconsistency — reject rather than emit an `i64` op on an `f64` (invalid wasm).
8972            if kinds.valtype(lhs as usize) != I64 || kinds.valtype(rhs as usize) != I64 {
8973                return Err(WasmLowerError::Unsupported(
8974                    "integer arithmetic with a non-integer operand",
8975                ));
8976            }
8977            let helper = match op {
8978                ArithOp::Add => Some(RuntimeFn::AddChecked),
8979                ArithOp::Sub => Some(RuntimeFn::SubChecked),
8980                ArithOp::Mul => Some(RuntimeFn::MulChecked),
8981                ArithOp::Div | ArithOp::Mod => None,
8982            };
8983            // Outside a loop ([`Ctx::hot`]) the overflow check is the runtime's; inside one it stays
8984            // inline, where a call would be paid per iteration.
8985            let call = helper
8986                .filter(|_| !ctx.hot.get())
8987                .and_then(|f| ctx.runtime.and_then(|r| r.index(f)));
8988            if let Some(f) = call {
8989                local_get(code, lhs as u32);
8990                local_get(code, rhs as u32);
8991                code.push(0x10);
8992                leb_u32(code, f);
8993                local_set(code, dst as u32);
8994                return Ok(Flow::Straight);
8995            }
8996            match op {
8997                ArithOp::Add => emit_checked_addsub(code, false, dst, lhs, rhs),
8998                ArithOp::Sub => emit_checked_addsub(code, true, dst, lhs, rhs),
8999                ArithOp::Mul => emit_checked_mul(code, dst, lhs, rhs),
9000                // `i64.div_s`/`rem_s` TRAP on a zero divisor all by themselves, so the program
9001                // already stopped correctly — it just stopped anonymously. Reporting first costs a
9002                // compare and a well-predicted branch in front of an instruction that takes tens of
9003                // cycles, which is noise, and buys the reference tier's own sentence instead of a
9004                // bare trap. (`i64::MIN / -1` still traps unreported: the wording differs there and
9005                // guessing at it would be worse than saying nothing.)
9006                ArithOp::Div | ArithOp::Mod => {
9007                    if let Some(fail_at) = (ctx.host_index)(HostFn::LogosRtFailAt) {
9008                        local_get(code, rhs as u32);
9009                        code.push(0x50); // i64.eqz
9010                        code.push(0x04);
9011                        code.push(0x40); // if
9012                        i32_const(
9013                            code,
9014                            crate::semantics::failcode::FailCode::DivisionByZero.code(),
9015                        );
9016                        code.push(0x42); // i64.const — this failure needs no value
9017                        leb_i64(code, 0);
9018                        code.push(0x10); // call logos_rt_fail_at(code, value)
9019                        leb_u32(code, fail_at);
9020                        code.push(0x00); // unreachable
9021                        code.push(0x0B); // end
9022                    }
9023                    let opcode = if matches!(op, ArithOp::Div) {
9024                        0x7F
9025                    } else {
9026                        0x81
9027                    };
9028                    arith(code, opcode, dst, lhs, rhs)
9029                }
9030            }
9031        }
9032        // Word arithmetic is the ℤ/2ⁿ ring: native wasm `i32`/`i64` ops WRAP by definition (no overflow
9033        // check, unlike `Int`'s checked path), and division/remainder are UNSIGNED — matching `WordVal`.
9034        Some(Kind::Word32) => {
9035            let opcode = match op {
9036                ArithOp::Add => 0x6A, // i32.add
9037                ArithOp::Sub => 0x6B, // i32.sub
9038                ArithOp::Mul => 0x6C, // i32.mul
9039                ArithOp::Div => 0x6E, // i32.div_u
9040                ArithOp::Mod => 0x70, // i32.rem_u
9041            };
9042            arith(code, opcode, dst, lhs, rhs);
9043        }
9044        Some(Kind::Word64) => {
9045            let opcode = match op {
9046                ArithOp::Add => 0x7C, // i64.add
9047                ArithOp::Sub => 0x7D, // i64.sub
9048                ArithOp::Mul => 0x7E, // i64.mul
9049                ArithOp::Div => 0x80, // i64.div_u
9050                ArithOp::Mod => 0x82, // i64.rem_u
9051            };
9052            arith(code, opcode, dst, lhs, rhs);
9053        }
9054        Some(Kind::Float) => {
9055            let opcode = match op {
9056                ArithOp::Add => 0xA0,
9057                ArithOp::Sub => 0xA1,
9058                ArithOp::Mul => 0xA2,
9059                ArithOp::Div => 0xA3,
9060                ArithOp::Mod => return Err(WasmLowerError::Unsupported("float modulo")),
9061            };
9062            // Promote an `Int` operand to `f64` (matching the tree-walker's mixed-expression
9063            // promotion), so `3 + 1.5` etc. compile instead of emitting an `f64` op on an `i64`; a rational
9064            // operand is the double the VM computes it as.
9065            push_number_as_f64(code, ctx, lhs, kinds.get(lhs as usize))?;
9066            push_number_as_f64(code, ctx, rhs, kinds.get(rhs as usize))?;
9067            code.push(opcode);
9068            local_set(code, dst as u32);
9069        }
9070        // Temporal arithmetic (`Duration ± Duration = Duration`, `Moment ± Duration = Moment`) is i64
9071        // nanos that WRAP (matching the VM's `wrapping_add`/`wrapping_sub`) — no overflow check, and only
9072        // `+`/`-` (the kind arms never route `× ÷ %` here).
9073        Some(Kind::Duration) | Some(Kind::Time) | Some(Kind::Moment) => {
9074            let opcode = match op {
9075                ArithOp::Add => 0x7C, // i64.add
9076                ArithOp::Sub => 0x7D, // i64.sub
9077                _ => {
9078                    return Err(WasmLowerError::Unsupported(
9079                        "only + and - on temporal values",
9080                    ))
9081                }
9082            };
9083            arith(code, opcode, dst, lhs, rhs);
9084        }
9085        _ => {
9086            return Err(WasmLowerError::Unsupported(
9087                "arithmetic on a non-numeric value",
9088            ))
9089        }
9090    }
9091    Ok(Flow::Straight)
9092}
9093
9094#[derive(Clone, Copy)]
9095enum Cmp {
9096    Lt,
9097    Gt,
9098    Le,
9099    Ge,
9100    Eq,
9101    Ne,
9102}
9103
9104/// Lower a comparison, dispatching on the *operand* kind (the result is always a `Bool` i64
9105/// 0/1). `i64` signed compares for `Int`, ordered `f64` compares for `Float`.
9106fn lower_compare(
9107    code: &mut Vec<u8>,
9108    ctx: &Ctx,
9109    kinds: &KindTable,
9110    dst: u16,
9111    lhs: u16,
9112    rhs: u16,
9113    cmp: Cmp,
9114) -> R<Flow> {
9115    let (lk, rk) = (kinds.get(lhs as usize), kinds.get(rhs as usize));
9116    if ctx.linked && (lk == Some(Kind::Rational) || rk == Some(Kind::Rational)) {
9117        return lower_rational_compare(code, kinds, ctx, dst, lhs, rhs, cmp);
9118    }
9119    if lk == Some(Kind::Nothing) || rk == Some(Kind::Nothing) {
9120        if !matches!(cmp, Cmp::Eq | Cmp::Ne) {
9121            return Err(WasmLowerError::Unsupported(
9122                "ordering comparison with nothing",
9123            ));
9124        }
9125        let other = if lk == Some(Kind::Nothing) { rhs } else { lhs };
9126        let other_kind = kinds
9127            .get(other as usize)
9128            .ok_or(WasmLowerError::Unsupported(
9129                "comparison of unknown-kind values",
9130            ))?;
9131        if other_kind == Kind::Optional {
9132            local_get(code, other as u32);
9133            code.push(0x45); // i32.eqz — the optional box is absent
9134        } else {
9135            i32_const(code, i32::from(other_kind == Kind::Nothing));
9136        }
9137        if matches!(cmp, Cmp::Ne) {
9138            code.push(0x45); // invert equality
9139        }
9140        code.push(0xAD); // i64.extend_i32_u
9141        local_set(code, dst as u32);
9142        return Ok(Flow::Straight);
9143    }
9144    let lf = kinds.valtype(lhs as usize) == F64;
9145    let rf = kinds.valtype(rhs as usize) == F64;
9146    if lf || rf {
9147        // Mixed Int/Float equality is EXACT — mathematical values (`1 equals
9148        // 1.0` is true, but 2^53+1 never equals the float 2^53). The test:
9149        // convert-both-ways equality (i→f64 rounds, f→i64 truncates — both
9150        // agreeing pins the exact value) with an upper guard at 2^63 where
9151        // the saturating truncation would alias i64::MAX. NaN fails the f64
9152        // compare; a fractional f fails the i64 compare.
9153        if lf != rf {
9154            if matches!(cmp, Cmp::Eq | Cmp::Ne) {
9155                let (int_reg, float_reg) = if lf { (rhs, lhs) } else { (lhs, rhs) };
9156                // c1: (int as f64) == f
9157                local_get(code, int_reg as u32);
9158                code.push(0xB9); // f64.convert_i64_s
9159                local_get(code, float_reg as u32);
9160                code.push(0x61); // f64.eq
9161                                 // c2: int == trunc_sat(f)
9162                local_get(code, int_reg as u32);
9163                local_get(code, float_reg as u32);
9164                code.push(0xFC); // saturating-truncation prefix
9165                code.push(0x06); // i64.trunc_sat_f64_s
9166                code.push(0x51); // i64.eq
9167                code.push(0x71); // i32.and
9168                                 // c3: f < 2^63 (above it trunc_sat aliases i64::MAX)
9169                local_get(code, float_reg as u32);
9170                code.push(0x44); // f64.const 2^63
9171                code.extend_from_slice(&9223372036854775808.0f64.to_le_bytes());
9172                code.push(0x63); // f64.lt
9173                code.push(0x71); // i32.and
9174                if matches!(cmp, Cmp::Ne) {
9175                    code.push(0x45); // i32.eqz — negate
9176                }
9177                code.push(0xAD); // i64.extend_i32_u
9178                local_set(code, dst as u32);
9179                return Ok(Flow::Straight);
9180            }
9181        }
9182        let opcode = match cmp {
9183            Cmp::Lt => 0x63, // f64.lt
9184            Cmp::Gt => 0x64, // f64.gt
9185            Cmp::Le => 0x65, // f64.le
9186            Cmp::Ge => 0x66, // f64.ge
9187            Cmp::Eq => 0x61, // f64.eq (both Float)
9188            Cmp::Ne => 0x62, // f64.ne (both Float)
9189        };
9190        push_as_f64(code, lhs, kinds.get(lhs as usize))?;
9191        push_as_f64(code, rhs, kinds.get(rhs as usize))?;
9192        code.push(opcode);
9193        code.push(0xAD); // i64.extend_i32_u — keep the VM's truthy-Int boolean width
9194        local_set(code, dst as u32);
9195        return Ok(Flow::Straight);
9196    }
9197    if lk == Some(Kind::Optional) || rk == Some(Kind::Optional) {
9198        return Err(WasmLowerError::Unsupported(
9199            "comparison of present optional payloads requires their inner value kinds",
9200        ));
9201    }
9202    let operand = kinds.get(lhs as usize).or_else(|| kinds.get(rhs as usize));
9203    match operand {
9204        Some(Kind::Nothing) => unreachable!("absence comparisons handled above"),
9205        // A `Char` compares by code point (`char`'s own ordering), so an `i64` compare of the
9206        // stored `char as u32` is byte-identical to the VM's `Char` comparison.
9207        Some(Kind::Int) | Some(Kind::Bool) | Some(Kind::Char) | Some(Kind::Duration)
9208        | Some(Kind::Time) | Some(Kind::Span) => {
9209            let opcode = match cmp {
9210                Cmp::Lt => 0x53, // i64.lt_s
9211                Cmp::Gt => 0x55, // i64.gt_s
9212                Cmp::Le => 0x57, // i64.le_s
9213                Cmp::Ge => 0x59, // i64.ge_s
9214                Cmp::Eq => 0x51, // i64.eq
9215                Cmp::Ne => 0x52, // i64.ne
9216            };
9217            compare(code, opcode, dst, lhs, rhs);
9218        }
9219        // Words compare by their UNSIGNED value (the ℤ/2ⁿ ring order) — `Word32` as `i32` unsigned,
9220        // `Word64` as `i64` unsigned, matching `WordVal`'s `to_u64`-based comparison.
9221        Some(Kind::Word32) => {
9222            let opcode = match cmp {
9223                Cmp::Lt => 0x49, // i32.lt_u
9224                Cmp::Gt => 0x4B, // i32.gt_u
9225                Cmp::Le => 0x4D, // i32.le_u
9226                Cmp::Ge => 0x4F, // i32.ge_u
9227                Cmp::Eq => 0x46, // i32.eq
9228                Cmp::Ne => 0x47, // i32.ne
9229            };
9230            compare(code, opcode, dst, lhs, rhs);
9231        }
9232        Some(Kind::Word64) => {
9233            let opcode = match cmp {
9234                Cmp::Lt => 0x54, // i64.lt_u
9235                Cmp::Gt => 0x56, // i64.gt_u
9236                Cmp::Le => 0x58, // i64.le_u
9237                Cmp::Ge => 0x5A, // i64.ge_u
9238                Cmp::Eq => 0x51, // i64.eq
9239                Cmp::Ne => 0x52, // i64.ne
9240            };
9241            compare(code, opcode, dst, lhs, rhs);
9242        }
9243        // A Float operand has value type `F64`, so it always took the promotion path above.
9244        Some(Kind::Float) => unreachable!("float comparison handled by the f64 promotion path"),
9245        Some(Kind::Date) | Some(Kind::Moment) => {
9246            return Err(WasmLowerError::Unsupported("comparison of temporal values"))
9247        }
9248        Some(Kind::SeqInt)
9249        | Some(Kind::SeqBool)
9250        | Some(Kind::SeqFloat)
9251        | Some(Kind::SeqText)
9252        | Some(Kind::SeqStruct)
9253        | Some(Kind::SeqEnum)
9254        | Some(Kind::SeqSeqInt)
9255        | Some(Kind::SeqHandle)
9256        | Some(Kind::SeqAny)
9257        | Some(Kind::SeqWord32)
9258        | Some(Kind::SeqWord64) => {
9259            return Err(WasmLowerError::Unsupported("comparison of sequences"))
9260        }
9261        Some(Kind::Text) => return Err(WasmLowerError::Unsupported("comparison of text values")),
9262        Some(Kind::Tower) => {
9263            return Err(WasmLowerError::Unsupported(
9264                "comparison of an exact value outside the value runtime",
9265            ))
9266        }
9267        Some(Kind::Struct) => {
9268            return Err(WasmLowerError::Unsupported("comparison of struct values"))
9269        }
9270        Some(Kind::Map) => return Err(WasmLowerError::Unsupported("comparison of map values")),
9271        Some(Kind::Set) | Some(Kind::SetText) | Some(Kind::CrdtSetText) => {
9272            return Err(WasmLowerError::Unsupported("comparison of set values"))
9273        }
9274        // A raw counter object never reaches a compare — `obj's counter` projects to its Int total at
9275        // GetField, so a relational test sees the `Int`. A direct compare of the counter object is
9276        // soundly refused (the native AOT / VM compare counters as their value; the WASM tier does so
9277        // only through the projected Int).
9278        Some(Kind::CrdtCounter) => {
9279            return Err(WasmLowerError::Unsupported(
9280                "comparison of counter CRDT values",
9281            ))
9282        }
9283        Some(Kind::Enum) => return Err(WasmLowerError::Unsupported("comparison of enum values")),
9284        Some(Kind::Closure) => {
9285            return Err(WasmLowerError::Unsupported("comparison of closure values"))
9286        }
9287        Some(Kind::Tuple) => return Err(WasmLowerError::Unsupported("comparison of tuple values")),
9288        Some(Kind::Rational) => {
9289            return Err(WasmLowerError::Unsupported("comparison of rational values"))
9290        }
9291        Some(Kind::BigInt) => {
9292            return Err(WasmLowerError::Unsupported("comparison of bigint values"))
9293        }
9294        Some(Kind::Complex) => {
9295            return Err(WasmLowerError::Unsupported("comparison of complex values"))
9296        }
9297        Some(Kind::Modular) => {
9298            return Err(WasmLowerError::Unsupported("comparison of modular values"))
9299        }
9300        Some(Kind::Decimal) => {
9301            return Err(WasmLowerError::Unsupported("comparison of decimal values"))
9302        }
9303        Some(Kind::Money) => return Err(WasmLowerError::Unsupported("comparison of money values")),
9304        Some(Kind::Quantity) => {
9305            return Err(WasmLowerError::Unsupported("comparison of quantity values"))
9306        }
9307        Some(Kind::Uuid) => {
9308            return Err(WasmLowerError::Unsupported(
9309                "ordering comparison of uuid values",
9310            ))
9311        }
9312        Some(Kind::LanesV) => {
9313            return Err(WasmLowerError::Unsupported(
9314                "comparison of lane-vector values",
9315            ))
9316        }
9317        Some(Kind::Dynamic) => {
9318            return Err(WasmLowerError::Unsupported(
9319                "comparison of dynamic wire values",
9320            ))
9321        }
9322        Some(Kind::Lanes) => return Err(WasmLowerError::Unsupported("comparison of lane vectors")),
9323        // Optional comparisons are handled or refused before scalar dispatch.
9324        Some(Kind::Optional) => {
9325            unreachable!("optional comparisons handled by the is-nothing path above")
9326        }
9327        None => {
9328            return Err(WasmLowerError::Unsupported(
9329                "comparison of unknown-kind values",
9330            ))
9331        }
9332    }
9333    Ok(Flow::Straight)
9334}
9335
9336/// Push a register as an `f64` on the wasm stack — directly for a Float, via `f64.convert_i64_s`
9337/// for an Int.
9338/// `a is approximately b` — the shared isclose semantics
9339/// (`logicaffeine_data::ops::logos_approx_eq`), lowered as pure f64
9340/// instructions so the result is bit-identical to every other engine:
9341/// `(a == b) || |a - b| <= max(1e-9 * max(|a|, |b|), 1e-12)`.
9342/// `dst = lhs <cmp> rhs` over exact rationals (linker mode): both operands as `Rational` handles (an `Int` or
9343/// `BigInt` widens), ordered by the runtime's `Rational::cmp` — exact, never through a float.
9344fn lower_rational_compare(
9345    code: &mut Vec<u8>,
9346    kinds: &KindTable,
9347    ctx: &Ctx,
9348    dst: u16,
9349    lhs: u16,
9350    rhs: u16,
9351    cmp: Cmp,
9352) -> R<Flow> {
9353    let real = |r: u16| kinds.get(r as usize) == Some(Kind::Float);
9354    if real(lhs) || real(rhs) {
9355        // A rational against a real, by the real's exact value: -1, 0, 1, or 2 for a NaN, which orders against
9356        // nothing and equals nothing.
9357        let (rational, f, flipped) = if real(rhs) { (lhs, rhs, false) } else { (rhs, lhs, true) };
9358        let idx = (ctx.host_index)(HostFn::RationalCmpF64)
9359            .ok_or(WasmLowerError::Unsupported("rational_cmp_f64 not imported"))?;
9360        local_get(code, rational as u32);
9361        local_get(code, f as u32);
9362        code.push(0x10);
9363        leb_u32(code, idx);
9364        let cmp = match (cmp, flipped) {
9365            (Cmp::Lt, true) => Cmp::Gt,
9366            (Cmp::Gt, true) => Cmp::Lt,
9367            (Cmp::Le, true) => Cmp::Ge,
9368            (Cmp::Ge, true) => Cmp::Le,
9369            (c, _) => c,
9370        };
9371        match cmp {
9372            Cmp::Eq => code.push(0x45), // i32.eqz
9373            Cmp::Ne => code.extend([0x45, 0x45]),
9374            Cmp::Lt => {
9375                i32_const(code, 0);
9376                code.push(0x48); // i32.lt_s
9377            }
9378            Cmp::Gt => {
9379                i32_const(code, 1);
9380                code.push(0x46); // i32.eq
9381            }
9382            Cmp::Le => {
9383                i32_const(code, 1);
9384                code.push(0x48); // i32.lt_s
9385            }
9386            Cmp::Ge => {
9387                i32_const(code, 2);
9388                code.push(0x49); // i32.lt_u: 0 or 1; -1 and NaN's 2 are not
9389            }
9390        }
9391        code.push(0xAD); // i64.extend_i32_u
9392        local_set(code, dst as u32);
9393        return Ok(Flow::Straight);
9394    }
9395    push_rational_operand(code, kinds, ctx, lhs)?;
9396    push_rational_operand(code, kinds, ctx, rhs)?;
9397    let order = (ctx.host_index)(HostFn::RationalCmp)
9398        .ok_or(WasmLowerError::Unsupported("rational_cmp not imported"))?;
9399    code.push(0x10);
9400    leb_u32(code, order);
9401    match cmp {
9402        Cmp::Eq => code.push(0x45), // i32.eqz
9403        Cmp::Ne => code.extend([0x45, 0x45]),
9404        Cmp::Lt | Cmp::Gt | Cmp::Le | Cmp::Ge => {
9405            i32_const(code, 0);
9406            code.push(match cmp {
9407                Cmp::Lt => 0x48, // i32.lt_s
9408                Cmp::Gt => 0x4A, // i32.gt_s
9409                Cmp::Le => 0x4C, // i32.le_s
9410                _ => 0x4E,       // i32.ge_s
9411            });
9412        }
9413    }
9414    code.push(0xAD); // i64.extend_i32_u — the VM's truthy-Int boolean width
9415    local_set(code, dst as u32);
9416    Ok(Flow::Straight)
9417}
9418
9419fn lower_approx_eq(code: &mut Vec<u8>, kinds: &KindTable, dst: u16, lhs: u16, rhs: u16) -> R<Flow> {
9420    let lk = kinds.get(lhs as usize);
9421    let rk = kinds.get(rhs as usize);
9422    // c1: a == b (the exact fast path — also makes inf ≈ inf hold).
9423    push_as_f64(code, lhs, lk)?;
9424    push_as_f64(code, rhs, rk)?;
9425    code.push(0x61); // f64.eq → i32
9426                     // diff = |a - b|
9427    push_as_f64(code, lhs, lk)?;
9428    push_as_f64(code, rhs, rk)?;
9429    code.push(0xA1); // f64.sub
9430    code.push(0x99); // f64.abs
9431                     // tol = max(1e-9 * max(|a|, |b|), 1e-12)
9432    push_as_f64(code, lhs, lk)?;
9433    code.push(0x99); // f64.abs
9434    push_as_f64(code, rhs, rk)?;
9435    code.push(0x99); // f64.abs
9436    code.push(0xA5); // f64.max
9437    code.push(0x44); // f64.const 1e-9
9438    code.extend_from_slice(&1e-9f64.to_le_bytes());
9439    code.push(0xA2); // f64.mul
9440    code.push(0x44); // f64.const 1e-12
9441    code.extend_from_slice(&1e-12f64.to_le_bytes());
9442    code.push(0xA5); // f64.max
9443                     // c2: diff <= tol
9444    code.push(0x65); // f64.le → i32
9445    code.push(0x72); // i32.or (c1 | c2)
9446    code.push(0xAD); // i64.extend_i32_u — the VM's truthy-Int boolean width
9447    local_set(code, dst as u32);
9448    Ok(Flow::Straight)
9449}
9450
9451/// [`push_as_f64`], a linked rational as the double the VM computes with when it meets a real.
9452fn push_number_as_f64(code: &mut Vec<u8>, ctx: &Ctx, reg: u16, kind: Option<Kind>) -> R<()> {
9453    if kind == Some(Kind::Rational) {
9454        let idx = (ctx.host_index)(HostFn::RationalToF64)
9455            .ok_or(WasmLowerError::Unsupported("rational_to_f64 not imported"))?;
9456        local_get(code, reg as u32);
9457        code.push(0x10);
9458        leb_u32(code, idx);
9459        return Ok(());
9460    }
9461    push_as_f64(code, reg, kind)
9462}
9463
9464fn push_as_f64(code: &mut Vec<u8>, reg: u16, kind: Option<Kind>) -> R<()> {
9465    local_get(code, reg as u32);
9466    match kind {
9467        Some(Kind::Float) => {}
9468        Some(Kind::Int) => code.push(0xB9), // f64.convert_i64_s
9469        _ => {
9470            return Err(WasmLowerError::Unsupported(
9471                "numeric builtin on a non-number",
9472            ))
9473        }
9474    }
9475    Ok(())
9476}
9477
9478/// Lower a numeric builtin call, bit-exactly matching the VM (`semantics/builtins.rs`).
9479fn lower_builtin(
9480    code: &mut Vec<u8>,
9481    kinds: &KindTable,
9482    dst: u16,
9483    builtin: BuiltinId,
9484    args_start: u16,
9485    arg_count: u16,
9486) -> R<Flow> {
9487    let arg = args_start;
9488    let ak = kinds.get(arg as usize);
9489    match builtin {
9490        // `sqrt` → Float (Int converts first), matching `(n as f64).sqrt()`.
9491        BuiltinId::Sqrt => {
9492            push_as_f64(code, arg, ak)?;
9493            code.push(0x9F); // f64.sqrt
9494            local_set(code, dst as u32);
9495            Ok(Flow::Straight)
9496        }
9497        // `floor`/`ceil` → Int via the SATURATING truncation (matches `f.floor() as i64`), or the
9498        // identity on an already-whole Int. (A LINKED `Rational` arg is handled in the main `lower_op`
9499        // match, which has the `ctx` host table — the exact `logos_rt_rational_*` rounding.)
9500        BuiltinId::Floor => lower_floor_ceil(code, ak, dst, arg, 0x9C), // f64.floor
9501        BuiltinId::Ceil => lower_floor_ceil(code, ak, dst, arg, 0x9B),  // f64.ceil
9502        // `round` → round-half-AWAY-from-zero (Rust's `f64::round`, NOT wasm's round-half-even):
9503        // `trunc(x + copysign(0.5, x))`, then the saturating cast. Identity on a whole Int.
9504        BuiltinId::Round => match ak {
9505            Some(Kind::Float) => {
9506                local_get(code, arg as u32);
9507                code.push(0x44); // f64.const 0.5
9508                code.extend_from_slice(&0.5f64.to_le_bytes());
9509                local_get(code, arg as u32);
9510                code.push(0xA6); // f64.copysign → 0.5 with x's sign
9511                code.push(0xA0); // f64.add → x + copysign(0.5, x)
9512                code.push(0x9D); // f64.trunc
9513                code.push(0xFC); // saturating-truncation prefix
9514                leb_u32(code, 6); // i64.trunc_sat_f64_s
9515                local_set(code, dst as u32);
9516                Ok(Flow::Straight)
9517            }
9518            Some(Kind::Int) => {
9519                local_get(code, arg as u32);
9520                local_set(code, dst as u32);
9521                Ok(Flow::Straight)
9522            }
9523            _ => Err(WasmLowerError::Unsupported("round of a non-number")),
9524        },
9525        // `abs`: f64.abs for a Float; for an Int, `x < 0 ? -x : x` with an i64::MIN overflow trap
9526        // (|i64::MIN| does not fit i64 — the VM promotes to BigInt; the standalone module traps,
9527        // matching the checked-arithmetic contract).
9528        BuiltinId::Abs => match ak {
9529            Some(Kind::Float) => {
9530                local_get(code, arg as u32);
9531                code.push(0x99); // f64.abs
9532                local_set(code, dst as u32);
9533                Ok(Flow::Straight)
9534            }
9535            Some(Kind::Int) => {
9536                // trap if arg == i64::MIN
9537                local_get(code, arg as u32);
9538                code.push(0x42); // i64.const i64::MIN
9539                leb_i64(code, i64::MIN);
9540                code.push(0x51); // i64.eq
9541                code.push(0x04);
9542                code.push(0x40); // if (void)
9543                code.push(0x00); // unreachable
9544                code.push(0x0B); // end
9545                                 // x < 0 ? -x : x
9546                code.push(0x42);
9547                leb_i64(code, 0); // i64.const 0
9548                local_get(code, arg as u32);
9549                code.push(0x7D); // i64.sub → -x  (value-if-true)
9550                local_get(code, arg as u32); // x  (value-if-false)
9551                local_get(code, arg as u32);
9552                code.push(0x42);
9553                leb_i64(code, 0);
9554                code.push(0x53); // i64.lt_s → x < 0 (selector)
9555                code.push(0x1B); // select
9556                local_set(code, dst as u32);
9557                Ok(Flow::Straight)
9558            }
9559            _ => Err(WasmLowerError::Unsupported("abs of a non-number")),
9560        },
9561        BuiltinId::Min => lower_minmax(code, kinds, dst, args_start, arg_count, false),
9562        BuiltinId::Max => lower_minmax(code, kinds, dst, args_start, arg_count, true),
9563        // `count_ones(n)` → the population count of the Int's u64 bit pattern (`i64.popcnt`), an Int.
9564        // Matches the VM's `(n as u64).count_ones() as i64`.
9565        BuiltinId::CountOnes => {
9566            local_get(code, arg as u32);
9567            code.push(0x7B); // i64.popcnt
9568            local_set(code, dst as u32);
9569            Ok(Flow::Straight)
9570        }
9571        // `leading_zeros(n)` / `trailing_zeros(n)` → the Int's high/low zero-bit
9572        // count (`i64.clz` / `i64.ctz`; both give 64 for 0), matching the VM.
9573        BuiltinId::LeadingZeros => {
9574            local_get(code, arg as u32);
9575            code.push(0x79); // i64.clz
9576            local_set(code, dst as u32);
9577            Ok(Flow::Straight)
9578        }
9579        BuiltinId::TrailingZeros => {
9580            local_get(code, arg as u32);
9581            code.push(0x7A); // i64.ctz
9582            local_set(code, dst as u32);
9583            Ok(Flow::Straight)
9584        }
9585        // ── Word ring (ℤ/2ⁿ) construct / extract ──
9586        // `word32(n)` = the low 32 bits of the Int (`i32.wrap_i64`); `word64(n)` = the Int's bits
9587        // unchanged (an `i64` IS the u64 representation).
9588        BuiltinId::Word32 => {
9589            local_get(code, arg as u32);
9590            code.push(0xA7); // i32.wrap_i64
9591            local_set(code, dst as u32);
9592            Ok(Flow::Straight)
9593        }
9594        BuiltinId::Word64 => {
9595            local_get(code, arg as u32);
9596            local_set(code, dst as u32);
9597            Ok(Flow::Straight)
9598        }
9599        // `intOfWord32(w)` = zero-extend the u32 to Int (`i64.extend_i32_u`); `intOfWord64(w)` = the
9600        // 64-bit pattern unchanged (Int is i64).
9601        BuiltinId::IntOfWord32 => {
9602            local_get(code, arg as u32);
9603            code.push(0xAD); // i64.extend_i32_u
9604            local_set(code, dst as u32);
9605            Ok(Flow::Straight)
9606        }
9607        BuiltinId::IntOfWord64 => {
9608            local_get(code, arg as u32);
9609            local_set(code, dst as u32);
9610            Ok(Flow::Straight)
9611        }
9612        // ── Word rotate (`rotl`/`rotr`) — native `i32.rotl`/`i64.rotl` etc., dispatched on the word
9613        //    operand's width. The rotate count (an Int) narrows to `i32` for a `Word32`. ──
9614        BuiltinId::Rotl | BuiltinId::Rotr => {
9615            let is_l = matches!(builtin, BuiltinId::Rotl);
9616            match kinds.get(args_start as usize) {
9617                Some(Kind::Word32) => {
9618                    local_get(code, args_start as u32);
9619                    local_get(code, (args_start + 1) as u32);
9620                    code.push(0xA7); // i32.wrap_i64 — count as i32
9621                    code.push(if is_l { 0x77 } else { 0x78 }); // i32.rotl / i32.rotr
9622                }
9623                Some(Kind::Word64) => {
9624                    local_get(code, args_start as u32);
9625                    local_get(code, (args_start + 1) as u32);
9626                    code.push(if is_l { 0x89 } else { 0x8A }); // i64.rotl / i64.rotr
9627                }
9628                _ => return Err(WasmLowerError::Unsupported("rotate of a non-Word value")),
9629            }
9630            local_set(code, dst as u32);
9631            Ok(Flow::Straight)
9632        }
9633        // ── Word bitwise `word_and`/`word_or`/`word_not` — native and/or/xor, dispatched on width. ──
9634        BuiltinId::Wand | BuiltinId::Wor => {
9635            let is_and = matches!(builtin, BuiltinId::Wand);
9636            let op32 = if is_and { 0x71 } else { 0x72 }; // i32.and / i32.or
9637            let op64 = if is_and { 0x83 } else { 0x84 }; // i64.and / i64.or
9638            match kinds.get(args_start as usize) {
9639                Some(Kind::Word32) => {
9640                    local_get(code, args_start as u32);
9641                    local_get(code, (args_start + 1) as u32);
9642                    code.push(op32);
9643                }
9644                Some(Kind::Word64) => {
9645                    local_get(code, args_start as u32);
9646                    local_get(code, (args_start + 1) as u32);
9647                    code.push(op64);
9648                }
9649                _ => {
9650                    return Err(WasmLowerError::Unsupported(
9651                        "word_and/or of a non-Word value",
9652                    ))
9653                }
9654            }
9655            local_set(code, dst as u32);
9656            Ok(Flow::Straight)
9657        }
9658        // `word_not(w)` = XOR with all-ones (wasm has no `i32.not`).
9659        BuiltinId::Wnot => {
9660            match kinds.get(arg as usize) {
9661                Some(Kind::Word32) => {
9662                    local_get(code, arg as u32);
9663                    i32_const(code, -1);
9664                    code.push(0x73); // i32.xor
9665                }
9666                Some(Kind::Word64) => {
9667                    local_get(code, arg as u32);
9668                    i64c(code, -1);
9669                    code.push(0x85); // i64.xor
9670                }
9671                _ => return Err(WasmLowerError::Unsupported("word_not of a non-Word value")),
9672            }
9673            local_set(code, dst as u32);
9674            Ok(Flow::Straight)
9675        }
9676        // ── `word64Shl`/`word64Shr`/`word64And` — the Word64 shift/mask primitives (Keccak). ──
9677        BuiltinId::Word64Shl | BuiltinId::Word64Shr | BuiltinId::Word64And => {
9678            local_get(code, args_start as u32);
9679            local_get(code, (args_start + 1) as u32);
9680            code.push(match builtin {
9681                BuiltinId::Word64Shl => 0x86, // i64.shl
9682                BuiltinId::Word64Shr => 0x88, // i64.shr_u (Word64 is unsigned)
9683                _ => 0x83,                    // i64.and
9684            });
9685            local_set(code, dst as u32);
9686            Ok(Flow::Straight)
9687        }
9688        // ── `word32Shr` — logical right-shift of a Word32 (SHA-256 `σ0`/`σ1`). The shift amount is an
9689        //    Int (i64) so it narrows to i32; `i32.shr_u` is unsigned, so the vacated high bits are 0. ──
9690        BuiltinId::Word32Shr => {
9691            local_get(code, args_start as u32);
9692            local_get(code, (args_start + 1) as u32);
9693            code.push(0xA7); // i32.wrap_i64 — shift amount as i32
9694            code.push(0x76); // i32.shr_u
9695            local_set(code, dst as u32);
9696            Ok(Flow::Straight)
9697        }
9698        other => {
9699            // Name the builtin under the trace — "builtin not yet lowered" describes the backend
9700            // and leaves the reader with no idea which sentence in their page caused it.
9701            if std::env::var_os("LOGOS_WASM_TRACE_FIELD").is_some() {
9702                eprintln!("[wasm] builtin not yet lowered: {other:?}");
9703            }
9704            Err(WasmLowerError::Unsupported("builtin not yet lowered"))
9705        }
9706    }
9707}
9708
9709/// `floor`/`ceil` (`fop` = `f64.floor`/`f64.ceil`): a Float rounds then truncates with the
9710/// saturating cast to match the VM's `as i64`; an already-whole Int is returned unchanged.
9711fn lower_floor_ceil(
9712    code: &mut Vec<u8>,
9713    arg_kind: Option<Kind>,
9714    dst: u16,
9715    arg: u16,
9716    fop: u8,
9717) -> R<Flow> {
9718    match arg_kind {
9719        Some(Kind::Float) => {
9720            local_get(code, arg as u32);
9721            code.push(fop); // f64.floor / f64.ceil
9722            code.push(0xFC); // saturating-truncation prefix
9723            leb_u32(code, 6); // i64.trunc_sat_f64_s
9724            local_set(code, dst as u32);
9725        }
9726        Some(Kind::Int) => {
9727            local_get(code, arg as u32);
9728            local_set(code, dst as u32);
9729        }
9730        _ => return Err(WasmLowerError::Unsupported("floor/ceil of a non-number")),
9731    }
9732    Ok(Flow::Straight)
9733}
9734
9735/// `min`/`max` (`is_max` selects max). `Int×Int` is an `i64` compare + `select`. Any Float
9736/// operand promotes both to `f64` and uses `f64.min`/`f64.max` — but with explicit NaN guards,
9737/// because Rust's `f64::min`/`max` return the NON-NaN argument whereas raw `f64.min`/`f64.max`
9738/// return NaN. The `±0` case already agrees between the two.
9739fn lower_minmax(
9740    code: &mut Vec<u8>,
9741    kinds: &KindTable,
9742    dst: u16,
9743    args_start: u16,
9744    arg_count: u16,
9745    is_max: bool,
9746) -> R<Flow> {
9747    if arg_count != 2 {
9748        return Err(WasmLowerError::Unsupported("min/max arity"));
9749    }
9750    let (a, b) = (args_start, args_start + 1);
9751    let (ak, bk) = (kinds.get(a as usize), kinds.get(b as usize));
9752    match (ak, bk) {
9753        (Some(Kind::Int), Some(Kind::Int)) => {
9754            local_get(code, a as u32); // value-if-true
9755            local_get(code, b as u32); // value-if-false
9756            local_get(code, a as u32);
9757            local_get(code, b as u32);
9758            code.push(if is_max { 0x55 } else { 0x53 }); // i64.gt_s / i64.lt_s
9759            code.push(0x1B); // select
9760            local_set(code, dst as u32);
9761            Ok(Flow::Straight)
9762        }
9763        (a_some, b_some) if a_some.is_some() && b_some.is_some() => {
9764            let fop = if is_max { 0xA5 } else { 0xA4 }; // f64.max / f64.min
9765                                                        // result = a_nan ? b_f : (b_nan ? a_f : fop(a_f, b_f))
9766            push_as_f64(code, b, bk)?; // [b_f]              (value-if-true for the outer select)
9767            push_as_f64(code, a, ak)?; // [b_f, a_f]         (value-if-true for the inner select)
9768            push_as_f64(code, a, ak)?;
9769            push_as_f64(code, b, bk)?;
9770            code.push(fop); // [b_f, a_f, fop(a_f,b_f)]      (value-if-false for the inner select)
9771            push_as_f64(code, b, bk)?;
9772            push_as_f64(code, b, bk)?;
9773            code.push(0x62); // f64.ne → b_nan               (inner selector)
9774            code.push(0x1B); // select → [b_f, inner]
9775            push_as_f64(code, a, ak)?;
9776            push_as_f64(code, a, ak)?;
9777            code.push(0x62); // f64.ne → a_nan                (outer selector)
9778            code.push(0x1B); // select → [result]
9779            local_set(code, dst as u32);
9780            Ok(Flow::Straight)
9781        }
9782        _ => Err(WasmLowerError::Unsupported("min/max of non-numbers")),
9783    }
9784}
9785
9786/// The host `pow` import a `pow(base, exp)` needs, by operand kinds: any `^Float` uses
9787/// `pow_ff` (`f64::powf`); `Float^Int` uses `pow_fi` (`f64::powi`); `Int^Int` uses neither (an
9788/// integer exponentiation-by-squaring loop, [`lower_int_pow`]).
9789fn pow_host_for(base: Option<Kind>, exp: Option<Kind>) -> Option<HostFn> {
9790    match (base, exp) {
9791        (_, Some(Kind::Float)) => Some(HostFn::PowFf),
9792        (Some(Kind::Float), Some(Kind::Int)) => Some(HostFn::PowFi),
9793        // `pow(m, e)` on a ℤ/nℤ base (linker-only kind) → modular exponentiation.
9794        (Some(Kind::Modular), Some(Kind::Int)) => Some(HostFn::ModularPow),
9795        _ => None,
9796    }
9797}
9798
9799/// Lower `pow(base, exp)` bit-exactly. Float-result cases (any Float operand) defer to the host
9800/// `pow_ff`/`pow_fi` (so `powf` vs `powi` exactly match the VM). `Int^Int` is computed in-module
9801/// by [`lower_int_pow`] (Int result, overflow-trapping). A negative Int exponent (VM → Float)
9802/// traps, since a Float cannot ride the Int result slot.
9803fn lower_pow(
9804    code: &mut Vec<u8>,
9805    kinds: &KindTable,
9806    ctx: &Ctx,
9807    num_regs: u32,
9808    dst: u16,
9809    args_start: u16,
9810    arg_count: u16,
9811) -> R<Flow> {
9812    if arg_count != 2 {
9813        return Err(WasmLowerError::Unsupported("pow arity"));
9814    }
9815    lower_pow_regs(code, kinds, ctx, num_regs, dst, args_start, args_start + 1)
9816}
9817
9818/// Shared core of `pow(base, exp)` and the `**` operator (`Op::Pow`): the two operands are given as
9819/// explicit registers (adjacent for the builtin, arbitrary for the operator). Float-result cases
9820/// defer to the host `pow_ff`/`pow_fi`; `Int^Int` is the in-module overflow-trapping squaring loop.
9821/// Push an i32 `BigInt` handle for `reg` onto the wasm stack: a `Kind::BigInt` register pushes its
9822/// handle directly; an `Int` register is promoted with `logos_rt_bigint_from_i64`. Brings a mixed
9823/// `BigInt <op> Int` operand to a common handle type before a `logos_rt_bigint_*` call.
9824fn push_bigint_operand(code: &mut Vec<u8>, kinds: &KindTable, ctx: &Ctx, reg: u16) -> R<()> {
9825    match kinds.get(reg as usize) {
9826        Some(Kind::BigInt) => local_get(code, reg as u32),
9827        Some(Kind::Int) => {
9828            let from_i64 = (ctx.host_index)(HostFn::BigintFromI64)
9829                .ok_or(WasmLowerError::Unsupported("bigint_from_i64 not imported"))?;
9830            local_get(code, reg as u32);
9831            code.push(0x10);
9832            leb_u32(code, from_i64);
9833        }
9834        _ => {
9835            return Err(WasmLowerError::Unsupported(
9836                "bigint arithmetic operand must be a BigInt or an Int",
9837            ))
9838        }
9839    }
9840    Ok(())
9841}
9842
9843/// `dst = lhs <op> rhs` as an exact big-integer binary operation (linker mode) — `op` is the
9844/// `logos_rt_bigint_{mul,add,sub}` sink. Both operands are brought to BigInt handles (an `Int` operand
9845/// promoted via `from_i64`); the resulting handle binds `dst`.
9846fn lower_bigint_binop(
9847    code: &mut Vec<u8>,
9848    kinds: &KindTable,
9849    ctx: &Ctx,
9850    dst: u16,
9851    lhs: u16,
9852    rhs: u16,
9853    host: HostFn,
9854) -> R<Flow> {
9855    let op = (ctx.host_index)(host).ok_or(WasmLowerError::Unsupported("bigint op not imported"))?;
9856    push_bigint_operand(code, kinds, ctx, lhs)?;
9857    push_bigint_operand(code, kinds, ctx, rhs)?;
9858    code.push(0x10);
9859    leb_u32(code, op);
9860    local_set(code, dst as u32);
9861    Ok(Flow::Straight)
9862}
9863
9864/// Push an i32 `Complex` handle for `reg`: a `Kind::Complex` register pushes its handle directly; an
9865/// `Int` operand `n` promotes to the real Complex `n + 0i` via `logos_rt_complex_from_i64(n, 0)`.
9866fn push_complex_operand(code: &mut Vec<u8>, kinds: &KindTable, ctx: &Ctx, reg: u16) -> R<()> {
9867    match kinds.get(reg as usize) {
9868        Some(Kind::Complex) => local_get(code, reg as u32),
9869        Some(Kind::Int) => {
9870            let from = (ctx.host_index)(HostFn::ComplexFromI64)
9871                .ok_or(WasmLowerError::Unsupported("complex_from_i64 not imported"))?;
9872            local_get(code, reg as u32);
9873            code.push(0x42); // i64.const 0 — the imaginary part of a promoted real
9874            leb_i64(code, 0);
9875            code.push(0x10);
9876            leb_u32(code, from);
9877        }
9878        _ => {
9879            return Err(WasmLowerError::Unsupported(
9880                "complex arithmetic operand must be a Complex or an Int",
9881            ))
9882        }
9883    }
9884    Ok(())
9885}
9886
9887/// `dst = lhs <op> rhs` as exact complex arithmetic (linker mode) — `op` is the
9888/// `logos_rt_complex_{add,sub,mul}` sink; both operands become Complex handles (an `Int` promoted).
9889fn lower_complex_binop(
9890    code: &mut Vec<u8>,
9891    kinds: &KindTable,
9892    ctx: &Ctx,
9893    dst: u16,
9894    lhs: u16,
9895    rhs: u16,
9896    host: HostFn,
9897) -> R<Flow> {
9898    let op =
9899        (ctx.host_index)(host).ok_or(WasmLowerError::Unsupported("complex op not imported"))?;
9900    push_complex_operand(code, kinds, ctx, lhs)?;
9901    push_complex_operand(code, kinds, ctx, rhs)?;
9902    code.push(0x10);
9903    leb_u32(code, op);
9904    local_set(code, dst as u32);
9905    Ok(Flow::Straight)
9906}
9907
9908/// Push an i32 `Modular` handle for `reg` (a `Kind::Modular` register). An `Int` operand can NOT be
9909/// promoted (the ring modulus is unknown), so a non-Modular operand is soundly refused.
9910fn push_modular_operand(code: &mut Vec<u8>, kinds: &KindTable, reg: u16) -> R<()> {
9911    match kinds.get(reg as usize) {
9912        Some(Kind::Modular) => local_get(code, reg as u32),
9913        _ => {
9914            return Err(WasmLowerError::Unsupported(
9915                "modular arithmetic operand must be a Modular",
9916            ))
9917        }
9918    }
9919    Ok(())
9920}
9921
9922/// `dst = lhs <op> rhs` as exact ℤ/nℤ arithmetic (linker mode) — `op` is the `logos_rt_modular_*` sink.
9923fn lower_modular_binop(
9924    code: &mut Vec<u8>,
9925    kinds: &KindTable,
9926    ctx: &Ctx,
9927    dst: u16,
9928    lhs: u16,
9929    rhs: u16,
9930    host: HostFn,
9931) -> R<Flow> {
9932    let op =
9933        (ctx.host_index)(host).ok_or(WasmLowerError::Unsupported("modular op not imported"))?;
9934    push_modular_operand(code, kinds, lhs)?;
9935    push_modular_operand(code, kinds, rhs)?;
9936    code.push(0x10);
9937    leb_u32(code, op);
9938    local_set(code, dst as u32);
9939    Ok(Flow::Straight)
9940}
9941
9942/// Push an i32 `Decimal` handle for `reg`: a `Kind::Decimal` register pushes its handle; an `Int`
9943/// operand `n` promotes to the exact Decimal `n` via `logos_rt_decimal_from_i64(n)` (`price * 3`).
9944fn push_decimal_operand(code: &mut Vec<u8>, kinds: &KindTable, ctx: &Ctx, reg: u16) -> R<()> {
9945    match kinds.get(reg as usize) {
9946        Some(Kind::Decimal) => local_get(code, reg as u32),
9947        Some(Kind::Int) => {
9948            let from = (ctx.host_index)(HostFn::DecimalFromI64)
9949                .ok_or(WasmLowerError::Unsupported("decimal_from_i64 not imported"))?;
9950            local_get(code, reg as u32);
9951            code.push(0x10);
9952            leb_u32(code, from);
9953        }
9954        _ => {
9955            return Err(WasmLowerError::Unsupported(
9956                "decimal arithmetic operand must be a Decimal or an Int",
9957            ))
9958        }
9959    }
9960    Ok(())
9961}
9962
9963/// `dst = lhs <op> rhs` as exact base-10 arithmetic (linker mode) — `op` is the `logos_rt_decimal_*` sink.
9964fn lower_decimal_binop(
9965    code: &mut Vec<u8>,
9966    kinds: &KindTable,
9967    ctx: &Ctx,
9968    dst: u16,
9969    lhs: u16,
9970    rhs: u16,
9971    host: HostFn,
9972) -> R<Flow> {
9973    let op =
9974        (ctx.host_index)(host).ok_or(WasmLowerError::Unsupported("decimal op not imported"))?;
9975    push_decimal_operand(code, kinds, ctx, lhs)?;
9976    push_decimal_operand(code, kinds, ctx, rhs)?;
9977    code.push(0x10);
9978    leb_u32(code, op);
9979    local_set(code, dst as u32);
9980    Ok(Flow::Straight)
9981}
9982
9983fn push_money_operand(code: &mut Vec<u8>, kinds: &KindTable, _ctx: &Ctx, reg: u16) -> R<()> {
9984    match kinds.get(reg as usize) {
9985        Some(Kind::Money) => local_get(code, reg as u32),
9986        _ => {
9987            return Err(WasmLowerError::Unsupported(
9988                "money arithmetic operand must be a Money value",
9989            ))
9990        }
9991    }
9992    Ok(())
9993}
9994
9995/// `dst = lhs <op> rhs` as exact currency arithmetic (linker mode) — `op` is the `logos_rt_money_*` sink.
9996fn lower_money_binop(
9997    code: &mut Vec<u8>,
9998    kinds: &KindTable,
9999    ctx: &Ctx,
10000    dst: u16,
10001    lhs: u16,
10002    rhs: u16,
10003    host: HostFn,
10004) -> R<Flow> {
10005    let op = (ctx.host_index)(host).ok_or(WasmLowerError::Unsupported("money op not imported"))?;
10006    push_money_operand(code, kinds, ctx, lhs)?;
10007    push_money_operand(code, kinds, ctx, rhs)?;
10008    code.push(0x10);
10009    leb_u32(code, op);
10010    local_set(code, dst as u32);
10011    Ok(Flow::Straight)
10012}
10013
10014fn push_quantity_operand(code: &mut Vec<u8>, kinds: &KindTable, _ctx: &Ctx, reg: u16) -> R<()> {
10015    match kinds.get(reg as usize) {
10016        Some(Kind::Quantity) => local_get(code, reg as u32),
10017        // Scalar-scaling a Quantity by a bare number (`q * 2`) has no linked runtime sink yet — refuse
10018        // it cleanly rather than pass a scalar where the runtime expects a Quantity handle.
10019        _ => {
10020            return Err(WasmLowerError::Unsupported(
10021                "quantity arithmetic operand must be a Quantity value",
10022            ))
10023        }
10024    }
10025    Ok(())
10026}
10027
10028/// `dst = lhs <op> rhs` as exact dimensional arithmetic (linker mode) — `op` is the `logos_rt_quantity_*`
10029/// sink. `+`/`-` keep the left display unit; `×`/`÷` combine dimensions and render in SI/dimension form.
10030fn lower_quantity_binop(
10031    code: &mut Vec<u8>,
10032    kinds: &KindTable,
10033    ctx: &Ctx,
10034    dst: u16,
10035    lhs: u16,
10036    rhs: u16,
10037    host: HostFn,
10038) -> R<Flow> {
10039    let op =
10040        (ctx.host_index)(host).ok_or(WasmLowerError::Unsupported("quantity op not imported"))?;
10041    push_quantity_operand(code, kinds, ctx, lhs)?;
10042    push_quantity_operand(code, kinds, ctx, rhs)?;
10043    code.push(0x10);
10044    leb_u32(code, op);
10045    local_set(code, dst as u32);
10046    Ok(Flow::Straight)
10047}
10048
10049/// Push a Rational operand as a `logos_rt_rational` handle: a Rational rides as-is, an Int widens via
10050/// `from_i64`, a BigInt via `from_bigint` (matching the VM's `rat_of` view of every exact number as a
10051/// Rational). Any other operand is refused (a Rational never mixes with a Float or a heap value).
10052fn push_rational_operand(code: &mut Vec<u8>, kinds: &KindTable, ctx: &Ctx, reg: u16) -> R<()> {
10053    match kinds.get(reg as usize) {
10054        Some(Kind::Rational) => local_get(code, reg as u32),
10055        Some(Kind::Int) => {
10056            let from = (ctx.host_index)(HostFn::RationalFromI64).ok_or(
10057                WasmLowerError::Unsupported("rational_from_i64 not imported"),
10058            )?;
10059            local_get(code, reg as u32);
10060            code.push(0x10);
10061            leb_u32(code, from);
10062        }
10063        Some(Kind::BigInt) => {
10064            let from = (ctx.host_index)(HostFn::RationalFromBigint).ok_or(
10065                WasmLowerError::Unsupported("rational_from_bigint not imported"),
10066            )?;
10067            local_get(code, reg as u32);
10068            code.push(0x10);
10069            leb_u32(code, from);
10070        }
10071        _ => {
10072            return Err(WasmLowerError::Unsupported(
10073                "rational arithmetic operand must be a Rational, Int, or BigInt",
10074            ))
10075        }
10076    }
10077    Ok(())
10078}
10079
10080/// `dst = lhs <op> rhs` as exact BigInt-backed rational arithmetic (linker mode) — `op` is the
10081/// `logos_rt_rational_*` sink. Operands promote to Rational handles first, so num/den stay exact past i64.
10082fn lower_rational_binop(
10083    code: &mut Vec<u8>,
10084    kinds: &KindTable,
10085    ctx: &Ctx,
10086    dst: u16,
10087    lhs: u16,
10088    rhs: u16,
10089    host: HostFn,
10090) -> R<Flow> {
10091    let op =
10092        (ctx.host_index)(host).ok_or(WasmLowerError::Unsupported("rational op not imported"))?;
10093    push_rational_operand(code, kinds, ctx, lhs)?;
10094    push_rational_operand(code, kinds, ctx, rhs)?;
10095    code.push(0x10);
10096    leb_u32(code, op);
10097    local_set(code, dst as u32);
10098    Ok(Flow::Straight)
10099}
10100
10101/// `dst = <op>(arg)` on a Rational handle (linker mode) — `op` is a unary `logos_rt_rational_*` sink
10102/// (`floor`/`ceil`/`round` returning a BigInt handle, `abs` a Rational handle).
10103fn lower_rational_unary(
10104    code: &mut Vec<u8>,
10105    ctx: &Ctx,
10106    dst: u16,
10107    arg: u16,
10108    host: HostFn,
10109) -> R<Flow> {
10110    let op = (ctx.host_index)(host).ok_or(WasmLowerError::Unsupported(
10111        "rational unary op not imported",
10112    ))?;
10113    local_get(code, arg as u32);
10114    code.push(0x10);
10115    leb_u32(code, op);
10116    local_set(code, dst as u32);
10117    Ok(Flow::Straight)
10118}
10119
10120/// `dst = (lhs == rhs)` (or `!=` when `negate`) on two Uuid handles (linker mode) — `logos_rt_uuid_eq`
10121/// compares the 16 bytes and returns an i32 0/1, extended to the i64 a `Bool` register holds (matching
10122/// [`lower_text_eq`]'s i64-boolean convention).
10123fn lower_uuid_eq(
10124    code: &mut Vec<u8>,
10125    ctx: &Ctx,
10126    dst: u16,
10127    lhs: u16,
10128    rhs: u16,
10129    negate: bool,
10130) -> R<Flow> {
10131    let eq = (ctx.host_index)(HostFn::UuidEq)
10132        .ok_or(WasmLowerError::Unsupported("uuid_eq not imported"))?;
10133    local_get(code, lhs as u32);
10134    local_get(code, rhs as u32);
10135    code.push(0x10);
10136    leb_u32(code, eq); // → i32 0/1
10137    if negate {
10138        code.push(0x45); // i32.eqz → logical NOT
10139    }
10140    code.push(0xAD); // i64.extend_i32_u → the i64 a Bool register holds
10141    local_set(code, dst as u32);
10142    Ok(Flow::Straight)
10143}
10144
10145/// `dst = base <±> span` calendar arithmetic (linker mode): unpack the `Span` i64 (`months` high word,
10146/// `days` low word), negate for subtraction, then call `logos_rt_moment_add_span` (Moment base, i64) or
10147/// `logos_rt_date_add_span` (Date base, i32). `base`/`dst` share the base's width (Moment i64 / Date i32).
10148fn lower_span_add(
10149    code: &mut Vec<u8>,
10150    ctx: &Ctx,
10151    num_regs: u32,
10152    dst: u16,
10153    base: u16,
10154    span: u16,
10155    is_date: bool,
10156    negate: bool,
10157) -> R<Flow> {
10158    let host = if is_date {
10159        HostFn::DateAddSpan
10160    } else {
10161        HostFn::MomentAddSpan
10162    };
10163    let idx = (ctx.host_index)(host).ok_or(WasmLowerError::Unsupported("span add not imported"))?;
10164    let (months, days) = (num_regs + 5, num_regs + 6);
10165    // months = (span >> 32) as i32 (arithmetic — a Span's months can be negative)
10166    local_get(code, span as u32);
10167    code.push(0x42);
10168    leb_i64(code, 32);
10169    code.push(0x87); // i64.shr_s
10170    code.push(0xA7); // i32.wrap_i64
10171    local_set(code, months);
10172    // days = span as i32 (low word)
10173    local_get(code, span as u32);
10174    code.push(0xA7); // i32.wrap_i64
10175    local_set(code, days);
10176    if negate {
10177        for r in [months, days] {
10178            i32_const(code, 0);
10179            local_get(code, r);
10180            code.push(0x6B); // i32.sub → 0 - r
10181            local_set(code, r);
10182        }
10183    }
10184    // dst = host(base, months, days)
10185    local_get(code, base as u32);
10186    local_get(code, months);
10187    local_get(code, days);
10188    code.push(0x10);
10189    leb_u32(code, idx);
10190    local_set(code, dst as u32);
10191    Ok(Flow::Straight)
10192}
10193
10194fn lower_pow_regs(
10195    code: &mut Vec<u8>,
10196    kinds: &KindTable,
10197    ctx: &Ctx,
10198    num_regs: u32,
10199    dst: u16,
10200    base: u16,
10201    exp: u16,
10202) -> R<Flow> {
10203    let (bk, ek) = (kinds.get(base as usize), kinds.get(exp as usize));
10204    match (bk, ek) {
10205        (_, Some(Kind::Float)) => {
10206            push_as_f64(code, base, bk)?;
10207            local_get(code, exp as u32); // exp is already f64
10208            let idx = (ctx.host_index)(HostFn::PowFf)
10209                .ok_or(WasmLowerError::Unsupported("pow_ff not imported"))?;
10210            code.push(0x10);
10211            leb_u32(code, idx);
10212            local_set(code, dst as u32);
10213            Ok(Flow::Straight)
10214        }
10215        (Some(Kind::Float), Some(Kind::Int)) => {
10216            local_get(code, base as u32);
10217            local_get(code, exp as u32);
10218            let idx = (ctx.host_index)(HostFn::PowFi)
10219                .ok_or(WasmLowerError::Unsupported("pow_fi not imported"))?;
10220            code.push(0x10);
10221            leb_u32(code, idx);
10222            local_set(code, dst as u32);
10223            Ok(Flow::Straight)
10224        }
10225        (Some(Kind::Modular), Some(Kind::Int)) if ctx.linked => {
10226            // `pow(m, e)` on a ℤ/nℤ base — modular exponentiation via the linked runtime. Push the
10227            // Modular handle (i32) and the i64 exponent, `call logos_rt_modular_pow` → a Modular handle.
10228            let pow = (ctx.host_index)(HostFn::ModularPow)
10229                .ok_or(WasmLowerError::Unsupported("modular_pow not imported"))?;
10230            local_get(code, base as u32); // i32 Modular handle
10231            local_get(code, exp as u32); // i64 exponent
10232            code.push(0x10);
10233            leb_u32(code, pow);
10234            local_set(code, dst as u32);
10235            Ok(Flow::Straight)
10236        }
10237        (Some(Kind::Int), Some(Kind::Int)) if ctx.linked => {
10238            // LINKER MODE: compute the exact big integer via the real `logicaffeine_base::BigInt`
10239            // runtime — `from_i64(base)` → `pow(handle, exp)` — leaving a BigInt HANDLE in `dst`. No
10240            // overflow, no trap. The handle stays a handle (rendered to a decimal `Text` only at `Show`,
10241            // via `lower_show`), so a downstream `*` keeps multiplying on real BigInts.
10242            let from_i64 = (ctx.host_index)(HostFn::BigintFromI64)
10243                .ok_or(WasmLowerError::Unsupported("bigint_from_i64 not imported"))?;
10244            let pow = (ctx.host_index)(HostFn::BigintPow)
10245                .ok_or(WasmLowerError::Unsupported("bigint_pow not imported"))?;
10246            local_get(code, base as u32); // i64 base
10247            code.push(0x10);
10248            leb_u32(code, from_i64); // -> i32 BigInt handle
10249            local_get(code, exp as u32); // i64 exponent
10250            code.push(0x10);
10251            leb_u32(code, pow); // (handle, exp) -> i32 BigInt handle
10252            local_set(code, dst as u32);
10253            Ok(Flow::Straight)
10254        }
10255        (Some(Kind::Int), Some(Kind::Int)) => {
10256            lower_int_pow(code, num_regs, dst, base, exp);
10257            Ok(Flow::Straight)
10258        }
10259        _ => Err(WasmLowerError::Unsupported("pow of non-numbers")),
10260    }
10261}
10262
10263/// `a // b` — floor division (toward negative infinity). `Int`: `i64.div_s` truncates toward
10264/// zero, so correct by one when the remainder is nonzero AND the operands differ in sign —
10265/// `q - ((r != 0) & ((r ^ b) < 0))`, borrowing one pow i64 scratch (`num_regs+1`) for `r`.
10266/// `i64.div_s`/`rem_s` trap on `/0` and `i64::MIN // -1` (the BigInt-promotion frontier,
10267/// matching `Op::Div`). `Float`: `f64.floor(a / b)`, promoting an Int operand. `Word`: unsigned
10268/// `div_u` (floor == truncation on non-negative). Mirrors `arith::floor_divide`.
10269fn lower_floordiv_regs(
10270    code: &mut Vec<u8>,
10271    kinds: &KindTable,
10272    num_regs: u32,
10273    dst: u16,
10274    lhs: u16,
10275    rhs: u16,
10276) -> R<Flow> {
10277    match kinds.get(dst as usize) {
10278        Some(Kind::Int) => {
10279            if kinds.valtype(lhs as usize) != I64 || kinds.valtype(rhs as usize) != I64 {
10280                return Err(WasmLowerError::Unsupported(
10281                    "integer floor division with a non-integer operand",
10282                ));
10283            }
10284            let s_r = num_regs + 1; // borrow a pow i64 scratch to hold the remainder
10285                                    // s_r = a % b   (rem_s traps on b == 0)
10286            local_get(code, lhs as u32);
10287            local_get(code, rhs as u32);
10288            code.push(0x81); // i64.rem_s
10289            local_set(code, s_r);
10290            // q = a / b     (div_s traps on b == 0 and i64::MIN / -1)
10291            local_get(code, lhs as u32);
10292            local_get(code, rhs as u32);
10293            code.push(0x7F); // i64.div_s
10294                             // corr = (r != 0) & ((r ^ b) < 0)  → 1 when the truncated quotient overshot
10295            local_get(code, s_r);
10296            code.push(0x42);
10297            leb_i64(code, 0); // i64.const 0
10298            code.push(0x52); // i64.ne → i32
10299            local_get(code, s_r);
10300            local_get(code, rhs as u32);
10301            code.push(0x85); // i64.xor
10302            code.push(0x42);
10303            leb_i64(code, 0); // i64.const 0
10304            code.push(0x53); // i64.lt_s → i32
10305            code.push(0x71); // i32.and
10306            code.push(0xAD); // i64.extend_i32_u → i64 corr
10307            code.push(0x7D); // i64.sub → q - corr
10308            local_set(code, dst as u32);
10309        }
10310        Some(Kind::Word32) => arith(code, 0x6E, dst, lhs, rhs), // i32.div_u
10311        Some(Kind::Word64) => arith(code, 0x80, dst, lhs, rhs), // i64.div_u
10312        Some(Kind::Float) => {
10313            push_as_f64(code, lhs, kinds.get(lhs as usize))?;
10314            push_as_f64(code, rhs, kinds.get(rhs as usize))?;
10315            code.push(0xA3); // f64.div
10316            code.push(0x9C); // f64.floor
10317            local_set(code, dst as u32);
10318        }
10319        _ => {
10320            return Err(WasmLowerError::Unsupported(
10321                "floor division on a non-numeric value",
10322            ))
10323        }
10324    }
10325    Ok(Flow::Straight)
10326}
10327
10328/// `base^exp` for two Ints, by exponentiation-by-squaring, using three reserved scratch locals
10329/// (`num_regs+1..=num_regs+3`). Each multiply is overflow-checked (traps → matches the VM's
10330/// promote-to-BigInt contract). A negative exponent traps (the VM yields a Float).
10331fn lower_int_pow(code: &mut Vec<u8>, num_regs: u32, dst: u16, base: u16, exp: u16) {
10332    let result = (num_regs + 1) as u16;
10333    let base_s = (num_regs + 2) as u16;
10334    let exp_s = (num_regs + 3) as u16;
10335    // A product temp distinct from result/base_s — `emit_checked_mul` writes its dst BEFORE
10336    // re-reading lhs for the overflow check, so dst must not alias lhs (else the check sees the
10337    // product and falsely traps).
10338    let tmp = (num_regs + 4) as u16;
10339    // if exp < 0: trap
10340    local_get(code, exp as u32);
10341    code.push(0x42);
10342    leb_i64(code, 0);
10343    code.push(0x53); // i64.lt_s
10344    code.push(0x04);
10345    code.push(0x40); // if
10346    code.push(0x00); // unreachable
10347    code.push(0x0B); // end
10348                     // result = 1; base_s = base; exp_s = exp
10349    code.push(0x42);
10350    leb_i64(code, 1);
10351    local_set(code, result as u32);
10352    local_get(code, base as u32);
10353    local_set(code, base_s as u32);
10354    local_get(code, exp as u32);
10355    local_set(code, exp_s as u32);
10356    // block $exit { loop $loop {
10357    code.push(0x02);
10358    code.push(0x40);
10359    code.push(0x03);
10360    code.push(0x40);
10361    //   if exp_s == 0 → br $exit  (while exp_s != 0)
10362    local_get(code, exp_s as u32);
10363    code.push(0x50); // i64.eqz
10364    code.push(0x0D);
10365    leb_u32(code, 1); // br_if $exit
10366                      //   if (exp_s & 1) != 0: result = result * base_s  (checked)
10367    local_get(code, exp_s as u32);
10368    code.push(0x42);
10369    leb_i64(code, 1);
10370    code.push(0x83); // i64.and
10371    code.push(0xA7); // i32.wrap_i64 (low bit as the i32 condition)
10372    code.push(0x04);
10373    code.push(0x40); // if
10374    emit_checked_mul(code, tmp, result, base_s); // tmp = result * base_s (no aliasing)
10375    local_get(code, tmp as u32);
10376    local_set(code, result as u32); // result = tmp
10377    code.push(0x0B); // end if
10378                     //   exp_s >>= 1
10379    local_get(code, exp_s as u32);
10380    code.push(0x42);
10381    leb_i64(code, 1);
10382    code.push(0x87); // i64.shr_s
10383    local_set(code, exp_s as u32);
10384    //   if exp_s != 0: base_s = base_s * base_s  (checked; skip the unused final square)
10385    local_get(code, exp_s as u32);
10386    code.push(0x50); // i64.eqz
10387    code.push(0x45); // i32.eqz → exp_s != 0
10388    code.push(0x04);
10389    code.push(0x40); // if
10390    emit_checked_mul(code, tmp, base_s, base_s); // tmp = base_s * base_s (no aliasing)
10391    local_get(code, tmp as u32);
10392    local_set(code, base_s as u32); // base_s = tmp
10393    code.push(0x0B); // end if
10394    code.push(0x0C);
10395    leb_u32(code, 0); // br $loop
10396    code.push(0x0B); // end loop
10397    code.push(0x0B); // end block
10398                     // dst = result
10399    local_get(code, result as u32);
10400    local_set(code, dst as u32);
10401}
10402
10403/// A function the emitter writes itself rather than compiling from LOGOS.
10404#[derive(Clone, Copy, PartialEq, Eq, Debug)]
10405enum RuntimeFn {
10406    /// `__logos_alloc(size) -> ptr` — see [`emit_alloc_helper`].
10407    Alloc,
10408    /// `__logos_free(ptr, size)` — see [`emit_free_helper`].
10409    Free,
10410    /// `__logos_heap_allocated() -> bytes` — the GROSS heap: every byte the allocator has claimed
10411    /// from linear memory, live or waiting on a free list. It only grows.
10412    HeapAllocated,
10413    /// `__logos_heap_used() -> bytes` — the NET heap: the gross heap less the blocks sitting on the
10414    /// free lists, which is what the page's values actually occupy.
10415    HeapUsed,
10416    /// `__logos_iter_unwind(base)` — pop and free `Repeat` frames down to `base`; see
10417    /// [`emit_leave_loops`].
10418    IterUnwind,
10419    /// `__logos_text_new(len) -> handle` — a Text block for the HOST to write `len` bytes into,
10420    /// allocated through the same allocator every module-side Text uses. Gives the host a way to
10421    /// put a string on the module's own heap instead of bump-allocating pages of its own above it.
10422    TextNew,
10423    /// `__logos_seq_new(len, handles) -> handle` — a `Seq` of `len` 8-byte slots for the HOST to
10424    /// fill, the list analog of [`RuntimeFn::TextNew`]: the header an ordinary `Seq` has (its class
10425    /// from `handles`, and — on a module that counts holders — a true count of 1 credited to the
10426    /// turn, exactly as a module-built sequence is born), so nothing downstream can tell a list the
10427    /// host built from one the module did.
10428    SeqNew,
10429    /// `__logos_seq_slot(handle, index) -> address` — the 8-byte slot of the 1-based `index` in a
10430    /// sequence (or a tuple: the same header and slots), trapping through `logos_rt_fail_at` with
10431    /// the index out of bounds. Every `item i of xs` and `Set item i of xs to v` is a call to it and
10432    /// the load or store at the element's width. See `emit_seq_slot_helper`.
10433    SeqSlot,
10434    /// `__logos_seq_push_slot(handle) -> address` — a sequence one element longer, its buffer
10435    /// doubled first when full (the old buffer freed), and the address of the new last slot, for
10436    /// a push to store its element at the element's width. See `emit_seq_push_slot_helper`.
10437    SeqPushSlot,
10438    /// `__logos_seq_clone(handle, mode) -> handle` — a fresh sequence with `handle`'s elements
10439    /// (8-byte slots, copied as they are), stamped the class in `mode`'s low byte, and born counted
10440    /// when the module counts holders and the class carries a count; `mode`'s [`CLONE_RETAINS`] and
10441    /// [`CLONE_SHARES`] bits say what the copy's elements gain. The copy of a sequence, a set or a
10442    /// record. See `emit_seq_clone_helper`.
10443    SeqClone,
10444    /// `__logos_seq_own(handle, mode) -> handle` — the copy-on-write of a sequence about to be
10445    /// written: `handle` itself when nothing else holds it (or it is a `SharedMap` replica), else
10446    /// `__logos_seq_clone(handle, mode)`. Every mutation of a sequence or set is a call to it.
10447    SeqOwn,
10448    /// `__logos_text_eq(a, b) -> i32` — byte equality of two Texts. See `emit_text_eq_helper`.
10449    TextEq,
10450    /// `__logos_text_concat(a, b) -> handle` — a fresh Text of `a`'s bytes then `b`'s. See
10451    /// `emit_text_concat_helper`.
10452    TextConcat,
10453    /// `__logos_map_clone(handle) -> handle` — a fresh map holding `handle`'s entries, its class
10454    /// (and a `SharedMap`'s mark) kept. See `emit_map_clone_helper`.
10455    MapClone,
10456    /// `__logos_map_own(handle) -> handle` — the copy-on-write of a map about to be written, as
10457    /// [`RuntimeFn::SeqOwn`] is a sequence's.
10458    MapOwn,
10459    /// `__logos_map_put(map, key, class) -> address` — the entry `key` names, appended (growing the
10460    /// entry buffer) when the map has none, its value slot empty. See `emit_map_put_helper`.
10461    MapPut,
10462    /// `__logos_map_find(map, key, text_key) -> address` — the entry `key` names, or 0. See
10463    /// `emit_map_find_helper`.
10464    MapFind,
10465    /// `__logos_map_at(map, key, text_key) -> address` — the entry `key` names; a key the map does
10466    /// not hold traps, as `item k of m` on an absent key does.
10467    MapAt,
10468    /// `__logos_add_checked(a, b) -> i64` — `a + b`, trapping on signed overflow as the inline check
10469    /// does ([`super::encode::emit_checked_addsub`]). With [`RuntimeFn::SubChecked`] and
10470    /// [`RuntimeFn::MulChecked`], checked Int arithmetic outside a loop is a call.
10471    AddChecked,
10472    /// `__logos_sub_checked(a, b) -> i64` — `a - b`, trapping on signed overflow.
10473    SubChecked,
10474    /// `__logos_mul_checked(a, b) -> i64` — `a * b`, trapping on signed overflow
10475    /// ([`super::encode::emit_checked_mul`]).
10476    MulChecked,
10477    /// `__logos_exact_add(a, b) -> i64` — the sum of two tagged words as a tagged word of its own:
10478    /// inline on two small ones, the host's `exact_add` otherwise. With [`RuntimeFn::ExactSub`] and
10479    /// [`RuntimeFn::ExactMul`], exact Int arithmetic outside a loop is a call
10480    /// ([`exact::emit_ring_helper`]).
10481    ExactAdd,
10482    /// `__logos_exact_sub(a, b) -> i64` — the difference of two tagged words.
10483    ExactSub,
10484    /// `__logos_exact_mul(a, b) -> i64` — the product of two tagged words.
10485    ExactMul,
10486    /// `__logos_exact_add_w(a, w) -> i64` — the sum of the tagged word `a` and the machine word `w`, which the
10487    /// helper tags and gives back itself, so a site beside a machine-word operand holds no tagged word of its
10488    /// own ([`exact::emit_ring_word_helper`]).
10489    ExactAddW,
10490    /// `__logos_exact_sub_w(a, w) -> i64` — `a` less the machine word `w`.
10491    ExactSubW,
10492    /// `__logos_exact_mul_w(a, w) -> i64` — `a` times the machine word `w`.
10493    ExactMulW,
10494    /// `__logos_exact_tag(w) -> i64` — a machine word as a tagged word: shifted beside the tag when it
10495    /// fits, held by the host when not. Outside a loop, tagging is a call.
10496    ExactTag,
10497    /// `__logos_exact_release(t)` — give back the integer a tagged word names when the host holds it.
10498    /// Outside a loop, giving one up is a call.
10499    ExactRelease,
10500    /// `__logos_exact_narrow(t, why) -> i64` — a tagged word's integer as a machine word, failing with the code
10501    /// `why` when it is past one. Outside a loop, narrowing is a call.
10502    ExactNarrow,
10503    /// `__logos_exact_clone(t) -> i64` — a tagged word of its own for `t`: the host's clone of a held integer,
10504    /// a small one as it is. Outside a loop, cloning is a call.
10505    ExactClone,
10506    /// Shared exact collection representation and cell-allocation mechanisms.
10507    ExactSeqPromote,
10508    ExactCell,
10509    ExactCompare,
10510    ExactSeqAt,
10511    ExactSeqStore,
10512    ExactMapPromoteKey,
10513    ExactMapPromoteValue,
10514    /// `__logos_new_header(class) -> handle` — a fresh, empty 16-byte collection header
10515    /// `[len=0][cap=0][data_ptr=0]` stamped `class`, born a true holder count of 1 credited to the
10516    /// turn when that class carries one, as [`emit_alloc`] births every counted block. An empty
10517    /// `Seq`/`Set`/`Map` constructor is a call to it.
10518    NewHeader,
10519    /// `__logos_share(handle)` — one more copy-on-write holder of `handle`: word 12's count (bits
10520    /// 8–31) grows by one, its class byte untouched ([`emit_retain`]'s call form).
10521    Share,
10522    /// `__logos_turn_retain(handle)` — append `handle` (already carrying a true holder count, see
10523    /// [`AllocClass::is_counted`]) to the per-turn retained list, growing it (doubling, like every
10524    /// other buffer in this backend) when full. Called from [`emit_alloc`] for every fresh counted
10525    /// block (the turn is its first, implicit holder) and from a mid-turn release that would
10526    /// otherwise take a count to zero (S8's "a mid-turn drop to 0 re-lists it on the turn").
10527    TurnRetain,
10528    /// `__logos_retain(handle)` — `mem[handle+16] += 1` (a no-op on a null handle). The true-count
10529    /// analogue of [`emit_retain`] (which stays on word 12, COW-only, untouched by S8): called
10530    /// whenever a counted value becomes held by a SECOND real, heap-resident holder (a global, a
10531    /// collection element, a struct field, a closure capture) — never for a register-only borrow
10532    /// (a `Call` argument, an `Index`/`Pop` extraction), matching the plan's "registers borrow".
10533    Retain,
10534    /// `__logos_retain_children(handle)` — a container has just become a further holder of every
10535    /// handle it holds (a copy sharing its source's elements or entries, a literal built from
10536    /// registers): [`RuntimeFn::Retain`] on each handle its class says it holds. One call per site,
10537    /// so a copy or a literal of any length costs the same code. See `emit_retain_children_helper`.
10538    RetainChildren,
10539    /// `__logos_release(handle)` — the MID-TURN release: `mem[handle+16] -= 1`, UNLESS that would
10540    /// reach 0, in which case the count is left alone and `handle` is pushed back onto the turn's
10541    /// retained list instead (deferred to the next safepoint — "nothing is freed mid-turn"). A
10542    /// no-op on a null handle. Called wherever a real holder stops holding a value mid-turn: a
10543    /// `GlobalSet`/`SetIndex`/map-insert overwriting what was there, `RemoveFrom`.
10544    Release,
10545    /// `__logos_safepoint()` — run when the host's own re-entry depth returns to 0 (today called
10546    /// directly by a test/host driver; the runtime.js wiring lands separately). Drains the turn's
10547    /// retained list: each entry's count drops by exactly 1 (the turn's own implicit hold ending);
10548    /// whatever reaches 0 is handed to the free cascade. Nothing is freed anywhere else.
10549    Safepoint,
10550    /// `__logos_free_object(handle)` — the cascade worker: given a handle whose true count JUST
10551    /// reached 0, walk its class-specific children (a `HandleHeader`'s element slots) through
10552    /// [`RuntimeFn::Release`]'s AUTHORITATIVE sibling (an unconditional decrement-and-enqueue, no
10553    /// mid-turn deferral — see `emit_free_object_helper`), free its data buffer(s) and its own
10554    /// 20-byte header, and POISON the freed range. Only ever called from inside
10555    /// [`RuntimeFn::Safepoint`]'s own worklist loop, never mid-turn.
10556    FreeObject,
10557    /// `__logos_heap_census() -> i32` — a CHECK-MODE instrument, not part of a page's normal
10558    /// operation: walks every counted value reachable from the program's own globals, and for each
10559    /// one INDEPENDENTLY recomputes how many of those roots/slots point at it, comparing the
10560    /// recomputed number to the block's own stored true count. Returns 0 when every reachable
10561    /// object's stored count exactly equals its recomputed in-degree, or the address of the first
10562    /// mismatch otherwise. See `emit_heap_census_helper`.
10563    Census,
10564    /// Count one incoming edge, visiting a container's children only on its first visit.
10565    CensusVisit,
10566    /// Register a closure with the host, returning a fresh opaque callback identity.
10567    /// Each registry entry owns one true reference, independently of other registrations.
10568    ClosureRetain,
10569    /// Exported as `__logos_release`: remove the host registration named by its identity,
10570    /// release its closure reference, and return the registry entry's storage to the allocator.
10571    /// Unknown or already-released identities own nothing and have no effect.
10572    ClosureRelease,
10573}
10574
10575impl RuntimeFn {
10576    fn signature(self) -> (Vec<u8>, Vec<u8>) {
10577        match self {
10578            RuntimeFn::Alloc
10579            | RuntimeFn::TextNew
10580            | RuntimeFn::SeqPushSlot
10581            | RuntimeFn::MapClone
10582            | RuntimeFn::MapOwn
10583            | RuntimeFn::ClosureRetain => (vec![I32], vec![I32]),
10584            RuntimeFn::SeqNew
10585            | RuntimeFn::SeqClone
10586            | RuntimeFn::SeqOwn
10587            | RuntimeFn::TextEq
10588            | RuntimeFn::TextConcat => (vec![I32, I32], vec![I32]),
10589            RuntimeFn::SeqSlot => (vec![I32, I64], vec![I32]),
10590            RuntimeFn::MapPut | RuntimeFn::MapFind | RuntimeFn::MapAt => {
10591                (vec![I32, I64, I32], vec![I32])
10592            }
10593            RuntimeFn::AddChecked
10594            | RuntimeFn::SubChecked
10595            | RuntimeFn::MulChecked
10596            | RuntimeFn::ExactAdd
10597            | RuntimeFn::ExactSub
10598            | RuntimeFn::ExactMul
10599            | RuntimeFn::ExactAddW
10600            | RuntimeFn::ExactSubW
10601            | RuntimeFn::ExactMulW => (vec![I64, I64], vec![I64]),
10602            RuntimeFn::ExactTag | RuntimeFn::ExactClone => (vec![I64], vec![I64]),
10603            RuntimeFn::ExactCell => (vec![I64], vec![I32]),
10604            RuntimeFn::ExactCompare => (vec![I64, I64], vec![I32]),
10605            RuntimeFn::ExactSeqAt => (vec![I32, I64], vec![I64]),
10606            RuntimeFn::ExactSeqStore => (vec![I32, I64], vec![]),
10607            RuntimeFn::ExactSeqPromote
10608            | RuntimeFn::ExactMapPromoteKey
10609            | RuntimeFn::ExactMapPromoteValue => (vec![I32], vec![]),
10610            RuntimeFn::ExactRelease => (vec![I64], vec![]),
10611            RuntimeFn::ExactNarrow => (vec![I64, I32], vec![I64]),
10612            RuntimeFn::NewHeader => (vec![I32], vec![I32]),
10613            RuntimeFn::Share => (vec![I32], vec![]),
10614            RuntimeFn::Free => (vec![I32, I32], vec![]),
10615            RuntimeFn::HeapAllocated | RuntimeFn::HeapUsed => (vec![], vec![I32]),
10616            RuntimeFn::IterUnwind => (vec![I32], vec![]),
10617            RuntimeFn::TurnRetain
10618            | RuntimeFn::Retain
10619            | RuntimeFn::RetainChildren
10620            | RuntimeFn::Release
10621            | RuntimeFn::FreeObject
10622            | RuntimeFn::ClosureRelease => (vec![I32], vec![]),
10623            RuntimeFn::Safepoint => (vec![], vec![]),
10624            RuntimeFn::Census => (vec![], vec![I32]),
10625            RuntimeFn::CensusVisit => (vec![I32, I32], vec![]),
10626        }
10627    }
10628
10629    /// The name a host calls this by, or `None` for a function only the module calls.
10630    fn export(self) -> Option<&'static str> {
10631        match self {
10632            RuntimeFn::Alloc
10633            | RuntimeFn::Free
10634            | RuntimeFn::IterUnwind
10635            | RuntimeFn::SeqSlot
10636            | RuntimeFn::SeqPushSlot
10637            | RuntimeFn::SeqClone
10638            | RuntimeFn::SeqOwn
10639            | RuntimeFn::TextEq
10640            | RuntimeFn::TextConcat
10641            | RuntimeFn::MapClone
10642            | RuntimeFn::MapOwn
10643            | RuntimeFn::MapPut
10644            | RuntimeFn::MapFind
10645            | RuntimeFn::MapAt
10646            | RuntimeFn::AddChecked
10647            | RuntimeFn::SubChecked
10648            | RuntimeFn::MulChecked
10649            | RuntimeFn::ExactAdd
10650            | RuntimeFn::ExactSub
10651            | RuntimeFn::ExactMul
10652            | RuntimeFn::ExactAddW
10653            | RuntimeFn::ExactSubW
10654            | RuntimeFn::ExactMulW
10655            | RuntimeFn::ExactTag
10656            | RuntimeFn::ExactRelease
10657            | RuntimeFn::ExactNarrow
10658            | RuntimeFn::ExactClone
10659            | RuntimeFn::ExactSeqPromote
10660            | RuntimeFn::ExactCell
10661            | RuntimeFn::ExactCompare
10662            | RuntimeFn::ExactSeqAt
10663            | RuntimeFn::ExactSeqStore
10664            | RuntimeFn::ExactMapPromoteKey
10665            | RuntimeFn::ExactMapPromoteValue
10666            | RuntimeFn::NewHeader
10667            | RuntimeFn::Share
10668            | RuntimeFn::TurnRetain
10669            | RuntimeFn::Retain
10670            | RuntimeFn::RetainChildren
10671            | RuntimeFn::Release
10672            | RuntimeFn::FreeObject
10673            | RuntimeFn::CensusVisit
10674            | RuntimeFn::ClosureRetain => None,
10675            RuntimeFn::HeapAllocated => Some("__logos_heap_allocated"),
10676            RuntimeFn::HeapUsed => Some("__logos_heap_used"),
10677            RuntimeFn::TextNew => Some("__logos_text_new"),
10678            RuntimeFn::SeqNew => Some("__logos_seq_new"),
10679            RuntimeFn::Safepoint => Some("__logos_safepoint"),
10680            RuntimeFn::Census => Some("__logos_heap_census"),
10681            // `runtime.js`'s `releaseHandle` already calls `inst.exports.__logos_release(h)` when
10682            // the HOST stops holding a closure it registered (a replaced listener, a finished
10683            // fetch, a superseded route handler) — the Wave 6 plan's "the host calls
10684            // `__logos_release(h)` once per dropped handle". It has always guarded on the export
10685            // existing and silently no-opped until this session, since nothing exported it. THIS
10686            // export is closure-specific (see `RuntimeFn::ClosureRelease`'s doc) — a DIFFERENT,
10687            // narrower true-count than the header count `RuntimeFn::Release` (internal only, never
10688            // called by the host) maintains for `Seq`/`Set`.
10689            RuntimeFn::ClosureRelease => Some("__logos_release"),
10690        }
10691    }
10692
10693    fn body(self, env: &RuntimeEnv) -> Vec<u8> {
10694        match self {
10695            RuntimeFn::Alloc => emit_alloc_helper(env.heap_global, env.fail_at),
10696            RuntimeFn::Free => emit_free_helper(),
10697            RuntimeFn::HeapAllocated => emit_heap_allocated_helper(env),
10698            RuntimeFn::HeapUsed => emit_heap_used_helper(env),
10699            RuntimeFn::IterUnwind => emit_iter_unwind_helper(env),
10700            RuntimeFn::TextNew => emit_text_new_helper(env),
10701            RuntimeFn::SeqNew => emit_seq_new_helper(env),
10702            RuntimeFn::SeqSlot => emit_seq_slot_helper(env),
10703            RuntimeFn::SeqPushSlot => emit_seq_push_slot_helper(env),
10704            RuntimeFn::SeqClone => emit_seq_clone_helper(env),
10705            RuntimeFn::SeqOwn => emit_seq_own_helper(env),
10706            RuntimeFn::TextEq => emit_text_eq_helper(),
10707            RuntimeFn::TextConcat => emit_text_concat_helper(env),
10708            RuntimeFn::MapClone => emit_map_clone_helper(env),
10709            RuntimeFn::MapOwn => emit_map_own_helper(env),
10710            RuntimeFn::MapPut => emit_map_put_helper(env),
10711            RuntimeFn::MapFind => emit_map_find_helper(env),
10712            RuntimeFn::MapAt => emit_map_at_helper(env),
10713            RuntimeFn::AddChecked => emit_checked_arith_helper(ArithOp::Add),
10714            RuntimeFn::SubChecked => emit_checked_arith_helper(ArithOp::Sub),
10715            RuntimeFn::MulChecked => emit_checked_arith_helper(ArithOp::Mul),
10716            RuntimeFn::ExactAdd => exact::emit_ring_helper(env, ArithOp::Add),
10717            RuntimeFn::ExactSub => exact::emit_ring_helper(env, ArithOp::Sub),
10718            RuntimeFn::ExactMul => exact::emit_ring_helper(env, ArithOp::Mul),
10719            RuntimeFn::ExactAddW => exact::emit_ring_word_helper(env, ArithOp::Add),
10720            RuntimeFn::ExactSubW => exact::emit_ring_word_helper(env, ArithOp::Sub),
10721            RuntimeFn::ExactMulW => exact::emit_ring_word_helper(env, ArithOp::Mul),
10722            RuntimeFn::ExactTag => exact::emit_tag_helper(env),
10723            RuntimeFn::ExactRelease => exact::emit_release_helper(env),
10724            RuntimeFn::ExactNarrow => exact::emit_narrow_helper(env),
10725            RuntimeFn::ExactClone => exact::emit_clone_helper(env),
10726            RuntimeFn::ExactSeqPromote => exact::emit_seq_promote_helper(env),
10727            RuntimeFn::ExactCell => exact::emit_cell_helper(env),
10728            RuntimeFn::ExactCompare => exact::emit_compare_helper(env),
10729            RuntimeFn::ExactSeqAt => exact::emit_seq_at_helper(env),
10730            RuntimeFn::ExactSeqStore => exact::emit_seq_store_helper(env),
10731            RuntimeFn::ExactMapPromoteKey => exact::emit_map_promote_helper(env, 0),
10732            RuntimeFn::ExactMapPromoteValue => exact::emit_map_promote_helper(env, 8),
10733            RuntimeFn::NewHeader => emit_new_header_helper(env),
10734            RuntimeFn::Share => emit_share_helper(),
10735            RuntimeFn::TurnRetain => emit_turn_retain_helper(env),
10736            RuntimeFn::Retain => emit_true_retain_helper(),
10737            RuntimeFn::RetainChildren => emit_retain_children_helper(env),
10738            RuntimeFn::Release => emit_true_release_helper(env),
10739            RuntimeFn::Safepoint => emit_safepoint_helper(env),
10740            RuntimeFn::FreeObject => emit_free_object_helper(env),
10741            RuntimeFn::Census => emit_heap_census_helper(env),
10742            RuntimeFn::CensusVisit => emit_heap_census_visit_helper(env),
10743            RuntimeFn::ClosureRetain => emit_closure_retain_helper(env),
10744            RuntimeFn::ClosureRelease => emit_closure_release_helper(env),
10745        }
10746    }
10747}
10748
10749/// What a runtime function's body needs that is only known once the program's own bodies are
10750/// lowered.
10751struct RuntimeEnv<'r> {
10752    heap_global: u32,
10753    iter_global: u32,
10754    /// Where the dynamic heap begins: above the free-list table and the interned text.
10755    heap_base: i32,
10756    /// The host import index of `logos_rt_fail_at`, for the allocator's own out-of-memory report.
10757    fail_at: u32,
10758    /// Releases the host value owned by an exact integer cell, when this module uses them.
10759    exact_drop: Option<u32>,
10760    exact_clone: Option<u32>,
10761    exact_cmp: Option<u32>,
10762    /// The host's exact-integer imports the out-of-line exact helpers call, when the module holds
10763    /// integers exact: `exact_box`, `exact_add`, `exact_sub`, `exact_mul`, `exact_narrow`, `exact_clone`.
10764    exact_host: Option<[u32; 6]>,
10765    /// The wasm global index of the turn-retained list's `data_ptr`; `+1` is its `len`, `+2` its
10766    /// `cap` (S8). `None` on a non-interactive module (see [`Runtime::layout`]).
10767    retain_base: Option<u32>,
10768    /// Every user global's kind (by global index), so the census can tell which globals are ROOTS
10769    /// of the counted heap graph — `None`/scalar globals are skipped.
10770    global_kinds: Vec<Option<Kind>>,
10771    callback_base: Option<u32>,
10772    /// Whether the program builds a `SharedMap`, whose copy stays a replica ([`SHARED_MAP_MARK`]).
10773    shared_maps: bool,
10774    runtime: &'r Runtime,
10775}
10776
10777impl RuntimeEnv<'_> {
10778    /// The wasm function index of the runtime function `f` one runtime function's body calls —
10779    /// which makes `f` a function the module carries in full ([`Runtime::index`]).
10780    fn call(&self, f: RuntimeFn) -> u32 {
10781        self.runtime.index(f).unwrap_or_else(|| {
10782            panic!("a runtime body calls {f:?}, which this module's runtime does not lay out")
10783        })
10784    }
10785}
10786
10787/// The runtime functions a module carries, laid out after the closure trampoline in a fixed order
10788/// so every index is known before any body is lowered.
10789struct Runtime {
10790    /// The wasm function index of `fns[0]`.
10791    first: u32,
10792    fns: Vec<RuntimeFn>,
10793    /// The type index of each of `fns`.
10794    types: Vec<u32>,
10795    /// Bit `i` set: something the module emits calls `fns[i]`. A laid-out function nothing calls and
10796    /// no host is handed keeps its index and type but carries an `unreachable` body.
10797    called: std::cell::Cell<u64>,
10798}
10799
10800impl Runtime {
10801    /// Every self-contained heap module carries the allocator. An INTERACTIVE one — a page the host
10802    /// re-enters after `main`, through a callback it registered or a function it enters by name —
10803    /// also exports the heap readings a host measures
10804    /// it by; a program that runs `main` once and ends has no host left to read them. Either one
10805    /// that takes a Text from its host (`host_text`) exports the allocator the host writes it
10806    /// through, `__logos_text_new`; one that takes a sequence from its host (`host_seq`) exports
10807    /// `__logos_seq_new`.
10808    fn layout(
10809        first: u32,
10810        interactive: bool,
10811        host_text: bool,
10812        host_seq: bool,
10813        loops: bool,
10814        exact: bool,
10815        reclaim: Reclaim,
10816        types: &mut TypeTable,
10817    ) -> Runtime {
10818        let mut fns = vec![
10819            RuntimeFn::Alloc,
10820            RuntimeFn::Free,
10821            RuntimeFn::SeqSlot,
10822            RuntimeFn::SeqPushSlot,
10823            RuntimeFn::SeqClone,
10824            RuntimeFn::SeqOwn,
10825            RuntimeFn::TextEq,
10826            RuntimeFn::TextConcat,
10827            RuntimeFn::MapClone,
10828            RuntimeFn::MapOwn,
10829            RuntimeFn::MapPut,
10830            RuntimeFn::MapFind,
10831            RuntimeFn::MapAt,
10832            RuntimeFn::AddChecked,
10833            RuntimeFn::SubChecked,
10834            RuntimeFn::MulChecked,
10835            RuntimeFn::NewHeader,
10836            RuntimeFn::Share,
10837        ];
10838        if !interactive && host_text {
10839            fns.push(RuntimeFn::TextNew);
10840        }
10841        if interactive {
10842            fns.extend([
10843                RuntimeFn::HeapAllocated,
10844                RuntimeFn::HeapUsed,
10845                RuntimeFn::TextNew,
10846            ]);
10847        }
10848        if reclaim != Reclaim::Off {
10849            fns.extend([
10850                RuntimeFn::TurnRetain,
10851                RuntimeFn::Retain,
10852                RuntimeFn::RetainChildren,
10853                RuntimeFn::Release,
10854                RuntimeFn::Safepoint,
10855                RuntimeFn::FreeObject,
10856                RuntimeFn::ClosureRetain,
10857                RuntimeFn::ClosureRelease,
10858            ]);
10859        }
10860        if reclaim == Reclaim::Checked {
10861            fns.extend([RuntimeFn::Census, RuntimeFn::CensusVisit]);
10862        }
10863        if host_seq {
10864            fns.push(RuntimeFn::SeqNew);
10865        }
10866        if loops {
10867            fns.push(RuntimeFn::IterUnwind);
10868        }
10869        if exact {
10870            fns.extend([
10871                RuntimeFn::ExactAdd,
10872                RuntimeFn::ExactSub,
10873                RuntimeFn::ExactMul,
10874                RuntimeFn::ExactAddW,
10875                RuntimeFn::ExactSubW,
10876                RuntimeFn::ExactMulW,
10877                RuntimeFn::ExactTag,
10878                RuntimeFn::ExactRelease,
10879                RuntimeFn::ExactNarrow,
10880                RuntimeFn::ExactClone,
10881                RuntimeFn::ExactSeqPromote,
10882                RuntimeFn::ExactCell,
10883                RuntimeFn::ExactCompare,
10884                RuntimeFn::ExactSeqAt,
10885                RuntimeFn::ExactSeqStore,
10886                RuntimeFn::ExactMapPromoteKey,
10887                RuntimeFn::ExactMapPromoteValue,
10888            ]);
10889        }
10890        let types = fns
10891            .iter()
10892            .map(|f| {
10893                let (p, r) = f.signature();
10894                types.intern(p, r)
10895            })
10896            .collect();
10897        Runtime {
10898            first,
10899            fns,
10900            types,
10901            called: std::cell::Cell::new(0),
10902        }
10903    }
10904
10905    /// The wasm function index of `f`, for a call to it: asking marks `f` called, so the module
10906    /// carries its body.
10907    fn index(&self, f: RuntimeFn) -> Option<u32> {
10908        let i = self.fns.iter().position(|x| *x == f)?;
10909        self.called.set(self.called.get() | 1 << i);
10910        Some(self.first + i as u32)
10911    }
10912
10913    /// Every laid-out function's body, in layout order: in full for one a host is handed or
10914    /// something the module emits calls — its callers' bodies included, until no body calls one
10915    /// more — and `unreachable` for the rest, which nothing reaches.
10916    fn bodies(&self, env: &RuntimeEnv<'_>) -> Vec<Vec<u8>> {
10917        let mut bodies: Vec<Option<Vec<u8>>> = vec![None; self.fns.len()];
10918        loop {
10919            let mut grew = false;
10920            for (i, f) in self.fns.iter().enumerate() {
10921                if bodies[i].is_none()
10922                    && (f.export().is_some() || self.called.get() & (1 << i) != 0)
10923                {
10924                    bodies[i] = Some(f.body(env));
10925                    grew = true;
10926                }
10927            }
10928            if !grew {
10929                break;
10930            }
10931        }
10932        bodies
10933            .into_iter()
10934            .map(|b| b.unwrap_or_else(|| vec![0x00, 0x00, 0x0B]))
10935            .collect()
10936    }
10937}
10938
10939/// `__logos_heap_allocated() -> i32`: the bump pointer's distance from the heap base.
10940fn emit_heap_allocated_helper(env: &RuntimeEnv) -> Vec<u8> {
10941    let mut c = vec![0x00]; // no locals
10942    global_get(&mut c, env.heap_global);
10943    i32_const(&mut c, env.heap_base);
10944    c.push(0x6B); // i32.sub
10945    c.push(0x0B);
10946    c
10947}
10948
10949/// `__logos_heap_used() -> i32`: the gross heap less every block on a free list. Walks the lists,
10950/// so it costs nothing on the allocation path — it is a reading, not a counter.
10951fn emit_heap_used_helper(env: &RuntimeEnv) -> Vec<u8> {
10952    let mut c = Vec::new();
10953    // locals: 0 = class, 1 = block, 2 = used
10954    c.push(0x01);
10955    leb_u32(&mut c, 3);
10956    c.push(I32);
10957    global_get(&mut c, env.heap_global);
10958    i32_const(&mut c, env.heap_base);
10959    c.push(0x6B);
10960    local_set(&mut c, 2);
10961    c.push(0x02);
10962    c.push(0x40); // block $classes_done
10963    c.push(0x03);
10964    c.push(0x40); // loop $classes
10965    local_get(&mut c, 0);
10966    i32_const(&mut c, FREE_CLASSES + POWER_CLASSES);
10967    c.push(0x4E); // i32.ge_s
10968    c.push(0x0D);
10969    leb_u32(&mut c, 1); // br_if $classes_done
10970                        // block = table[class]
10971    local_get(&mut c, 0);
10972    i32_const(&mut c, 4);
10973    c.push(0x6C);
10974    i32_load(&mut c, FREE_TABLE_BASE as u32);
10975    local_set(&mut c, 1);
10976    c.push(0x02);
10977    c.push(0x40); // block $list_done
10978    c.push(0x03);
10979    c.push(0x40); // loop $list
10980    local_get(&mut c, 1);
10981    c.push(0x45); // i32.eqz
10982    c.push(0x0D);
10983    leb_u32(&mut c, 1); // br_if $list_done
10984                        // used -= this class's block size: the exact tier's is (class+1)*8; the power tier's
10985                        // (class >= FREE_CLASSES) is 2^(POWER_MIN + class - FREE_CLASSES).
10986    local_get(&mut c, 0);
10987    i32_const(&mut c, FREE_CLASSES);
10988    c.push(0x49); // i32.lt_u
10989    c.push(0x04);
10990    c.push(0x40); // if
10991    {
10992        local_get(&mut c, 2);
10993        local_get(&mut c, 0);
10994        i32_const(&mut c, 1);
10995        c.push(0x6A);
10996        i32_const(&mut c, 8);
10997        c.push(0x6C);
10998        c.push(0x6B);
10999        local_set(&mut c, 2);
11000    }
11001    c.push(0x05); // else
11002    {
11003        local_get(&mut c, 2);
11004        i32_const(&mut c, 1);
11005        i32_const(&mut c, POWER_MIN);
11006        local_get(&mut c, 0);
11007        i32_const(&mut c, FREE_CLASSES);
11008        c.push(0x6B); // class - FREE_CLASSES
11009        c.push(0x6A); // POWER_MIN + (class - FREE_CLASSES)
11010        c.push(0x74); // i32.shl → 1 << exponent
11011        c.push(0x6B);
11012        local_set(&mut c, 2);
11013    }
11014    c.push(0x0B); // end if
11015    local_get(&mut c, 1);
11016    i32_load(&mut c, 0); // next
11017    local_set(&mut c, 1);
11018    c.push(0x0C);
11019    leb_u32(&mut c, 0); // br $list
11020    c.push(0x0B);
11021    c.push(0x0B);
11022    local_get(&mut c, 0);
11023    i32_const(&mut c, 1);
11024    c.push(0x6A);
11025    local_set(&mut c, 0);
11026    c.push(0x0C);
11027    leb_u32(&mut c, 0); // br $classes
11028    c.push(0x0B);
11029    c.push(0x0B);
11030    local_get(&mut c, 2);
11031    c.push(0x0B);
11032    c
11033}
11034
11035/// `__logos_alloc(size: i32) -> i32` — the self-contained allocator, emitted ONCE and called from
11036/// every allocation site: a call is four bytes where the free-list check inline would be forty.
11037///
11038/// Take the head of this size's free list when there is one; otherwise bump. Up to `FREE_CLASSES`
11039/// units the class IS `u - 1` — exact, so nothing is rounded up. Above that, the class is the
11040/// smallest power of two at or above the request (`2^(32 - clz(size - 1))`, the usual round-up-to-
11041/// power-of-two identity); a request past the last power class still bumps, sized to its own exact
11042/// rounded need, but is never reclaimed — the same as any size ever was before this tier existed.
11043fn emit_alloc_helper(heap_global: u32, fail_at: u32) -> Vec<u8> {
11044    let mut c = Vec::new();
11045    // locals: 1 = u, 2 = slot address, 3 = head, 4 = result, 5 = this block's class size in bytes,
11046    // 6 = whether a free list exists for this size at all (0/1), 7 = new_top (the bump path's
11047    // candidate `__heap_ptr`), 8 = memory's current size in PAGES, 9 = pages needed to fit `new_top`
11048    c.push(0x01); // one local group
11049    leb_u32(&mut c, 9);
11050    c.push(I32);
11051
11052    // A request for nothing (an empty list's or Text's buffer) is answered with the null block: no
11053    // byte of it is ever read or written, and `__logos_free` frees nothing at null. A zero-sized block
11054    // handed out at the bump pointer would be the very address the next request is handed.
11055    local_get(&mut c, 0);
11056    c.push(0x45); // i32.eqz
11057    c.push(0x04);
11058    c.push(0x40);
11059    {
11060        i32_const(&mut c, 0);
11061        c.push(0x0F); // return
11062    }
11063    c.push(0x0B);
11064
11065    // u = (size + 7) >> 3
11066    local_get(&mut c, 0);
11067    i32_const(&mut c, 7);
11068    c.push(0x6A); // i32.add
11069    i32_const(&mut c, 3);
11070    c.push(0x76); // i32.shr_u
11071    local_set(&mut c, 1);
11072
11073    i32_const(&mut c, 0);
11074    local_set(&mut c, 4); // result = 0 (nothing taken from a list yet)
11075
11076    local_get(&mut c, 1);
11077    i32_const(&mut c, FREE_CLASSES);
11078    c.push(0x4D); // i32.le_u
11079    c.push(0x04);
11080    c.push(0x40); // if (exact tier)
11081    {
11082        // slot = FREE_TABLE_BASE + (u - 1) * 4; class size = u * 8; a list always exists here
11083        local_get(&mut c, 1);
11084        i32_const(&mut c, 1);
11085        c.push(0x6B); // i32.sub
11086        i32_const(&mut c, 4);
11087        c.push(0x6C); // i32.mul
11088        i32_const(&mut c, FREE_TABLE_BASE);
11089        c.push(0x6A); // i32.add
11090        local_set(&mut c, 2);
11091        local_get(&mut c, 1);
11092        i32_const(&mut c, 8);
11093        c.push(0x6C);
11094        local_set(&mut c, 5);
11095        i32_const(&mut c, 1);
11096        local_set(&mut c, 6);
11097    }
11098    c.push(0x05); // else (power-of-two tier)
11099    {
11100        // power_idx = (32 - clz(size - 1)) - POWER_MIN, reusing local 1 (`u` is not needed again)
11101        i32_const(&mut c, 32 - POWER_MIN);
11102        local_get(&mut c, 0);
11103        i32_const(&mut c, 1);
11104        c.push(0x6B); // size - 1
11105        c.push(0x67); // i32.clz
11106        c.push(0x6B); // (32 - POWER_MIN) - clz(size - 1) = power_idx
11107        local_set(&mut c, 1);
11108        local_get(&mut c, 1);
11109        i32_const(&mut c, POWER_CLASSES);
11110        c.push(0x49); // i32.lt_u → power_idx < POWER_CLASSES
11111        local_set(&mut c, 6); // has_class
11112        local_get(&mut c, 6);
11113        c.push(0x04);
11114        c.push(0x40); // if (has a class)
11115        {
11116            local_get(&mut c, 1);
11117            i32_const(&mut c, FREE_CLASSES);
11118            c.push(0x6A);
11119            i32_const(&mut c, 4);
11120            c.push(0x6C);
11121            i32_const(&mut c, FREE_TABLE_BASE);
11122            c.push(0x6A);
11123            local_set(&mut c, 2); // slot
11124                                  // class size = 1 << (POWER_MIN + power_idx)
11125            i32_const(&mut c, 1);
11126            i32_const(&mut c, POWER_MIN);
11127            local_get(&mut c, 1);
11128            c.push(0x6A);
11129            c.push(0x74); // i32.shl
11130            local_set(&mut c, 5);
11131        }
11132        c.push(0x05); // else — past the last power class: bump the exact rounded size, no list
11133        {
11134            local_get(&mut c, 0);
11135            i32_const(&mut c, 7);
11136            c.push(0x6A);
11137            i32_const(&mut c, -8);
11138            c.push(0x71);
11139            local_set(&mut c, 5);
11140        }
11141        c.push(0x0B); // end if
11142    }
11143    c.push(0x0B); // end if/else
11144
11145    local_get(&mut c, 6);
11146    c.push(0x04);
11147    c.push(0x40); // if (has_class)
11148    {
11149        local_get(&mut c, 2);
11150        i32_load(&mut c, 0);
11151        local_tee(&mut c, 3); // head
11152        c.push(0x04);
11153        c.push(0x40); // if head != 0
11154        {
11155            // table[slot] = *head  — the next free block, kept in the block's own first word
11156            local_get(&mut c, 2);
11157            local_get(&mut c, 3);
11158            i32_load(&mut c, 0);
11159            i32_store(&mut c, 0);
11160            local_get(&mut c, 3);
11161            local_set(&mut c, 4);
11162        }
11163        c.push(0x0B); // end if
11164    }
11165    c.push(0x0B); // end if
11166
11167    // Nothing reusable: bump by this block's class size — growing linear memory first when the bump
11168    // would land past what is currently mapped, so a page's heap is bounded only by what the host
11169    // (or, under `StoreLimits`, the embedder) is willing to give it, not by a fixed slab size.
11170    local_get(&mut c, 4);
11171    c.push(0x45); // i32.eqz
11172    c.push(0x04);
11173    c.push(0x40); // if
11174    {
11175        global_get(&mut c, heap_global);
11176        i32_const(&mut c, 7);
11177        c.push(0x6A);
11178        i32_const(&mut c, -8);
11179        c.push(0x71); // i32.and → aligned p
11180        local_tee(&mut c, 4);
11181        local_get(&mut c, 5);
11182        c.push(0x6A); // p + class size
11183        local_set(&mut c, 7); // new_top
11184
11185        // need_grow = (cur_pages * 65536) < new_top
11186        c.push(0x3F); // memory.size
11187        c.push(0x00); // memory index 0
11188        local_tee(&mut c, 8); // cur_pages
11189        i32_const(&mut c, 16);
11190        c.push(0x74); // i32.shl → cur_bytes
11191        local_get(&mut c, 7); // new_top
11192        c.push(0x49); // i32.lt_u
11193        c.push(0x04);
11194        c.push(0x40); // if (need_grow)
11195        {
11196            // pages_needed = ceil((new_top - cur_bytes) / 65536)
11197            local_get(&mut c, 7);
11198            local_get(&mut c, 8);
11199            i32_const(&mut c, 16);
11200            c.push(0x74); // i32.shl → cur_bytes (recomputed; cur_pages is still valid)
11201            c.push(0x6B); // i32.sub → new_top - cur_bytes
11202            i32_const(&mut c, 65535);
11203            c.push(0x6A);
11204            i32_const(&mut c, 16);
11205            c.push(0x76); // i32.shr_u
11206            local_set(&mut c, 9); // pages_needed
11207
11208            // grow_by = max(pages_needed, cur_pages) — never less than doubling, so a run of small
11209            // allocations amortizes to O(1) `memory.grow` calls rather than one per block.
11210            local_get(&mut c, 9);
11211            local_get(&mut c, 8);
11212            c.push(0x49); // i32.lt_u → pages_needed < cur_pages
11213            c.push(0x04);
11214            c.push(0x40); // if
11215            {
11216                local_get(&mut c, 8);
11217                local_set(&mut c, 9); // grow_by = cur_pages
11218            }
11219            c.push(0x0B); // end if (local 9 already holds pages_needed otherwise)
11220
11221            local_get(&mut c, 9);
11222            c.push(0x40); // memory.grow
11223            c.push(0x00);
11224            i32_const(&mut c, -1);
11225            c.push(0x46); // i32.eq — the host refused to grow
11226            c.push(0x04);
11227            c.push(0x40); // if
11228            {
11229                i32_const(
11230                    &mut c,
11231                    crate::semantics::failcode::FailCode::OutOfMemory.code(),
11232                );
11233                c.push(0x42); // i64.const 0 (the value this code ignores)
11234                leb_i64(&mut c, 0);
11235                c.push(0x10); // call logos_rt_fail_at(code, value)
11236                leb_u32(&mut c, fail_at);
11237                c.push(0x00); // unreachable
11238            }
11239            c.push(0x0B); // end if
11240        }
11241        c.push(0x0B); // end if (need_grow)
11242
11243        local_get(&mut c, 7);
11244        global_set(&mut c, heap_global);
11245    }
11246    c.push(0x0B); // end if
11247
11248    local_get(&mut c, 4);
11249    c.push(0x0B); // end function
11250    c
11251}
11252
11253/// `__logos_seq_new(len: i32, handles: i32) -> i32` — a `Seq` handle over `len` zeroed 8-byte slots
11254/// for the HOST to fill: `len` scalars (`handles == 0`, a `ScalarHeader`) or `len` handles in each
11255/// slot's low word (`handles != 0`, a `HandleHeader`). Built the way [`emit_alloc`] builds every
11256/// module-side sequence — the class byte at word 12, and, where the module counts holders, a
11257/// 20-byte header with a true count of 1 credited to the turn — so the host's list is an ordinary
11258/// value the moment it is handed over.
11259fn emit_seq_new_helper(env: &RuntimeEnv) -> Vec<u8> {
11260    let mut c = Vec::new();
11261    // locals: 2 = data, 3 = hdr, 4 = i
11262    c.push(0x01);
11263    leb_u32(&mut c, 3);
11264    c.push(I32);
11265
11266    local_get(&mut c, 0);
11267    i32_const(&mut c, 8);
11268    c.push(0x6C); // i32.mul — 8-byte slots
11269    c.push(0x10); // call __logos_alloc(len * 8)
11270    leb_u32(&mut c, env.call(RuntimeFn::Alloc));
11271    local_set(&mut c, 2);
11272
11273    // Zero the slots: a reused free-list block carries whatever it held before.
11274    i32_const(&mut c, 0);
11275    local_set(&mut c, 4);
11276    c.push(0x02);
11277    c.push(0x40); // block
11278    c.push(0x03);
11279    c.push(0x40); // loop
11280    local_get(&mut c, 4);
11281    local_get(&mut c, 0);
11282    c.push(0x4E); // i32.ge_s
11283    c.push(0x0D);
11284    leb_u32(&mut c, 1); // br_if block
11285    local_get(&mut c, 2);
11286    local_get(&mut c, 4);
11287    i32_const(&mut c, 8);
11288    c.push(0x6C);
11289    c.push(0x6A); // data + i*8
11290    c.push(0x42);
11291    leb_i64(&mut c, 0);
11292    i64_store(&mut c, 0);
11293    local_get(&mut c, 4);
11294    i32_const(&mut c, 1);
11295    c.push(0x6A);
11296    local_set(&mut c, 4);
11297    c.push(0x0C);
11298    leb_u32(&mut c, 0); // br loop
11299    c.push(0x0B); // end loop
11300    c.push(0x0B); // end block
11301
11302    let counted = env.retain_base.is_some();
11303    i32_const(&mut c, if counted { 20 } else { 16 });
11304    c.push(0x10); // call __logos_alloc(header)
11305    leb_u32(&mut c, env.call(RuntimeFn::Alloc));
11306    local_set(&mut c, 3);
11307
11308    local_get(&mut c, 3);
11309    local_get(&mut c, 0);
11310    i32_store(&mut c, 0); // header.len = len
11311    local_get(&mut c, 3);
11312    local_get(&mut c, 0);
11313    i32_store(&mut c, 4); // header.cap = len
11314    local_get(&mut c, 3);
11315    local_get(&mut c, 2);
11316    i32_store(&mut c, 8); // header.data_ptr = data
11317    local_get(&mut c, 3);
11318    i32_const(&mut c, AllocClass::HandleHeader.code() as i32);
11319    i32_const(&mut c, AllocClass::ScalarHeader.code() as i32);
11320    local_get(&mut c, 1);
11321    c.push(0x1B); // select — the class byte from `handles`
11322    i32_store(&mut c, 12);
11323    if counted {
11324        local_get(&mut c, 3);
11325        i32_const(&mut c, 1);
11326        i32_store(&mut c, 16); // a true count of 1, held by the turn
11327        local_get(&mut c, 3);
11328        c.push(0x10); // call __logos_turn_retain(hdr)
11329        leb_u32(&mut c, env.call(RuntimeFn::TurnRetain));
11330    }
11331
11332    local_get(&mut c, 3); // return hdr
11333    c.push(0x0B); // end function
11334    c
11335}
11336
11337/// `__logos_seq_slot(hdr: i32, index: i64) -> i32` — the address of the 1-based `index`'s 8-byte
11338/// slot, `data_ptr + (index - 1) * 8`, after the bounds check: an index below 1 or past `len`
11339/// reports `IndexOutOfBounds` with the index through `logos_rt_fail_at` (the host renders the
11340/// reference tier's sentence from the code and the value) and traps.
11341fn emit_seq_slot_helper(env: &RuntimeEnv) -> Vec<u8> {
11342    let mut c = vec![0x00]; // no locals
11343    local_get(&mut c, 1);
11344    c.push(0x42);
11345    leb_i64(&mut c, 1);
11346    c.push(0x53); // i64.lt_s → index < 1
11347    local_get(&mut c, 1);
11348    local_get(&mut c, 0);
11349    i32_load(&mut c, 0);
11350    c.push(0xAD); // i64.extend_i32_u → len
11351    c.push(0x55); // i64.gt_s → index > len
11352    c.push(0x72); // i32.or
11353    c.push(0x04);
11354    c.push(0x40);
11355    {
11356        i32_const(
11357            &mut c,
11358            crate::semantics::failcode::FailCode::IndexOutOfBounds.code(),
11359        );
11360        local_get(&mut c, 1);
11361        c.push(0x10);
11362        leb_u32(&mut c, env.fail_at);
11363        c.push(0x00); // unreachable
11364    }
11365    c.push(0x0B);
11366    local_get(&mut c, 0);
11367    i32_load(&mut c, 8); // data_ptr
11368    local_get(&mut c, 1);
11369    c.push(0x42);
11370    leb_i64(&mut c, 1);
11371    c.push(0x7D); // i64.sub
11372    c.push(0xA7); // i32.wrap_i64
11373    i32_const(&mut c, 8);
11374    c.push(0x6C);
11375    c.push(0x6A);
11376    c.push(0x0B); // end function
11377    c
11378}
11379
11380/// `__logos_seq_push_slot(hdr: i32) -> i32` — the sequence one element longer, and the address of
11381/// its new last slot. AMORTIZED growth: when `len` has reached `cap` the buffer doubles (4 slots
11382/// from none), the live slots are copied across and the old buffer goes back to the allocator —
11383/// dead by construction, since a data buffer belongs to exactly one header and a shallow copy of
11384/// the sequence shares the header, not the buffer — so n pushes cost O(n) work, not O(n²).
11385fn emit_seq_push_slot_helper(env: &RuntimeEnv) -> Vec<u8> {
11386    let mut c = Vec::new();
11387    // locals: 1 = len, 2 = cap, 3 = the new buffer, 4 = the new cap
11388    c.push(0x01);
11389    leb_u32(&mut c, 4);
11390    c.push(I32);
11391    local_get(&mut c, 0);
11392    i32_load(&mut c, 0);
11393    local_tee(&mut c, 1);
11394    local_get(&mut c, 0);
11395    i32_load(&mut c, 4);
11396    local_tee(&mut c, 2);
11397    c.push(0x4E); // i32.ge_s → full
11398    c.push(0x04);
11399    c.push(0x40);
11400    {
11401        i32_const(&mut c, 4);
11402        local_get(&mut c, 2);
11403        i32_const(&mut c, 2);
11404        c.push(0x6C);
11405        local_get(&mut c, 2);
11406        c.push(0x45); // i32.eqz
11407        c.push(0x1B); // select → cap == 0 ? 4 : cap * 2
11408        local_tee(&mut c, 4);
11409        i32_const(&mut c, 8);
11410        c.push(0x6C);
11411        c.push(0x10);
11412        leb_u32(&mut c, env.call(RuntimeFn::Alloc));
11413        local_tee(&mut c, 3);
11414        local_get(&mut c, 0);
11415        i32_load(&mut c, 8);
11416        local_get(&mut c, 1);
11417        i32_const(&mut c, 8);
11418        c.push(0x6C);
11419        memory_copy(&mut c); // every live slot
11420        local_get(&mut c, 0);
11421        i32_load(&mut c, 8);
11422        local_get(&mut c, 2);
11423        i32_const(&mut c, 8);
11424        c.push(0x6C);
11425        c.push(0x10); // call __logos_free(old data_ptr, cap * 8) — null frees nothing
11426        leb_u32(&mut c, env.call(RuntimeFn::Free));
11427        local_get(&mut c, 0);
11428        local_get(&mut c, 3);
11429        i32_store(&mut c, 8);
11430        local_get(&mut c, 0);
11431        local_get(&mut c, 4);
11432        i32_store(&mut c, 4);
11433    }
11434    c.push(0x0B);
11435    local_get(&mut c, 0);
11436    local_get(&mut c, 1);
11437    i32_const(&mut c, 1);
11438    c.push(0x6A);
11439    i32_store(&mut c, 0); // len + 1
11440    local_get(&mut c, 0);
11441    i32_load(&mut c, 8);
11442    local_get(&mut c, 1);
11443    i32_const(&mut c, 8);
11444    c.push(0x6C);
11445    c.push(0x6A); // data_ptr + len * 8
11446    c.push(0x0B); // end function
11447    c
11448}
11449
11450/// `__logos_seq_clone` `mode` bit: each element of the copy gains the copy as a holder of its true
11451/// count (`__logos_retain_children`, on a module that counts holders).
11452const CLONE_RETAINS: i32 = 0x100;
11453/// `__logos_seq_clone` `mode` bit: each element of the copy gains a copy-on-write hold (word 12), so
11454/// a write to a record or collection through either list copies it first.
11455const CLONE_SHARES: i32 = 0x200;
11456
11457/// `__logos_seq_clone(src: i32, mode: i32) -> i32` — a fresh, independent sequence (or set, or
11458/// record: the same `[len][cap][data_ptr][word 12]` header over 8-byte slots) holding `src`'s slots
11459/// as they are, `len` = `cap` = `src`'s `len`, its header stamped the class in `mode`'s low byte —
11460/// and, on a module that counts holders, born with a true count of 1 credited to the turn when that
11461/// class carries one, as [`emit_alloc`] births every counted block. The copy's elements gain what
11462/// `mode` says: a true count ([`CLONE_RETAINS`]), a copy-on-write hold ([`CLONE_SHARES`]); a deep
11463/// copy of each is the caller's.
11464fn emit_seq_clone_helper(env: &RuntimeEnv) -> Vec<u8> {
11465    let mut c = Vec::new();
11466    // locals: 2 = hdr, 3 = data, 4 = i, 5 = len, 6 = counted (0/1)
11467    c.push(0x01);
11468    leb_u32(&mut c, 5);
11469    c.push(I32);
11470    let counting = env.retain_base.is_some();
11471    // A tagged integer buffer keeps its actual storage class across a copy.
11472    local_get(&mut c, 0);
11473    i32_load(&mut c, 12);
11474    i32_const(&mut c, 0xff);
11475    c.push(0x71);
11476    i32_const(&mut c, AllocClass::ExactIntegerHeader.code() as i32);
11477    c.extend([0x46, 0x04, 0x40]);
11478    local_get(&mut c, 1);
11479    i32_const(&mut c, !0xff);
11480    c.push(0x71);
11481    i32_const(&mut c, AllocClass::ExactIntegerHeader.code() as i32);
11482    c.push(0x72);
11483    local_set(&mut c, 1);
11484    c.push(0x0b);
11485    if counting {
11486        local_get(&mut c, 1);
11487        emit_class_is_counted(&mut c, 4);
11488        local_set(&mut c, 6);
11489    }
11490    i32_const(&mut c, 16);
11491    if counting {
11492        local_get(&mut c, 6);
11493        i32_const(&mut c, 2);
11494        c.push(0x74); // i32.shl → 4 bytes more for the count word
11495        c.push(0x6A);
11496    }
11497    c.push(0x10);
11498    leb_u32(&mut c, env.call(RuntimeFn::Alloc));
11499    local_set(&mut c, 2);
11500    local_get(&mut c, 2);
11501    local_get(&mut c, 1);
11502    i32_const(&mut c, 0xFF);
11503    c.push(0x71);
11504    i32_store(&mut c, 12); // the class byte; no copy-on-write hold yet
11505    if counting {
11506        local_get(&mut c, 6);
11507        c.push(0x04);
11508        c.push(0x40);
11509        {
11510            local_get(&mut c, 2);
11511            i32_const(&mut c, 1);
11512            i32_store(&mut c, 16);
11513            local_get(&mut c, 2);
11514            c.push(0x10);
11515            leb_u32(&mut c, env.call(RuntimeFn::TurnRetain));
11516        }
11517        c.push(0x0B);
11518    }
11519    local_get(&mut c, 0);
11520    i32_load(&mut c, 0);
11521    local_tee(&mut c, 5);
11522    if counting {
11523        // Records retain their field-kind bytes in addition to their eight-byte values.
11524        i32_const(&mut c, 9);
11525        i32_const(&mut c, 8);
11526        local_get(&mut c, 1);
11527        i32_const(&mut c, 0xFF);
11528        c.push(0x71);
11529        i32_const(&mut c, i32::from(AllocClass::RecordHeader.code()));
11530        c.push(0x46);
11531        c.push(0x1B);
11532    } else {
11533        i32_const(&mut c, 8);
11534    }
11535    c.push(0x6C);
11536    c.push(0x10);
11537    leb_u32(&mut c, env.call(RuntimeFn::Alloc));
11538    local_tee(&mut c, 3);
11539    local_get(&mut c, 0);
11540    i32_load(&mut c, 8);
11541    local_get(&mut c, 5);
11542    if counting {
11543        // Records retain their field-kind bytes in addition to their eight-byte values.
11544        i32_const(&mut c, 9);
11545        i32_const(&mut c, 8);
11546        local_get(&mut c, 1);
11547        i32_const(&mut c, 0xFF);
11548        c.push(0x71);
11549        i32_const(&mut c, i32::from(AllocClass::RecordHeader.code()));
11550        c.push(0x46);
11551        c.push(0x1B);
11552    } else {
11553        i32_const(&mut c, 8);
11554    }
11555    c.push(0x6C);
11556    memory_copy(&mut c);
11557    for off in [0u32, 4] {
11558        local_get(&mut c, 2);
11559        local_get(&mut c, 5);
11560        i32_store(&mut c, off);
11561    }
11562    local_get(&mut c, 2);
11563    local_get(&mut c, 3);
11564    i32_store(&mut c, 8);
11565    if counting {
11566        local_get(&mut c, 1);
11567        i32_const(&mut c, CLONE_RETAINS);
11568        c.push(0x71);
11569        c.push(0x04);
11570        c.push(0x40);
11571        local_get(&mut c, 2);
11572        c.push(0x10);
11573        leb_u32(&mut c, env.call(RuntimeFn::RetainChildren));
11574        c.push(0x0B);
11575    }
11576    local_get(&mut c, 1);
11577    i32_const(&mut c, CLONE_SHARES);
11578    c.push(0x71);
11579    c.push(0x04);
11580    c.push(0x40);
11581    emit_cow_retain_each_element(&mut c, 2, 4);
11582    c.push(0x0B);
11583    if let Some(clone) = env.exact_clone {
11584        emit_exact_buffer_holds(&mut c, 2, 4, 6, clone, true);
11585    }
11586    local_get(&mut c, 2);
11587    c.push(0x0B); // end function
11588    c
11589}
11590
11591/// `__logos_add_checked` / `__logos_sub_checked` / `__logos_mul_checked(a: i64, b: i64) -> i64` — the
11592/// Int result, or a trap on signed overflow: the very check a site inlines inside a loop
11593/// ([`super::encode::emit_checked_addsub`], [`super::encode::emit_checked_mul`]), on the parameters.
11594fn emit_checked_arith_helper(op: ArithOp) -> Vec<u8> {
11595    let mut c = Vec::new();
11596    // locals: 2 = the result
11597    c.push(0x01);
11598    leb_u32(&mut c, 1);
11599    c.push(I64);
11600    match op {
11601        ArithOp::Add => emit_checked_addsub(&mut c, false, 2, 0, 1),
11602        ArithOp::Sub => emit_checked_addsub(&mut c, true, 2, 0, 1),
11603        ArithOp::Mul => emit_checked_mul(&mut c, 2, 0, 1),
11604        ArithOp::Div | ArithOp::Mod => {
11605            unreachable!("a division lowers inline; the runtime has no checked helper for it")
11606        }
11607    }
11608    local_get(&mut c, 2);
11609    c.push(0x0B); // end function
11610    c
11611}
11612
11613/// `__logos_new_header(class: i32) -> i32` — see [`RuntimeFn::NewHeader`]: the header
11614/// [`emit_empty_header`] builds inline, once, over a class the call site passes.
11615fn emit_new_header_helper(env: &RuntimeEnv) -> Vec<u8> {
11616    let mut c = Vec::new();
11617    // locals: 1 = hdr, 2 = counted (0/1), 3 = the class byte
11618    c.push(0x01);
11619    leb_u32(&mut c, 3);
11620    c.push(I32);
11621    let counting = env.retain_base.is_some();
11622    if counting {
11623        local_get(&mut c, 0);
11624        emit_class_is_counted(&mut c, 3);
11625        local_set(&mut c, 2);
11626    }
11627    i32_const(&mut c, 16);
11628    if counting {
11629        local_get(&mut c, 2);
11630        i32_const(&mut c, 2);
11631        c.push(0x74); // i32.shl → 4 bytes more for the count word
11632        c.push(0x6A);
11633    }
11634    c.push(0x10);
11635    leb_u32(&mut c, env.call(RuntimeFn::Alloc));
11636    local_set(&mut c, 1);
11637    for off in [0u32, 4, 8] {
11638        local_get(&mut c, 1);
11639        i32_const(&mut c, 0);
11640        i32_store(&mut c, off);
11641    }
11642    local_get(&mut c, 1);
11643    local_get(&mut c, 0);
11644    i32_store(&mut c, 12); // the class byte; no copy-on-write hold yet
11645    if counting {
11646        local_get(&mut c, 2);
11647        c.push(0x04);
11648        c.push(0x40);
11649        {
11650            local_get(&mut c, 1);
11651            i32_const(&mut c, 1);
11652            i32_store(&mut c, 16);
11653            local_get(&mut c, 1);
11654            c.push(0x10);
11655            leb_u32(&mut c, env.call(RuntimeFn::TurnRetain));
11656        }
11657        c.push(0x0B);
11658    }
11659    local_get(&mut c, 1);
11660    c.push(0x0B); // end function
11661    c
11662}
11663
11664/// `__logos_share(handle: i32)` — see [`RuntimeFn::Share`].
11665fn emit_share_helper() -> Vec<u8> {
11666    let mut c = vec![0x00]; // no locals
11667    emit_share_inline(&mut c, |c| local_get(c, 0));
11668    c.push(0x0B); // end function
11669    c
11670}
11671
11672/// `memory.copy` (bulk memory): `[dst, src, bytes]` on the stack, the bytes copied.
11673fn memory_copy(c: &mut Vec<u8>) {
11674    c.extend_from_slice(&[0xFC, 0x0A, 0x00, 0x00]);
11675}
11676
11677/// `__logos_text_eq(a: i32, b: i32) -> i32` — `1` when the two Texts hold the same bytes (the same
11678/// handle does), else `0`: unequal lengths differ at once, equal ones compare byte by byte.
11679fn emit_text_eq_helper() -> Vec<u8> {
11680    let mut c = Vec::new();
11681    // locals: 2 = i, 3 = len
11682    c.push(0x01);
11683    leb_u32(&mut c, 2);
11684    c.push(I32);
11685    local_get(&mut c, 0);
11686    local_get(&mut c, 1);
11687    c.push(0x46); // i32.eq — one handle
11688    c.push(0x04);
11689    c.push(0x40);
11690    i32_const(&mut c, 1);
11691    c.push(0x0F);
11692    c.push(0x0B);
11693    local_get(&mut c, 0);
11694    i32_load(&mut c, 0);
11695    local_tee(&mut c, 3);
11696    local_get(&mut c, 1);
11697    i32_load(&mut c, 0);
11698    c.push(0x47); // i32.ne — lengths differ
11699    c.push(0x04);
11700    c.push(0x40);
11701    i32_const(&mut c, 0);
11702    c.push(0x0F);
11703    c.push(0x0B);
11704    i32_const(&mut c, 0);
11705    local_set(&mut c, 2);
11706    c.push(0x02);
11707    c.push(0x40);
11708    c.push(0x03);
11709    c.push(0x40);
11710    local_get(&mut c, 2);
11711    local_get(&mut c, 3);
11712    c.push(0x4E); // i32.ge_s → every byte matched
11713    c.push(0x0D);
11714    leb_u32(&mut c, 1);
11715    for side in [0u32, 1] {
11716        local_get(&mut c, side);
11717        i32_load(&mut c, 8);
11718        local_get(&mut c, 2);
11719        c.push(0x6A);
11720        i32_load8_u(&mut c, 0);
11721    }
11722    c.push(0x47); // i32.ne
11723    c.push(0x04);
11724    c.push(0x40);
11725    i32_const(&mut c, 0);
11726    c.push(0x0F);
11727    c.push(0x0B);
11728    local_get(&mut c, 2);
11729    i32_const(&mut c, 1);
11730    c.push(0x6A);
11731    local_set(&mut c, 2);
11732    c.push(0x0C);
11733    leb_u32(&mut c, 0);
11734    c.push(0x0B);
11735    c.push(0x0B);
11736    i32_const(&mut c, 1);
11737    c.push(0x0B); // end function
11738    c
11739}
11740
11741/// `__logos_text_concat(a: i32, b: i32) -> i32` — a fresh Text of `a`'s bytes then `b`'s: its header
11742/// classed [`AllocClass::TextHeader`] (born counted, credited to the turn, on a module that counts
11743/// holders — as [`emit_alloc`] births one), then its buffer of exactly `len(a) + len(b)` bytes.
11744fn emit_text_concat_helper(env: &RuntimeEnv) -> Vec<u8> {
11745    let mut c = Vec::new();
11746    // locals: 2 = hdr, 3 = data, 4 = len(a)
11747    c.push(0x01);
11748    leb_u32(&mut c, 3);
11749    c.push(I32);
11750    let counting = env.retain_base.is_some();
11751    i32_const(&mut c, if counting { 20 } else { 16 });
11752    c.push(0x10);
11753    leb_u32(&mut c, env.call(RuntimeFn::Alloc));
11754    local_tee(&mut c, 2);
11755    i32_const(&mut c, i32::from(AllocClass::TextHeader.code()));
11756    i32_store(&mut c, 12);
11757    if counting {
11758        local_get(&mut c, 2);
11759        i32_const(&mut c, 1);
11760        i32_store(&mut c, 16);
11761        local_get(&mut c, 2);
11762        c.push(0x10);
11763        leb_u32(&mut c, env.call(RuntimeFn::TurnRetain));
11764    }
11765    local_get(&mut c, 0);
11766    i32_load(&mut c, 0);
11767    local_tee(&mut c, 4);
11768    local_get(&mut c, 1);
11769    i32_load(&mut c, 0);
11770    c.push(0x6A);
11771    c.push(0x10);
11772    leb_u32(&mut c, env.call(RuntimeFn::Alloc));
11773    local_tee(&mut c, 3);
11774    local_get(&mut c, 0);
11775    i32_load(&mut c, 8);
11776    local_get(&mut c, 4);
11777    memory_copy(&mut c); // a's bytes at [0, len(a))
11778    local_get(&mut c, 3);
11779    local_get(&mut c, 4);
11780    c.push(0x6A);
11781    local_get(&mut c, 1);
11782    i32_load(&mut c, 8);
11783    local_get(&mut c, 1);
11784    i32_load(&mut c, 0);
11785    memory_copy(&mut c); // b's bytes after them
11786    for off in [0u32, 4] {
11787        local_get(&mut c, 2);
11788        local_get(&mut c, 4);
11789        local_get(&mut c, 1);
11790        i32_load(&mut c, 0);
11791        c.push(0x6A);
11792        i32_store(&mut c, off);
11793    }
11794    local_get(&mut c, 2);
11795    local_get(&mut c, 3);
11796    i32_store(&mut c, 8);
11797    local_get(&mut c, 2);
11798    c.push(0x0B); // end function
11799    c
11800}
11801
11802/// `__logos_map_clone(src: i32) -> i32` — a fresh, independent map holding `src`'s `[key][value]`
11803/// entries as they are (`num` = `cap` = `src`'s `num`), with `src`'s class byte and, in a program
11804/// that builds `SharedMap`s, `src`'s replica mark ([`SHARED_MAP_MARK`]): a `SharedMap`'s copy is
11805/// another replica of the same map, classified like it. On a module that counts holders every
11806/// handle key and value gains the copy as a holder (`__logos_retain_children`).
11807fn emit_map_clone_helper(env: &RuntimeEnv) -> Vec<u8> {
11808    let mut c = Vec::new();
11809    // locals: 1 = hdr, 2 = data
11810    c.push(0x01);
11811    leb_u32(&mut c, 2);
11812    c.push(I32);
11813    i32_const(&mut c, i32::from(AllocClass::MapScalarScalar.code()));
11814    c.push(0x10);
11815    leb_u32(&mut c, env.call(RuntimeFn::NewHeader));
11816    local_set(&mut c, 1);
11817    local_get(&mut c, 0);
11818    i32_load(&mut c, 0);
11819    i32_const(&mut c, 16);
11820    c.push(0x6C);
11821    c.push(0x10);
11822    leb_u32(&mut c, env.call(RuntimeFn::Alloc));
11823    local_tee(&mut c, 2);
11824    local_get(&mut c, 0);
11825    i32_load(&mut c, 8);
11826    local_get(&mut c, 0);
11827    i32_load(&mut c, 0);
11828    i32_const(&mut c, 16);
11829    c.push(0x6C);
11830    memory_copy(&mut c);
11831    for off in [0u32, 4] {
11832        local_get(&mut c, 1);
11833        local_get(&mut c, 0);
11834        i32_load(&mut c, 0);
11835        i32_store(&mut c, off);
11836    }
11837    local_get(&mut c, 1);
11838    local_get(&mut c, 2);
11839    i32_store(&mut c, 8);
11840    local_get(&mut c, 1);
11841    if env.shared_maps {
11842        i32_const(&mut c, SHARED_MAP_MARK);
11843        i32_const(&mut c, 0);
11844        local_get(&mut c, 0);
11845        i32_load(&mut c, 12);
11846        i32_const(&mut c, 0);
11847        c.push(0x48); // i32.lt_s — a replica
11848        c.push(0x1B); // select
11849    } else {
11850        i32_const(&mut c, 0);
11851    }
11852    local_get(&mut c, 0);
11853    i32_load(&mut c, 12);
11854    i32_const(&mut c, 0xFF);
11855    c.push(0x71);
11856    c.push(0x72); // i32.or
11857    i32_store(&mut c, 12);
11858    if env.retain_base.is_some() {
11859        local_get(&mut c, 1);
11860        c.push(0x10);
11861        leb_u32(&mut c, env.call(RuntimeFn::RetainChildren));
11862    }
11863    local_get(&mut c, 1);
11864    c.push(0x0B); // end function
11865    c
11866}
11867
11868/// `__logos_map_own(m: i32) -> i32` — the copy-on-write of a map about to be written: `m` when no
11869/// other holder shares it (or it is a `SharedMap` replica), else `__logos_map_clone(m)`.
11870fn emit_map_own_helper(env: &RuntimeEnv) -> Vec<u8> {
11871    let mut c = vec![0x00]; // no locals
11872    emit_should_clone(&mut c, 0);
11873    c.push(0x04);
11874    c.push(I32);
11875    local_get(&mut c, 0);
11876    c.push(0x10);
11877    leb_u32(&mut c, env.call(RuntimeFn::MapClone));
11878    c.push(0x05);
11879    local_get(&mut c, 0);
11880    c.push(0x0B);
11881    c.push(0x0B); // end function
11882    c
11883}
11884
11885/// `__logos_map_find(m: i32, key: i64, text_key: i32) -> i32` — the address of the entry whose key
11886/// is `key` (a Text key by bytes, `key`'s low word its handle; an Int key by value), or 0.
11887fn emit_map_find_helper(env: &RuntimeEnv) -> Vec<u8> {
11888    let mut c = Vec::new();
11889    // locals: 3 = i, 4 = the entry's address
11890    c.push(0x01);
11891    leb_u32(&mut c, 2);
11892    c.push(I32);
11893    i32_const(&mut c, 0);
11894    local_set(&mut c, 3);
11895    c.push(0x02);
11896    c.push(0x40);
11897    c.push(0x03);
11898    c.push(0x40);
11899    local_get(&mut c, 3);
11900    local_get(&mut c, 0);
11901    i32_load(&mut c, 0);
11902    c.push(0x4E); // i32.ge_s → every entry scanned
11903    c.push(0x0D);
11904    leb_u32(&mut c, 1);
11905    local_get(&mut c, 0);
11906    i32_load(&mut c, 8);
11907    local_get(&mut c, 3);
11908    i32_const(&mut c, 16);
11909    c.push(0x6C);
11910    c.push(0x6A);
11911    local_set(&mut c, 4);
11912    local_get(&mut c, 2);
11913    c.push(0x04);
11914    c.push(I32);
11915    {
11916        if let Some(cmp) = env.exact_cmp {
11917            local_get(&mut c, 1);
11918            c.push(0xa7);
11919            i32_load(&mut c, 12);
11920            i32_const(&mut c, 0xff);
11921            c.push(0x71);
11922            i32_const(&mut c, AllocClass::ExactIntegerHeader.code() as i32);
11923            c.extend([0x46, 0x04, I32]);
11924            local_get(&mut c, 4);
11925            i32_load(&mut c, 0);
11926            i32_load(&mut c, 8);
11927            i64_load(&mut c, 0);
11928            local_get(&mut c, 1);
11929            c.push(0xa7);
11930            i32_load(&mut c, 8);
11931            i64_load(&mut c, 0);
11932            c.push(0x10);
11933            leb_u32(&mut c, cmp);
11934            c.extend([0x45, 0x05]);
11935        }
11936        local_get(&mut c, 4);
11937        i32_load(&mut c, 0);
11938        local_get(&mut c, 1);
11939        c.push(0xA7); // i32.wrap_i64
11940        c.push(0x10);
11941        leb_u32(&mut c, env.call(RuntimeFn::TextEq));
11942        if env.exact_cmp.is_some() {
11943            c.push(0x0b);
11944        }
11945    }
11946    c.push(0x05);
11947    {
11948        local_get(&mut c, 4);
11949        i64_load(&mut c, 0);
11950        local_get(&mut c, 1);
11951        c.push(0x51); // i64.eq
11952    }
11953    c.push(0x0B);
11954    c.push(0x04);
11955    c.push(0x40);
11956    local_get(&mut c, 4);
11957    c.push(0x0F);
11958    c.push(0x0B);
11959    local_get(&mut c, 3);
11960    i32_const(&mut c, 1);
11961    c.push(0x6A);
11962    local_set(&mut c, 3);
11963    c.push(0x0C);
11964    leb_u32(&mut c, 0);
11965    c.push(0x0B);
11966    c.push(0x0B);
11967    i32_const(&mut c, 0);
11968    c.push(0x0B); // end function
11969    c
11970}
11971
11972/// `__logos_map_at(m: i32, key: i64, text_key: i32) -> i32` — [`emit_map_find_helper`]'s entry,
11973/// trapping when the map holds no such key (the tree-walker's "Key not found").
11974fn emit_map_at_helper(env: &RuntimeEnv) -> Vec<u8> {
11975    let mut c = Vec::new();
11976    // locals: 3 = the entry's address
11977    c.push(0x01);
11978    leb_u32(&mut c, 1);
11979    c.push(I32);
11980    local_get(&mut c, 0);
11981    local_get(&mut c, 1);
11982    local_get(&mut c, 2);
11983    c.push(0x10);
11984    leb_u32(&mut c, env.call(RuntimeFn::MapFind));
11985    local_tee(&mut c, 3);
11986    c.push(0x45); // i32.eqz
11987    c.push(0x04);
11988    c.push(0x40);
11989    c.push(0x00); // unreachable
11990    c.push(0x0B);
11991    local_get(&mut c, 3);
11992    c.push(0x0B); // end function
11993    c
11994}
11995
11996/// `__logos_map_put(m: i32, key: i64, class: i32) -> i32` — the address of the entry `key` names in
11997/// `m`, which the caller stores the value into at +8. `class` (the map's key/value handle-ness,
11998/// [`AllocClass::of_map`]) is stamped into the class byte first — the first insert is where a map's
11999/// kinds are first visible, and every later one writes the same byte — and says whether the key is
12000/// a Text. An absent key is appended: the entry buffer doubles when full (4 entries from none; the
12001/// old buffer goes back to the allocator, dead by construction), the key is written, the value slot
12002/// starts empty, and on a module that counts holders a Text key gains the map as its holder. A
12003/// `SharedMap`'s sorted insert is not this function's (its callers insert inline).
12004fn emit_map_put_helper(env: &RuntimeEnv) -> Vec<u8> {
12005    let mut c = Vec::new();
12006    // locals: 3 = text key (0/1), 4 = the entry's address, 5 = the new buffer, 6 = the new cap
12007    c.push(0x01);
12008    leb_u32(&mut c, 4);
12009    c.push(I32);
12010    local_get(&mut c, 0);
12011    local_get(&mut c, 0);
12012    i32_load(&mut c, 12);
12013    i32_const(&mut c, !0xFFu32 as i32);
12014    c.push(0x71);
12015    local_get(&mut c, 2);
12016    c.push(0x72);
12017    i32_store(&mut c, 12);
12018    let key_handle: i32 = AllocClass::ALL
12019        .iter()
12020        .filter(|k| k.held_handles().0 && **k != AllocClass::HandleHeader)
12021        .map(|k| 1i32 << k.code())
12022        .sum();
12023    i32_const(&mut c, key_handle);
12024    local_get(&mut c, 2);
12025    c.push(0x76); // i32.shr_u
12026    i32_const(&mut c, 1);
12027    c.push(0x71);
12028    local_set(&mut c, 3);
12029    local_get(&mut c, 0);
12030    local_get(&mut c, 1);
12031    local_get(&mut c, 3);
12032    c.push(0x10);
12033    leb_u32(&mut c, env.call(RuntimeFn::MapFind));
12034    local_tee(&mut c, 4);
12035    c.push(0x04);
12036    c.push(0x40);
12037    local_get(&mut c, 4);
12038    c.push(0x0F); // an entry already holds the key
12039    c.push(0x0B);
12040    local_get(&mut c, 0);
12041    i32_load(&mut c, 0);
12042    local_get(&mut c, 0);
12043    i32_load(&mut c, 4);
12044    c.push(0x4E); // i32.ge_s → full
12045    c.push(0x04);
12046    c.push(0x40);
12047    {
12048        i32_const(&mut c, 4);
12049        local_get(&mut c, 0);
12050        i32_load(&mut c, 4);
12051        i32_const(&mut c, 2);
12052        c.push(0x6C);
12053        local_get(&mut c, 0);
12054        i32_load(&mut c, 4);
12055        c.push(0x45);
12056        c.push(0x1B); // select → cap == 0 ? 4 : cap * 2
12057        local_tee(&mut c, 6);
12058        i32_const(&mut c, 16);
12059        c.push(0x6C);
12060        c.push(0x10);
12061        leb_u32(&mut c, env.call(RuntimeFn::Alloc));
12062        local_tee(&mut c, 5);
12063        local_get(&mut c, 0);
12064        i32_load(&mut c, 8);
12065        local_get(&mut c, 0);
12066        i32_load(&mut c, 0);
12067        i32_const(&mut c, 16);
12068        c.push(0x6C);
12069        memory_copy(&mut c);
12070        local_get(&mut c, 0);
12071        i32_load(&mut c, 8);
12072        local_get(&mut c, 0);
12073        i32_load(&mut c, 4);
12074        i32_const(&mut c, 16);
12075        c.push(0x6C);
12076        c.push(0x10); // call __logos_free(old data_ptr, cap * 16) — null frees nothing
12077        leb_u32(&mut c, env.call(RuntimeFn::Free));
12078        local_get(&mut c, 0);
12079        local_get(&mut c, 5);
12080        i32_store(&mut c, 8);
12081        local_get(&mut c, 0);
12082        local_get(&mut c, 6);
12083        i32_store(&mut c, 4);
12084    }
12085    c.push(0x0B);
12086    local_get(&mut c, 0);
12087    i32_load(&mut c, 8);
12088    local_get(&mut c, 0);
12089    i32_load(&mut c, 0);
12090    i32_const(&mut c, 16);
12091    c.push(0x6C);
12092    c.push(0x6A);
12093    local_set(&mut c, 4);
12094    local_get(&mut c, 3);
12095    c.push(0x04);
12096    c.push(0x40);
12097    {
12098        local_get(&mut c, 4);
12099        local_get(&mut c, 1);
12100        c.push(0xA7);
12101        i32_store(&mut c, 0);
12102        if env.retain_base.is_some() {
12103            local_get(&mut c, 1);
12104            c.push(0xA7);
12105            c.push(0x10);
12106            leb_u32(&mut c, env.call(RuntimeFn::Retain));
12107        }
12108    }
12109    c.push(0x05);
12110    {
12111        local_get(&mut c, 4);
12112        local_get(&mut c, 1);
12113        i64_store(&mut c, 0);
12114    }
12115    c.push(0x0B);
12116    local_get(&mut c, 4);
12117    c.push(0x42);
12118    leb_i64(&mut c, 0);
12119    i64_store(&mut c, 8); // the value slot starts empty
12120    local_get(&mut c, 0);
12121    local_get(&mut c, 0);
12122    i32_load(&mut c, 0);
12123    i32_const(&mut c, 1);
12124    c.push(0x6A);
12125    i32_store(&mut c, 0);
12126    local_get(&mut c, 4);
12127    c.push(0x0B); // end function
12128    c
12129}
12130
12131/// `__logos_seq_own(hdr: i32, mode: i32) -> i32` — the copy-on-write of a sequence about to be
12132/// written. [`emit_should_clone`]'s test: a `SharedMap` replica (word 12 negative) and a block no
12133/// other holder shares (no count above the class byte) are written in place, and `hdr` comes back;
12134/// anything else comes back as `__logos_seq_clone(hdr, mode)`, the writer's own copy.
12135fn emit_seq_own_helper(env: &RuntimeEnv) -> Vec<u8> {
12136    let mut c = vec![0x00]; // no locals
12137    emit_should_clone(&mut c, 0);
12138    c.push(0x04);
12139    c.push(I32); // if (result i32)
12140    local_get(&mut c, 0);
12141    local_get(&mut c, 1);
12142    c.push(0x10);
12143    leb_u32(&mut c, env.call(RuntimeFn::SeqClone));
12144    c.push(0x05); // else
12145    local_get(&mut c, 0);
12146    c.push(0x0B);
12147    c.push(0x0B); // end function
12148    c
12149}
12150
12151/// `__logos_text_new(len: i32) -> i32` — a Text handle the HOST writes `len` raw bytes into, built
12152/// from the same allocator every module-side Text uses: a `len`-byte data buffer, then a
12153/// `[len][cap][data_ptr][extra_refs|class]` header pointed at it, classed [`AllocClass::TextHeader`]
12154/// (with a true-count word after it when the module reclaims).
12155fn emit_text_new_helper(env: &RuntimeEnv) -> Vec<u8> {
12156    let mut c = Vec::new();
12157    // locals: 1 = data, 2 = hdr
12158    c.push(0x01);
12159    leb_u32(&mut c, 2);
12160    c.push(I32);
12161
12162    local_get(&mut c, 0); // len
12163    c.push(0x10); // call __logos_alloc(len)
12164    leb_u32(&mut c, env.call(RuntimeFn::Alloc));
12165    local_set(&mut c, 1); // data
12166
12167    // A counted Text (S12, reclaim on): the header carries the count word, the turn is its first
12168    // holder, and a safepoint frees it once nothing the module keeps holds it — which is how the
12169    // host's per-event texts (the event name and value it writes for every dispatch) come back.
12170    let counted = env.retain_base.is_some();
12171    i32_const(&mut c, if counted { 20 } else { 16 });
12172    c.push(0x10); // call __logos_alloc(header)
12173    leb_u32(&mut c, env.call(RuntimeFn::Alloc));
12174    local_set(&mut c, 2); // hdr
12175
12176    local_get(&mut c, 2);
12177    local_get(&mut c, 0);
12178    i32_store(&mut c, 0); // header.len = len
12179    local_get(&mut c, 2);
12180    local_get(&mut c, 0);
12181    i32_store(&mut c, 4); // header.cap = len
12182    local_get(&mut c, 2);
12183    local_get(&mut c, 1);
12184    i32_store(&mut c, 8); // header.data_ptr = data
12185    local_get(&mut c, 2);
12186    i32_const(&mut c, AllocClass::TextHeader.code() as i32);
12187    i32_store(&mut c, 12);
12188    if counted {
12189        local_get(&mut c, 2);
12190        i32_const(&mut c, 1);
12191        i32_store(&mut c, 16); // a true count of 1, held by the turn
12192        local_get(&mut c, 2);
12193        c.push(0x10); // call __logos_turn_retain(hdr)
12194        leb_u32(&mut c, env.call(RuntimeFn::TurnRetain));
12195    }
12196
12197    local_get(&mut c, 2); // return hdr
12198    c.push(0x0B); // end function
12199    c
12200}
12201
12202/// `__logos_free(ptr: i32, size: i32)` — push a block back onto its size class's list.
12203///
12204/// ★ CALLED ONLY WHERE A BLOCK IS DEAD BY CONSTRUCTION. This is the allocator half of the work; the
12205/// release protocol that decides when a VALUE dies is a separate, larger piece. Until that lands the
12206/// one caller is the sequence-growth path, which allocates a bigger buffer, copies into it and
12207/// repoints `data_ptr` — the old buffer is an internal buffer of that one header and nothing else
12208/// can be holding it, so freeing it needs no refcount to be sound.
12209fn emit_free_helper() -> Vec<u8> {
12210    let mut c = Vec::new();
12211    // locals: 2 = u, 3 = slot address, 4 = whether a free list exists for this size at all,
12212    // 5 = the power tier's class index (kept apart from `u`, which the 16-byte guard still needs)
12213    c.push(0x01);
12214    leb_u32(&mut c, 4);
12215    c.push(I32);
12216
12217    local_get(&mut c, 0); // ptr — a null frees nothing
12218    c.push(0x04);
12219    c.push(0x40);
12220    {
12221        local_get(&mut c, 1);
12222        i32_const(&mut c, 7);
12223        c.push(0x6A);
12224        i32_const(&mut c, 3);
12225        c.push(0x76);
12226        local_set(&mut c, 2); // u = (size + 7) >> 3
12227        i32_const(&mut c, 0);
12228        local_set(&mut c, 4); // has_class = 0
12229
12230        // 1 <= u <= FREE_CLASSES: the exact tier, always has a list.
12231        local_get(&mut c, 2);
12232        i32_const(&mut c, 0);
12233        c.push(0x4B); // i32.gt_u → u > 0
12234        local_get(&mut c, 2);
12235        i32_const(&mut c, FREE_CLASSES);
12236        c.push(0x4D); // i32.le_u
12237        c.push(0x71); // i32.and
12238        c.push(0x04);
12239        c.push(0x40); // if (exact tier)
12240        {
12241            local_get(&mut c, 2);
12242            i32_const(&mut c, 1);
12243            c.push(0x6B);
12244            i32_const(&mut c, 4);
12245            c.push(0x6C);
12246            i32_const(&mut c, FREE_TABLE_BASE);
12247            c.push(0x6A);
12248            local_set(&mut c, 3); // slot
12249            i32_const(&mut c, 1);
12250            local_set(&mut c, 4); // has_class = 1
12251        }
12252        c.push(0x05); // else — u > FREE_CLASSES: the power-of-two tier, same size math as the alloc side
12253        {
12254            // power_idx = (32 - POWER_MIN) - clz(size - 1)
12255            i32_const(&mut c, 32 - POWER_MIN);
12256            local_get(&mut c, 1);
12257            i32_const(&mut c, 1);
12258            c.push(0x6B); // size - 1
12259            c.push(0x67); // i32.clz
12260            c.push(0x6B);
12261            local_tee(&mut c, 5); // power_idx
12262            i32_const(&mut c, POWER_CLASSES);
12263            c.push(0x49); // i32.lt_u
12264            c.push(0x04);
12265            c.push(0x40); // if (has a class)
12266            {
12267                local_get(&mut c, 5);
12268                i32_const(&mut c, FREE_CLASSES);
12269                c.push(0x6A);
12270                i32_const(&mut c, 4);
12271                c.push(0x6C);
12272                i32_const(&mut c, FREE_TABLE_BASE);
12273                c.push(0x6A);
12274                local_set(&mut c, 3); // slot
12275                i32_const(&mut c, 1);
12276                local_set(&mut c, 4); // has_class = 1
12277            }
12278            c.push(0x0B); // end if — else past the last power class: no list, the block is dropped
12279        }
12280        c.push(0x0B); // end if/else
12281
12282        local_get(&mut c, 4);
12283        c.push(0x04);
12284        c.push(0x40); // if (has_class)
12285        {
12286            // ★ A RECYCLED BLOCK MUST NOT CARRY A STALE REFCOUNT. An object header keeps its
12287            // `extra_refs` at word 12 and the builders write words 0, 4 and 8 only — they rely on
12288            // fresh bump memory being zero, which was true when nothing was ever reused. A block
12289            // handed back and later used as a header would otherwise start with whatever sat at
12290            // word 12, and for a recycled DATA BUFFER that is an element's value: `emit_cow` would
12291            // then read a huge count and clone on every mutation for the life of that object. Not
12292            // unsound — a clone is always safe — but it would have quietly undone the reuse this
12293            // allocator exists for, and only shown up as a page that got slower the longer it ran.
12294            //
12295            // Zeroed here rather than in `alloc` because only the free path knows the block is at
12296            // least 16 bytes: writing offset 12 of a smaller block would scribble on its neighbour.
12297            // A power-tier block is always at least 2 KiB, so this always fires there too.
12298            local_get(&mut c, 2);
12299            i32_const(&mut c, 2);
12300            c.push(0x4F); // i32.ge_u → the block is at least 16 bytes
12301            c.push(0x04);
12302            c.push(0x40); // if
12303            {
12304                local_get(&mut c, 0);
12305                i32_const(&mut c, 0);
12306                i32_store(&mut c, 12);
12307            }
12308            c.push(0x0B);
12309
12310            // *ptr = table[slot]; table[slot] = ptr
12311            local_get(&mut c, 0);
12312            local_get(&mut c, 3);
12313            i32_load(&mut c, 0);
12314            i32_store(&mut c, 0);
12315            local_get(&mut c, 3);
12316            local_get(&mut c, 0);
12317            i32_store(&mut c, 0);
12318        }
12319        c.push(0x0B);
12320    }
12321    c.push(0x0B);
12322
12323    c.push(0x0B); // end function
12324    c
12325}
12326
12327/// S8's UAF-detection value: overwritten across a freed object's own header (never its data buffer
12328/// — `__logos_free` immediately threads word 0 with the free list's own "next" pointer regardless,
12329/// so poisoning it is moot; words 4/8/16 are not touched by anything else and stay this value until
12330/// the block is handed back out by a fresh `__logos_alloc`, which zeroes it again).
12331const HEAP_POISON: i32 = 0xDEAD_BEEFu32 as i32;
12332
12333/// `__logos_turn_retain(handle)` — append `handle` to the S8 turn-retained list, growing its buffer
12334/// (double, `alloc`/`free`, the same amortized shape every other growable buffer in this backend
12335/// uses) when full. Two callers: [`emit_alloc`] for a fresh counted block (the turn is its first,
12336/// implicit holder) and [`emit_true_release_helper`] when a mid-turn release would otherwise take a
12337/// count to zero (deferred to the next safepoint instead of freed on the spot).
12338fn emit_turn_retain_helper(env: &RuntimeEnv) -> Vec<u8> {
12339    let Some(base) = env.retain_base else {
12340        return vec![0x00, 0x0B];
12341    };
12342    let (ptr_g, len_g, cap_g) = (base, base + 1, base + 2);
12343    let mut c = Vec::new();
12344    c.push(0x01);
12345    leb_u32(&mut c, 3);
12346    c.push(I32); // locals: 1 = new_cap, 2 = new_ptr, 3 = copy-loop i
12347    global_get(&mut c, len_g);
12348    global_get(&mut c, cap_g);
12349    c.push(0x48); // i32.lt_s → len < cap
12350    c.push(0x04);
12351    c.push(0x40); // if (room already): store and return
12352    {
12353        global_get(&mut c, ptr_g);
12354        global_get(&mut c, len_g);
12355        i32_const(&mut c, 4);
12356        c.push(0x6C);
12357        c.push(0x6A);
12358        local_get(&mut c, 0);
12359        i32_store(&mut c, 0);
12360        global_get(&mut c, len_g);
12361        i32_const(&mut c, 1);
12362        c.push(0x6A);
12363        global_set(&mut c, len_g);
12364        c.push(0x0F); // return
12365    }
12366    c.push(0x0B); // end if
12367                  // new_cap = cap == 0 ? 4 : cap * 2
12368    i32_const(&mut c, 4);
12369    global_get(&mut c, cap_g);
12370    i32_const(&mut c, 2);
12371    c.push(0x6C);
12372    global_get(&mut c, cap_g);
12373    c.push(0x45); // i32.eqz
12374    c.push(0x1B); // select
12375    local_set(&mut c, 1);
12376    // new_ptr = alloc(new_cap * 4)
12377    local_get(&mut c, 1);
12378    i32_const(&mut c, 4);
12379    c.push(0x6C);
12380    c.push(0x10);
12381    leb_u32(&mut c, env.call(RuntimeFn::Alloc));
12382    local_set(&mut c, 2);
12383    // for i in 0..len: new_ptr[i] = old_ptr[i]
12384    i32_const(&mut c, 0);
12385    local_set(&mut c, 3);
12386    c.push(0x02);
12387    c.push(0x40); // block
12388    c.push(0x03);
12389    c.push(0x40); // loop
12390    local_get(&mut c, 3);
12391    global_get(&mut c, len_g);
12392    c.push(0x4E); // i32.ge_s
12393    c.push(0x0D);
12394    leb_u32(&mut c, 1); // br_if exit
12395    local_get(&mut c, 2);
12396    local_get(&mut c, 3);
12397    i32_const(&mut c, 4);
12398    c.push(0x6C);
12399    c.push(0x6A);
12400    global_get(&mut c, ptr_g);
12401    local_get(&mut c, 3);
12402    i32_const(&mut c, 4);
12403    c.push(0x6C);
12404    c.push(0x6A);
12405    i32_load(&mut c, 0);
12406    i32_store(&mut c, 0);
12407    local_get(&mut c, 3);
12408    i32_const(&mut c, 1);
12409    c.push(0x6A);
12410    local_set(&mut c, 3);
12411    c.push(0x0C);
12412    leb_u32(&mut c, 0); // br loop
12413    c.push(0x0B); // end loop
12414    c.push(0x0B); // end block
12415                  // free the old buffer, if it had one
12416    global_get(&mut c, cap_g);
12417    c.push(0x04);
12418    c.push(0x40);
12419    {
12420        global_get(&mut c, ptr_g);
12421        global_get(&mut c, cap_g);
12422        i32_const(&mut c, 4);
12423        c.push(0x6C);
12424        c.push(0x10);
12425        leb_u32(&mut c, env.call(RuntimeFn::Free));
12426    }
12427    c.push(0x0B);
12428    local_get(&mut c, 2);
12429    global_set(&mut c, ptr_g);
12430    local_get(&mut c, 1);
12431    global_set(&mut c, cap_g);
12432    // store handle at [ptr, len]; len += 1
12433    global_get(&mut c, ptr_g);
12434    global_get(&mut c, len_g);
12435    i32_const(&mut c, 4);
12436    c.push(0x6C);
12437    c.push(0x6A);
12438    local_get(&mut c, 0);
12439    i32_store(&mut c, 0);
12440    global_get(&mut c, len_g);
12441    i32_const(&mut c, 1);
12442    c.push(0x6A);
12443    global_set(&mut c, len_g);
12444    c.push(0x0B); // end function
12445    c
12446}
12447
12448/// `__logos_retain(handle)` — `mem[handle+16] += 1` for a block whose class carries a true count
12449/// ([`emit_class_is_counted`]), a no-op on a null handle and on every other block. The S8 true-count
12450/// analogue of [`emit_retain`] (word 12, COW-only, untouched by this) — called wherever a counted
12451/// value becomes held by a SECOND real, heap-resident holder. The class byte, not the caller's static
12452/// kind, decides: a map or a `Raw` block has no word 16 of its own, and a kind that names the wrong
12453/// shape must not write one into whatever follows it.
12454fn emit_true_retain_helper() -> Vec<u8> {
12455    let mut c = Vec::new();
12456    c.push(0x01);
12457    leb_u32(&mut c, 1);
12458    c.push(I32); // local 1 = class
12459    local_get(&mut c, 0);
12460    c.push(0x04);
12461    c.push(0x40); // if handle != 0
12462    {
12463        local_get(&mut c, 0);
12464        i32_load(&mut c, 12);
12465        emit_class_is_counted(&mut c, 1);
12466        c.push(0x04);
12467        c.push(0x40); // if the block carries a true count
12468        {
12469            local_get(&mut c, 0);
12470            local_get(&mut c, 0);
12471            i32_load(&mut c, 16);
12472            i32_const(&mut c, 1);
12473            c.push(0x6A);
12474            i32_store(&mut c, 16);
12475        }
12476        c.push(0x0B);
12477    }
12478    c.push(0x0B);
12479    c.push(0x0B); // end function
12480    c
12481}
12482
12483/// `__logos_retain_children(handle)` — every handle the block holds gains it as a holder. The class
12484/// byte names the shape, as it does for the free cascade: a `HandleHeader`'s 8-byte slots up to
12485/// `len`; a map's 16-byte `[key][value]` entries up to `num`, the key word when its class names
12486/// handle keys and the value word when it names handle values ([`AllocClass::held_handles`]); no
12487/// slot at all for any other class. Each handle goes through `__logos_retain`, which leaves a block
12488/// whose own class carries no count (a record, a pooled literal) as it is. A no-op on a null handle.
12489/// Emit a visit to each owned child in a sequence or map. Each callback consumes one handle;
12490/// locals are private to this traversal and survive calls into recursive runtime helpers.
12491
12492fn emit_class_has_field_kinds(c: &mut Vec<u8>, class: u32) {
12493    for (i, kind) in [
12494        AllocClass::RecordHeader,
12495        AllocClass::EnumHeader,
12496        AllocClass::ClosureHeader,
12497    ]
12498    .iter()
12499    .enumerate()
12500    {
12501        local_get(c, class);
12502        i32_const(c, i32::from(kind.code()));
12503        c.push(0x46);
12504        if i != 0 {
12505            c.push(0x72);
12506        }
12507    }
12508}
12509
12510fn emit_heap_child_count(c: &mut Vec<u8>, handle: u32, class: u32) {
12511    local_get(c, handle);
12512    i32_load(c, 4);
12513    local_get(c, handle);
12514    i32_load(c, 0);
12515    local_get(c, class);
12516    i32_const(c, i32::from(AllocClass::EnumHeader.code()));
12517    c.push(0x46);
12518    local_get(c, class);
12519    i32_const(c, i32::from(AllocClass::ClosureHeader.code()));
12520    c.push(0x46);
12521    c.push(0x72);
12522    c.push(0x1B); // enum tags and closure function indices are not payload lengths
12523}
12524
12525fn emit_each_heap_child(
12526    c: &mut Vec<u8>,
12527    handle: u32,
12528    locals: [u32; 5],
12529    visit: impl Fn(&mut Vec<u8>),
12530) {
12531    let [class, stride, flags, index, slot] = locals;
12532    let mask = |second: bool| -> i32 {
12533        AllocClass::ALL
12534            .iter()
12535            .filter(|k| {
12536                let words = k.held_handles();
12537                if second {
12538                    words.1
12539                } else {
12540                    words.0
12541                }
12542            })
12543            .map(|k| 1i32 << k.code())
12544            .sum()
12545    };
12546    local_get(c, handle);
12547    i32_load(c, 12);
12548    i32_const(c, 0xFF);
12549    c.push(0x71);
12550    local_set(c, class);
12551    for (bit, m) in [(0, mask(false)), (1, mask(true))] {
12552        i32_const(c, m);
12553        local_get(c, class);
12554        c.push(0x76);
12555        i32_const(c, 1);
12556        c.push(0x71);
12557        if bit == 1 {
12558            i32_const(c, 1);
12559            c.push(0x74);
12560            c.push(0x72);
12561        }
12562    }
12563    local_set(c, flags);
12564    local_get(c, class);
12565    i32_const(c, AllocClass::ALL.len() as i32);
12566    c.push(0x49);
12567    c.push(0x04);
12568    c.push(0x40);
12569    local_get(c, flags);
12570    c.push(0x04);
12571    c.push(0x40);
12572    i32_const(c, 8);
12573    i32_const(c, 16);
12574    local_get(c, class);
12575    i32_const(c, i32::from(AllocClass::HandleHeader.code()));
12576    c.push(0x46);
12577    emit_class_has_field_kinds(c, class);
12578    c.push(0x72);
12579    c.push(0x1B);
12580    local_set(c, stride);
12581    i32_const(c, 0);
12582    local_set(c, index);
12583    c.push(0x02);
12584    c.push(0x40);
12585    c.push(0x03);
12586    c.push(0x40);
12587    local_get(c, index);
12588    emit_heap_child_count(c, handle, class);
12589    c.push(0x4F);
12590    c.push(0x0D);
12591    leb_u32(c, 1);
12592    local_get(c, handle);
12593    i32_load(c, 8);
12594    local_get(c, index);
12595    local_get(c, stride);
12596    c.push(0x6C);
12597    c.push(0x6A);
12598    local_set(c, slot);
12599    for (bit, off) in [(1, 0), (2, 8)] {
12600        local_get(c, flags);
12601        i32_const(c, bit);
12602        c.push(0x71);
12603        c.push(0x45);
12604        c.push(0x45); // normalize either handle bit (1 or 2) before combining with a field flag
12605        emit_class_has_field_kinds(c, class);
12606        c.push(0x04);
12607        c.push(I32);
12608        local_get(c, handle);
12609        i32_load(c, 8);
12610        emit_heap_child_count(c, handle, class);
12611        i32_const(c, 16);
12612        i32_const(c, 8);
12613        local_get(c, class);
12614        i32_const(c, i32::from(AllocClass::ClosureHeader.code()));
12615        c.push(0x46);
12616        c.push(0x1B); // closures place present flags between values and ownership bytes
12617        c.push(0x6C);
12618        c.push(0x6A);
12619        local_get(c, index);
12620        c.push(0x6A);
12621        i32_load8_u(c, 0);
12622        c.push(0x05);
12623        i32_const(c, 1);
12624        c.push(0x0B);
12625        c.push(0x71);
12626        c.push(0x04);
12627        c.push(0x40);
12628        local_get(c, slot);
12629        i32_load(c, off);
12630        visit(c);
12631        c.push(0x0B);
12632    }
12633    local_get(c, index);
12634    i32_const(c, 1);
12635    c.push(0x6A);
12636    local_set(c, index);
12637    c.push(0x0C);
12638    leb_u32(c, 0);
12639    c.push(0x0B);
12640    c.push(0x0B);
12641    c.push(0x0B);
12642    c.push(0x0B);
12643}
12644
12645fn emit_retain_children_helper(env: &RuntimeEnv) -> Vec<u8> {
12646    let mut c = vec![0x01];
12647    leb_u32(&mut c, 5);
12648    c.push(I32);
12649    local_get(&mut c, 0);
12650    c.push(0x04);
12651    c.push(0x40);
12652    emit_each_heap_child(&mut c, 0, [1, 2, 3, 4, 5], |c| {
12653        c.push(0x10);
12654        leb_u32(c, env.call(RuntimeFn::Retain));
12655    });
12656    c.push(0x0B);
12657    c.push(0x0B);
12658    c
12659}
12660
12661/// A new host registration owns its closure before the imported host is entered.
12662/// The registry stores `[identity, closure, next]`; released entries may be reused, identities may not.
12663fn emit_closure_retain_helper(env: &RuntimeEnv) -> Vec<u8> {
12664    let Some(base) = env.callback_base else {
12665        return vec![0x00, 0x00, 0x0B];
12666    };
12667    let mut c = vec![0x01];
12668    leb_u32(&mut c, 1);
12669    c.push(I32); // local 1: registry entry
12670    global_get(&mut c, base + 1);
12671    i32_const(&mut c, -1);
12672    c.push(0x46);
12673    c.extend([0x04, 0x40, 0x00, 0x0B]); // never wrap and reuse an identity
12674    i32_const(&mut c, 12);
12675    c.push(0x10);
12676    leb_u32(&mut c, env.call(RuntimeFn::Alloc));
12677    local_set(&mut c, 1);
12678    global_get(&mut c, base + 1);
12679    i32_const(&mut c, 1);
12680    c.push(0x6A);
12681    global_set(&mut c, base + 1);
12682    local_get(&mut c, 1);
12683    global_get(&mut c, base + 1);
12684    i32_store(&mut c, 0);
12685    local_get(&mut c, 1);
12686    local_get(&mut c, 0);
12687    i32_store(&mut c, 4);
12688    local_get(&mut c, 1);
12689    global_get(&mut c, base);
12690    i32_store(&mut c, 8);
12691    local_get(&mut c, 1);
12692    global_set(&mut c, base);
12693    local_get(&mut c, 0);
12694    c.push(0x10);
12695    leb_u32(&mut c, env.call(RuntimeFn::Retain));
12696    global_get(&mut c, base + 1);
12697    c.push(0x0B);
12698    c
12699}
12700
12701/// Remove one host registration. Other registrations of the same closure keep their own references.
12702/// The closure's final release joins the ordinary turn worklist; no captured value is freed mid-turn.
12703fn emit_closure_release_helper(env: &RuntimeEnv) -> Vec<u8> {
12704    let Some(base) = env.callback_base else {
12705        return vec![0x00, 0x0B];
12706    };
12707    let mut c = vec![0x01];
12708    leb_u32(&mut c, 2);
12709    c.push(I32); // locals 1: entry, 2: preceding entry
12710    global_get(&mut c, base);
12711    local_set(&mut c, 1);
12712    c.extend([0x02, 0x40, 0x03, 0x40]);
12713    local_get(&mut c, 1);
12714    c.push(0x45);
12715    c.push(0x0D);
12716    leb_u32(&mut c, 1);
12717    local_get(&mut c, 1);
12718    i32_load(&mut c, 0);
12719    local_get(&mut c, 0);
12720    c.push(0x46);
12721    c.extend([0x04, 0x40]);
12722    local_get(&mut c, 2);
12723    c.extend([0x04, 0x40]);
12724    local_get(&mut c, 2);
12725    local_get(&mut c, 1);
12726    i32_load(&mut c, 8);
12727    i32_store(&mut c, 8);
12728    c.push(0x05);
12729    local_get(&mut c, 1);
12730    i32_load(&mut c, 8);
12731    global_set(&mut c, base);
12732    c.push(0x0B);
12733    local_get(&mut c, 1);
12734    i32_load(&mut c, 4);
12735    c.push(0x10);
12736    leb_u32(&mut c, env.call(RuntimeFn::Release));
12737    local_get(&mut c, 1);
12738    i32_const(&mut c, 12);
12739    c.push(0x10);
12740    leb_u32(&mut c, env.call(RuntimeFn::Free));
12741    c.push(0x0F);
12742    c.push(0x0B);
12743    local_get(&mut c, 1);
12744    local_set(&mut c, 2);
12745    local_get(&mut c, 1);
12746    i32_load(&mut c, 8);
12747    local_set(&mut c, 1);
12748    c.push(0x0C);
12749    leb_u32(&mut c, 0);
12750    c.extend([0x0B, 0x0B, 0x0B]);
12751    c
12752}
12753
12754/// `__logos_release(handle)` — the MID-TURN release: `mem[handle+16] -= 1`, UNLESS that would reach
12755/// 0, in which case the count is left alone and `handle` is pushed back onto the turn's retained
12756/// list instead — "a mid-turn drop to 0 re-lists it on the turn" (S8's design). A no-op on a null
12757/// handle and on a block whose class carries no true count ([`emit_true_retain_helper`]'s rule —
12758/// a map listed here would be freed at the safepoint with its entries still reachable). Never frees
12759/// anything itself; only [`emit_safepoint_helper`]'s drain does that.
12760fn emit_true_release_helper(env: &RuntimeEnv) -> Vec<u8> {
12761    let mut c = Vec::new();
12762    c.push(0x01);
12763    leb_u32(&mut c, 1);
12764    c.push(I32); // local 1 = n
12765    local_get(&mut c, 0);
12766    c.push(0x04);
12767    c.push(0x40); // if handle != 0
12768    {
12769        local_get(&mut c, 0);
12770        i32_load(&mut c, 12);
12771        emit_class_is_counted(&mut c, 1);
12772        c.push(0x45); // i32.eqz
12773        c.push(0x0D); // br_if 0 — leave the `if`: nothing to release
12774        leb_u32(&mut c, 0);
12775        local_get(&mut c, 0);
12776        i32_load(&mut c, 16);
12777        local_set(&mut c, 1);
12778        local_get(&mut c, 1);
12779        i32_const(&mut c, 1);
12780        c.push(0x4C); // i32.le_s → n <= 1
12781        c.push(0x04);
12782        c.push(0x40); // if (would hit 0): defer to the turn list
12783        {
12784            local_get(&mut c, 0);
12785            c.push(0x10);
12786            leb_u32(&mut c, env.call(RuntimeFn::TurnRetain));
12787        }
12788        c.push(0x05); // else: a real remaining holder, plain decrement
12789        {
12790            local_get(&mut c, 0);
12791            local_get(&mut c, 1);
12792            i32_const(&mut c, 1);
12793            c.push(0x6B);
12794            i32_store(&mut c, 16);
12795        }
12796        c.push(0x0B); // end if/else
12797    }
12798    c.push(0x0B); // end outer if
12799    c.push(0x0B); // end function
12800    c
12801}
12802
12803/// `__logos_free_object(handle)` — the free cascade's own worker, called ONLY from
12804/// [`emit_safepoint_helper`]'s worklist (never mid-turn): `handle`'s true count has JUST reached 0.
12805/// For a `HandleHeader` (class 2), each element slot (an i32 handle, one per 8-byte slot up to
12806/// `num`) is released AUTHORITATIVELY — an unconditional decrement, recursing into this SAME
12807/// function when THAT reaches 0 too. A `Raw`-classified child (an immortal `Text`/`Struct`/`Enum`
12808/// element, class byte 0) is left alone: it was never counted, so it is never freed by this either
12809/// — the exact, permanent, SAFE leak `AllocClass::is_counted`'s doc names, not a bug.
12810///
12811/// The recursion here is ordinary wasm `call`s, not an explicit worklist array, because this
12812/// session's counted classes cannot nest more than one level deep: a `HandleHeader`'s own elements
12813/// are either `Raw` (no further children at all) or `ScalarHeader` (counted, but itself a LEAF —
12814/// nothing inside a plain numeric/boolean sequence is ever a handle). `Map` — the one shape that
12815/// COULD recurse arbitrarily — is not itself counted this session (see `AllocClass::is_counted`),
12816/// so it can never appear as a child here. An unboundedly deep counted graph is out of today's
12817/// scope, not silently mishandled.
12818///
12819/// Frees the data buffer (`cap` slots at 8 bytes each) and the 20-byte header, POISONing the header
12820/// first (see [`HEAP_POISON`]).
12821/// `[word 12] -> [counted]`: whether a header's class byte (the low byte of word 12) names a class
12822/// that carries a true holder count at word 16 ([`AllocClass::is_counted`]). A `Raw` block, a map
12823/// header (classified, never counted) and anything else answers 0 — none of them has a word 16 of its
12824/// own, so nothing may read or write one there. `class_local` is a free i32 local; it is left holding
12825/// the class byte.
12826fn emit_class_is_counted(c: &mut Vec<u8>, class_local: u32) {
12827    let mask: u32 = AllocClass::ALL
12828        .iter()
12829        .filter(|k| k.is_counted())
12830        .map(|k| 1u32 << k.code())
12831        .sum();
12832    let classes = AllocClass::ALL.len() as i32;
12833    i32_const(c, 0xFF);
12834    c.push(0x71); // i32.and → class
12835    local_tee(c, class_local);
12836    i32_const(c, classes);
12837    c.push(0x49); // i32.lt_u → a class this backend stamps
12838    i32_const(c, mask as i32);
12839    local_get(c, class_local);
12840    c.push(0x76); // i32.shr_u
12841    i32_const(c, 1);
12842    c.push(0x71); // i32.and → its bit in the counted mask
12843    c.push(0x71); // i32.and
12844}
12845
12846fn emit_exact_buffer_holds(
12847    code: &mut Vec<u8>,
12848    hdr: u32,
12849    i: u32,
12850    slot: u32,
12851    host: u32,
12852    cloning: bool,
12853) {
12854    local_get(code, hdr);
12855    i32_load(code, 12);
12856    i32_const(code, 0xff);
12857    code.push(0x71);
12858    i32_const(code, AllocClass::ExactIntegerHeader.code() as i32);
12859    code.extend([0x46, 0x04, 0x40]);
12860    i32_const(code, 0);
12861    local_set(code, i);
12862    code.extend([0x02, 0x40, 0x03, 0x40]);
12863    local_get(code, i);
12864    local_get(code, hdr);
12865    i32_load(code, 0);
12866    code.extend([0x4f, 0x0d]);
12867    leb_u32(code, 1);
12868    local_get(code, hdr);
12869    i32_load(code, 8);
12870    local_get(code, i);
12871    i32_const(code, 8);
12872    code.extend([0x6c, 0x6a]);
12873    local_tee(code, slot);
12874    i64_load(code, 0);
12875    code.push(0x42);
12876    leb_i64(code, 1);
12877    code.extend([0x83, 0xa7, 0x04, 0x40]);
12878    if cloning {
12879        local_get(code, slot);
12880    }
12881    local_get(code, slot);
12882    i64_load(code, 0);
12883    code.push(0x10);
12884    leb_u32(code, host);
12885    if cloning {
12886        i64_store(code, 0);
12887    }
12888    code.push(0x0b);
12889    local_get(code, i);
12890    i32_const(code, 1);
12891    code.push(0x6a);
12892    local_set(code, i);
12893    code.push(0x0c);
12894    leb_u32(code, 0);
12895    code.extend([0x0b, 0x0b, 0x0b]);
12896}
12897
12898fn emit_free_object_helper(env: &RuntimeEnv) -> Vec<u8> {
12899    let mut c = Vec::new();
12900    // locals: 1 = class, 2 = stride, 3 = flags/data, 4 = i, 5 = child, 6 = n, 7 = slot
12901    c.push(0x01);
12902    leb_u32(&mut c, 7);
12903    c.push(I32);
12904    local_get(&mut c, 0);
12905    c.push(0x04);
12906    c.push(0x40); // if handle != 0
12907    {
12908        local_get(&mut c, 0);
12909        i32_load(&mut c, 12);
12910        i32_const(&mut c, 0xFF);
12911        c.push(0x71); // i32.and → class
12912        local_set(&mut c, 1);
12913        emit_each_heap_child(&mut c, 0, [1, 2, 3, 4, 7], |c| {
12914            local_set(c, 5); // child
12915            local_get(c, 5);
12916            c.push(0x04);
12917            c.push(0x40); // if child != 0
12918            {
12919                local_get(c, 5);
12920                i32_load(c, 12);
12921                emit_class_is_counted(c, 6);
12922                c.push(0x04);
12923                c.push(0x40); // if the child's own class carries a true count
12924                {
12925                    local_get(c, 5);
12926                    local_get(c, 5);
12927                    i32_load(c, 16);
12928                    i32_const(c, 1);
12929                    c.push(0x6B); // n - 1
12930                    local_tee(c, 6);
12931                    i32_store(c, 16);
12932                    local_get(c, 6);
12933                    i32_const(c, 0);
12934                    c.push(0x4C); // i32.le_s → n <= 0
12935                    c.push(0x04);
12936                    c.push(0x40);
12937                    {
12938                        local_get(c, 5);
12939                        c.push(0x10); // call __logos_free_object(child) — recursion
12940                        leb_u32(c, env.call(RuntimeFn::FreeObject));
12941                    }
12942                    c.push(0x0B); // end if n<=0
12943                }
12944                c.push(0x0B); // end if class!=Raw
12945            }
12946            c.push(0x0B); // end if child!=0
12947        });
12948        if let Some(drop) = env.exact_drop {
12949            emit_exact_buffer_holds(&mut c, 0, 4, 7, drop, false);
12950        }
12951        // Free the data buffer — `emit_free_helper` no-ops a null ptr. A list's holds `cap` 8-byte
12952        // slots; a Text's holds `cap` bytes, unless it is an append's growable buffer, which other
12953        // views may still be reading: that loses one view, and goes with its last.
12954        local_get(&mut c, 1);
12955        i32_const(&mut c, AllocClass::TextHeader.code() as i32);
12956        c.push(0x46); // i32.eq
12957        c.push(0x04);
12958        c.push(0x40); // if a Text
12959        {
12960            local_get(&mut c, 0);
12961            i32_load(&mut c, 4);
12962            i32_const(&mut c, TEXT_GROWABLE);
12963            c.push(0x71);
12964            c.push(0x45); // i32.eqz → not growable
12965            c.push(0x04);
12966            c.push(0x40);
12967            {
12968                local_get(&mut c, 0);
12969                i32_load(&mut c, 8);
12970                local_get(&mut c, 0);
12971                i32_load(&mut c, 4);
12972                c.push(0x10);
12973                leb_u32(&mut c, env.call(RuntimeFn::Free));
12974            }
12975            c.push(0x05); // else: one view fewer reads the buffer; the last frees it
12976            {
12977                local_get(&mut c, 0);
12978                i32_load(&mut c, 8);
12979                i32_const(&mut c, 8);
12980                c.push(0x6B);
12981                local_set(&mut c, 3); // the buffer's base (its view count)
12982                local_get(&mut c, 3);
12983                local_get(&mut c, 3);
12984                i32_load(&mut c, 0);
12985                i32_const(&mut c, 1);
12986                c.push(0x6B);
12987                local_tee(&mut c, 6);
12988                i32_store(&mut c, 0);
12989                local_get(&mut c, 6);
12990                i32_const(&mut c, 0);
12991                c.push(0x4C); // i32.le_s → no view left
12992                c.push(0x04);
12993                c.push(0x40);
12994                {
12995                    local_get(&mut c, 3);
12996                    local_get(&mut c, 0);
12997                    i32_load(&mut c, 4);
12998                    i32_const(&mut c, i32::MAX);
12999                    c.push(0x71); // the capacity bytes
13000                    i32_const(&mut c, 8);
13001                    c.push(0x6A); // + the view count and mark words
13002                    c.push(0x10);
13003                    leb_u32(&mut c, env.call(RuntimeFn::Free));
13004                }
13005                c.push(0x0B);
13006            }
13007            c.push(0x0B);
13008        }
13009        c.push(0x05); // else: a list
13010        {
13011            local_get(&mut c, 0);
13012            i32_load(&mut c, 8);
13013            local_get(&mut c, 0);
13014            i32_load(&mut c, 4);
13015            i32_const(&mut c, 17);
13016            i32_const(&mut c, CRDT_RECORD_BYTES);
13017            i32_const(&mut c, 16);
13018            i32_const(&mut c, 9);
13019            i32_const(&mut c, 8);
13020            emit_class_has_field_kinds(&mut c, 1);
13021            c.push(0x1B);
13022            local_get(&mut c, 1);
13023            i32_const(&mut c, i32::from(AllocClass::MapScalarScalar.code()));
13024            c.push(0x4F);
13025            local_get(&mut c, 1);
13026            i32_const(&mut c, i32::from(AllocClass::MapHandleHandle.code()));
13027            c.push(0x4D);
13028            c.push(0x71);
13029            c.push(0x1B); // maps own 16-byte entries, sequences own 8-byte slots
13030            local_get(&mut c, 1);
13031            i32_const(&mut c, i32::from(AllocClass::CounterHeader.code()));
13032            c.push(0x46);
13033            c.push(0x1B); // counters own 24-byte replica records
13034            local_get(&mut c, 1);
13035            i32_const(&mut c, i32::from(AllocClass::ClosureHeader.code()));
13036            c.push(0x46);
13037            c.push(0x1B); // each capture has a value, a present flag, and an ownership byte
13038            c.push(0x6C);
13039            c.push(0x10);
13040            leb_u32(&mut c, env.call(RuntimeFn::Free));
13041        }
13042        c.push(0x0B);
13043        // POISON the header (word 0/4/8/16; word 0 is about to be overwritten by the free list
13044        // linkage regardless — see `HEAP_POISON`'s doc), then free the header itself (20 bytes).
13045        for off in [0u32, 4, 8, 16] {
13046            local_get(&mut c, 0);
13047            i32_const(&mut c, HEAP_POISON);
13048            i32_store(&mut c, off);
13049        }
13050        local_get(&mut c, 0);
13051        i32_const(&mut c, 20);
13052        c.push(0x10);
13053        leb_u32(&mut c, env.call(RuntimeFn::Free));
13054    }
13055    c.push(0x0B); // end outer if
13056    c.push(0x0B); // end function
13057    c
13058}
13059
13060/// `__logos_safepoint()` — run when the host's own re-entry depth returns to 0 (S8; the wiring that
13061/// calls this from `runtime.js`'s own depth tracking lands separately — a test/host driver calls it
13062/// directly today). Drains the ENTIRE turn-retained list into a local snapshot first (so a deferred
13063/// re-list from inside this very drain — S8's "count back to 1, listed once" — starts a fresh list
13064/// for the NEXT turn rather than being walked twice this one): each entry's count drops by exactly
13065/// 1 (the turn's own implicit hold ending); whatever reaches 0 is freed via
13066/// [`emit_free_object_helper`]. Nothing is freed anywhere else.
13067fn emit_safepoint_helper(env: &RuntimeEnv) -> Vec<u8> {
13068    let Some(base) = env.retain_base else {
13069        return vec![0x00, 0x0B];
13070    };
13071    let (ptr_g, len_g, cap_g) = (base, base + 1, base + 2);
13072    let mut c = Vec::new();
13073    // `__logos_safepoint` takes NO params: locals 0 = snapshot cap, 1 = snapshot ptr, 2 = snapshot
13074    // len, 3 = i, 4 = handle, 5 = n.
13075    c.push(0x01);
13076    leb_u32(&mut c, 6);
13077    c.push(I32);
13078    global_get(&mut c, ptr_g);
13079    local_set(&mut c, 1);
13080    global_get(&mut c, len_g);
13081    local_set(&mut c, 2);
13082    global_get(&mut c, cap_g);
13083    local_set(&mut c, 0); // the snapshot's capacity — what its buffer was allocated for
13084                          // reset the list to empty BEFORE processing — this buffer becomes the NEXT turn's own list; a
13085                          // deferred re-list mid-drain (`emit_true_release_helper` calling `__logos_turn_retain` again,
13086                          // reached only through a cascade this safepoint itself triggers — not expected today, since the
13087                          // cascade uses the unconditional `emit_free_object_helper` path, not the mid-turn one, but kept
13088                          // safe regardless) grows this fresh buffer rather than corrupting the snapshot being walked.
13089    i32_const(&mut c, 0);
13090    global_set(&mut c, ptr_g);
13091    i32_const(&mut c, 0);
13092    global_set(&mut c, len_g);
13093    i32_const(&mut c, 0);
13094    global_set(&mut c, cap_g);
13095    i32_const(&mut c, 0);
13096    local_set(&mut c, 3); // i
13097    c.push(0x02);
13098    c.push(0x40); // block $exit
13099    c.push(0x03);
13100    c.push(0x40); // loop $loop
13101    local_get(&mut c, 3);
13102    local_get(&mut c, 2);
13103    c.push(0x4E); // i32.ge_s → i >= snapshot len
13104    c.push(0x0D);
13105    leb_u32(&mut c, 1); // br_if $exit
13106    local_get(&mut c, 1);
13107    local_get(&mut c, 3);
13108    i32_const(&mut c, 4);
13109    c.push(0x6C);
13110    c.push(0x6A);
13111    i32_load(&mut c, 0);
13112    local_set(&mut c, 4); // handle
13113    local_get(&mut c, 4);
13114    c.push(0x04);
13115    c.push(0x40); // if handle != 0
13116    {
13117        local_get(&mut c, 4);
13118        local_get(&mut c, 4);
13119        i32_load(&mut c, 16);
13120        i32_const(&mut c, 1);
13121        c.push(0x6B); // n - 1
13122        local_tee(&mut c, 5);
13123        i32_store(&mut c, 16);
13124        local_get(&mut c, 5);
13125        i32_const(&mut c, 0);
13126        c.push(0x4C); // i32.le_s → n <= 0
13127        c.push(0x04);
13128        c.push(0x40);
13129        {
13130            local_get(&mut c, 4);
13131            c.push(0x10);
13132            leb_u32(&mut c, env.call(RuntimeFn::FreeObject));
13133        }
13134        c.push(0x0B); // end if
13135    }
13136    c.push(0x0B); // end if handle!=0
13137    local_get(&mut c, 3);
13138    i32_const(&mut c, 1);
13139    c.push(0x6A);
13140    local_set(&mut c, 3);
13141    c.push(0x0C);
13142    leb_u32(&mut c, 0); // br $loop
13143    c.push(0x0B); // end loop
13144    c.push(0x0B); // end block
13145                  // free the drained snapshot buffer itself (its slots are gone — every entry was consumed above),
13146                  // at the size it was allocated for, its capacity
13147    local_get(&mut c, 1);
13148    local_get(&mut c, 0);
13149    i32_const(&mut c, 4);
13150    c.push(0x6C);
13151    c.push(0x10);
13152    leb_u32(&mut c, env.call(RuntimeFn::Free));
13153    c.push(0x0B); // end function
13154    c
13155}
13156
13157/// `__logos_heap_census() -> i32` — CHECK-MODE ONLY, not part of a page's normal operation. Walks
13158/// every counted value reachable from the program's own globals and, for each one, INDEPENDENTLY
13159/// recomputes how many roots/slots point at it (a scratch array indexed by `(handle - heap_base) /
13160/// 8`, sized to the current heap and laid just above the bump pointer, outside the heap), then
13161/// compares that recomputed
13162/// in-degree to the block's own stored true count. Returns 0 when every reachable object's stored
13163/// count exactly equals its recomputed in-degree, or the address of the first mismatch otherwise.
13164///
13165/// Two full root-walks share one Rust closure (`visit`) rather than duplicating the traversal by
13166/// hand: the first increments the scratch slot for every handle visited, the second compares each
13167/// visited slot to its header's stored count, stopping at the first disagreement. The traversal
13168/// itself never needs to recurse more than one level (see [`emit_free_object_helper`]'s doc for why
13169/// a `HandleHeader`'s own elements cannot nest further this session).
13170fn emit_heap_census_visit_helper(env: &RuntimeEnv) -> Vec<u8> {
13171    let mut c = vec![0x01];
13172    // params: 0 = handle, 1 = scratch; locals 2..6 traverse children, 7 = cell, 8 = old count.
13173    leb_u32(&mut c, 7);
13174    c.push(I32);
13175    local_get(&mut c, 0);
13176    c.push(0x45);
13177    c.push(0x04);
13178    c.push(0x40);
13179    c.push(0x0F);
13180    c.push(0x0B);
13181    local_get(&mut c, 0);
13182    i32_load(&mut c, 12);
13183    emit_class_is_counted(&mut c, 2);
13184    c.push(0x45);
13185    c.push(0x04);
13186    c.push(0x40);
13187    c.push(0x0F);
13188    c.push(0x0B);
13189    local_get(&mut c, 1);
13190    local_get(&mut c, 0);
13191    i32_const(&mut c, env.heap_base);
13192    c.push(0x6B);
13193    i32_const(&mut c, 3);
13194    c.push(0x76);
13195    i32_const(&mut c, 4);
13196    c.push(0x6C);
13197    c.push(0x6A);
13198    local_tee(&mut c, 7);
13199    i32_load(&mut c, 0);
13200    local_set(&mut c, 8);
13201    local_get(&mut c, 7);
13202    local_get(&mut c, 8);
13203    i32_const(&mut c, 1);
13204    c.push(0x6A);
13205    i32_store(&mut c, 0);
13206    local_get(&mut c, 8);
13207    c.push(0x04);
13208    c.push(0x40);
13209    c.push(0x0F); // an already-visited container's owned edges were counted once
13210    c.push(0x0B);
13211    emit_each_heap_child(&mut c, 0, [2, 3, 4, 5, 6], |c| {
13212        local_get(c, 1);
13213        c.push(0x10);
13214        leb_u32(c, env.call(RuntimeFn::CensusVisit));
13215    });
13216    c.push(0x0B);
13217    c
13218}
13219
13220fn emit_heap_census_helper(env: &RuntimeEnv) -> Vec<u8> {
13221    let mut c = Vec::new();
13222    // locals: 0 = scratch_ptr, 1 = scratch_words, 2 = mismatch, 3 = handle, 4 = class, 5 = num,
13223    // 6 = data, 7 = i, 8 = child, 9 = slot, 10 = tmp
13224    c.push(0x01);
13225    leb_u32(&mut c, 11);
13226    c.push(I32);
13227    // scratch_words = (heap_ptr - heap_base) / 8 + 1, one per 8-byte slot of the heap. The scratch
13228    // sits just ABOVE the bump pointer, which never moves for it: the census observes the heap
13229    // without allocating in it, so it neither perturbs the layout it checks nor grows the heap it
13230    // will measure next time. Memory grows to cover it when it must.
13231    global_get(&mut c, env.heap_global);
13232    i32_const(&mut c, env.heap_base);
13233    c.push(0x6B);
13234    i32_const(&mut c, 3);
13235    c.push(0x76); // i32.shr_u → /8
13236    i32_const(&mut c, 1);
13237    c.push(0x6A);
13238    local_set(&mut c, 1); // scratch_words
13239    global_get(&mut c, env.heap_global);
13240    i32_const(&mut c, 7);
13241    c.push(0x6A);
13242    i32_const(&mut c, -8);
13243    c.push(0x71); // i32.and → 8-aligned
13244    local_set(&mut c, 0); // scratch_ptr
13245                          // tmp = scratch end; grow memory while it lies past the last page.
13246    local_get(&mut c, 0);
13247    local_get(&mut c, 1);
13248    i32_const(&mut c, 4);
13249    c.push(0x6C);
13250    c.push(0x6A);
13251    local_set(&mut c, 10);
13252    c.push(0x3F); // memory.size
13253    c.push(0x00);
13254    i32_const(&mut c, 16);
13255    c.push(0x74); // i32.shl → bytes
13256    local_get(&mut c, 10);
13257    c.push(0x49); // i32.lt_u → size < end
13258    c.push(0x04);
13259    c.push(0x40); // if
13260    {
13261        local_get(&mut c, 10);
13262        c.push(0x3F);
13263        c.push(0x00);
13264        i32_const(&mut c, 16);
13265        c.push(0x74);
13266        c.push(0x6B); // end - size
13267        i32_const(&mut c, 0xFFFF);
13268        c.push(0x6A);
13269        i32_const(&mut c, 16);
13270        c.push(0x76); // pages = ceil((end - size) / 64 KiB)
13271        c.push(0x40); // memory.grow
13272        c.push(0x00);
13273        i32_const(&mut c, -1);
13274        c.push(0x46); // i32.eq
13275        c.push(0x04);
13276        c.push(0x40); // if the grow failed: the allocator's own out-of-memory report
13277        {
13278            i32_const(&mut c, 4);
13279            c.push(0x42);
13280            c.push(0x00); // i64.const 0
13281            c.push(0x10);
13282            leb_u32(&mut c, env.fail_at);
13283            c.push(0x00); // unreachable
13284        }
13285        c.push(0x0B);
13286    }
13287    c.push(0x0B);
13288    // Zero the scratch before the walk, and again after it: the bump allocator hands out the memory
13289    // above its pointer on the promise that it is zero.
13290    let zero_scratch = |c: &mut Vec<u8>| {
13291        i32_const(c, 0);
13292        local_set(c, 9); // i (the zero-loop counter; its "slot" role is only inside the walk)
13293        c.push(0x02);
13294        c.push(0x40);
13295        c.push(0x03);
13296        c.push(0x40);
13297        local_get(c, 9);
13298        local_get(c, 1);
13299        c.push(0x4E);
13300        c.push(0x0D);
13301        leb_u32(c, 1);
13302        local_get(c, 0);
13303        local_get(c, 9);
13304        i32_const(c, 4);
13305        c.push(0x6C);
13306        c.push(0x6A);
13307        i32_const(c, 0);
13308        i32_store(c, 0);
13309        local_get(c, 9);
13310        i32_const(c, 1);
13311        c.push(0x6A);
13312        local_set(c, 9);
13313        c.push(0x0C);
13314        leb_u32(c, 0);
13315        c.push(0x0B);
13316        c.push(0x0B);
13317    };
13318    zero_scratch(&mut c);
13319
13320    for (i, kind) in env.global_kinds.iter().enumerate() {
13321        if counted_kind(*kind) {
13322            global_get(&mut c, i as u32);
13323            local_get(&mut c, 0);
13324            c.push(0x10);
13325            leb_u32(&mut c, env.call(RuntimeFn::CensusVisit));
13326        }
13327    }
13328
13329    if let Some(base) = env.callback_base {
13330        global_get(&mut c, base);
13331        local_set(&mut c, 7);
13332        c.extend([0x02, 0x40, 0x03, 0x40]);
13333        local_get(&mut c, 7);
13334        c.push(0x45);
13335        c.push(0x0D);
13336        leb_u32(&mut c, 1);
13337        local_get(&mut c, 7);
13338        i32_load(&mut c, 4);
13339        local_get(&mut c, 0);
13340        c.push(0x10);
13341        leb_u32(&mut c, env.call(RuntimeFn::CensusVisit));
13342        local_get(&mut c, 7);
13343        i32_load(&mut c, 8);
13344        local_set(&mut c, 7);
13345        c.push(0x0C);
13346        leb_u32(&mut c, 0);
13347        c.extend([0x0B, 0x0B]);
13348    }
13349    // Compare every visited object once. A zero scratch cell is not an object we reached.
13350    i32_const(&mut c, 0);
13351    local_set(&mut c, 9);
13352    c.push(0x02);
13353    c.push(0x40);
13354    c.push(0x03);
13355    c.push(0x40);
13356    local_get(&mut c, 9);
13357    local_get(&mut c, 1);
13358    c.push(0x4F);
13359    c.push(0x0D);
13360    leb_u32(&mut c, 1);
13361    local_get(&mut c, 0);
13362    local_get(&mut c, 9);
13363    i32_const(&mut c, 4);
13364    c.push(0x6C);
13365    c.push(0x6A);
13366    i32_load(&mut c, 0);
13367    local_tee(&mut c, 10);
13368    c.push(0x04);
13369    c.push(0x40);
13370    local_get(&mut c, 9);
13371    i32_const(&mut c, 8);
13372    c.push(0x6C);
13373    i32_const(&mut c, env.heap_base);
13374    c.push(0x6A);
13375    local_tee(&mut c, 3);
13376    i32_load(&mut c, 16);
13377    local_get(&mut c, 10);
13378    c.push(0x47);
13379    c.push(0x04);
13380    c.push(0x40);
13381    local_get(&mut c, 3);
13382    local_set(&mut c, 2);
13383    c.push(0x0C);
13384    leb_u32(&mut c, 3);
13385    c.push(0x0B);
13386    c.push(0x0B);
13387    local_get(&mut c, 9);
13388    i32_const(&mut c, 1);
13389    c.push(0x6A);
13390    local_set(&mut c, 9);
13391    c.push(0x0C);
13392    leb_u32(&mut c, 0);
13393    c.push(0x0B);
13394    c.push(0x0B);
13395    zero_scratch(&mut c);
13396    local_get(&mut c, 2);
13397    c.push(0x0B); // end function
13398    c
13399}
13400
13401/// What a heap-resident block IS, for the census a later step reads out of the low byte of its
13402/// header's word 12 (packed `count:24 | class:8` — see the design record in `heap.md`'s S7 entry).
13403/// Only ever stamped on a 16-byte `[len/num][cap][data_ptr][count|class]` header, never on a raw data
13404/// buffer or anything smaller: those stay [`AllocClass::Raw`], which is the zeroed default every
13405/// fresh OR freshly-reused block already starts at (`__logos_free` zeroes word 12 on any block of at
13406/// least 16 bytes; a never-freed bump block is zero from instantiation) — so a `Raw` classification
13407/// costs no emitted store at all.
13408///
13409/// Records, heterogeneous tuples, and enums carry ownership bytes alongside their slots.
13410/// This separates scalar payload bits from child handles during retain, release, and census.
13411/// Raw value layouts outside this protocol remain part of the reclamation audit.
13412#[derive(Clone, Copy, PartialEq, Eq, Debug)]
13413enum AllocClass {
13414    /// A raw byte/word buffer or a value layout outside the counted-header protocol.
13415    /// The allocator writes no header for this class.
13416    Raw,
13417    /// A 16-byte collection header whose `data_ptr` buffer holds ONLY scalar 8-byte slots (`Seq of
13418    /// Int/Float/Bool`, plain `Set`) — nothing in it for a census to recurse into.
13419    ScalarHeader,
13420    /// A 16-byte collection header whose `data_ptr` buffer holds ONLY handle slots, one per 8 bytes
13421    /// (`Seq of Text`/of a record, `Set of Text`) — a census walks every slot up to `len`.
13422    HandleHeader,
13423    /// A 16-byte Map header: `data_ptr` holds 16-byte key/value pairs; both sides scalar.
13424    MapScalarScalar,
13425    /// A Map header whose key is scalar and whose value is a handle.
13426    MapScalarHandle,
13427    /// A Map header whose key is a handle and whose value is scalar.
13428    MapHandleScalar,
13429    /// A Map header whose key AND value are both handles.
13430    MapHandleHandle,
13431    /// A `Text` header: `data_ptr` holds `cap` raw bytes (or, with the growable bit in `cap`, a
13432    /// buffer an append may share with other views of it). Counted (S12): a Text is freed at a
13433    /// safepoint once nothing holds it, like a list.
13434    TextHeader,
13435    /// A record's fields occupy 8-byte slots followed by one ownership byte per field.
13436    /// The byte is 1 for a handle and 0 for a scalar; numeric bits are never read as pointers.
13437    RecordHeader,
13438    /// An enum keeps its tag at word 0 and its payload length at word 4; payloads have field-kind bytes.
13439    EnumHeader,
13440    /// A counter owns scalar replica records, each three eight-byte words.
13441    CounterHeader,
13442    /// A closure records its function index, capture count, and typed capture buffer.
13443    ClosureHeader,
13444    /// An integer buffer owns one tagged host value per eight-byte slot (a record cell has length one).
13445    ExactIntegerHeader,
13446}
13447
13448impl AllocClass {
13449    const ALL: [AllocClass; 13] = [
13450        AllocClass::Raw,
13451        AllocClass::ScalarHeader,
13452        AllocClass::HandleHeader,
13453        AllocClass::MapScalarScalar,
13454        AllocClass::MapScalarHandle,
13455        AllocClass::MapHandleScalar,
13456        AllocClass::MapHandleHandle,
13457        AllocClass::TextHeader,
13458        AllocClass::RecordHeader,
13459        AllocClass::EnumHeader,
13460        AllocClass::CounterHeader,
13461        AllocClass::ClosureHeader,
13462        AllocClass::ExactIntegerHeader,
13463    ];
13464
13465    /// The byte a census reads back. `Raw` is 0, the same value dead/zeroed memory already carries —
13466    /// see the type doc for why that means `Raw` needs no emitted store.
13467    fn code(self) -> u8 {
13468        match self {
13469            AllocClass::Raw => 0,
13470            AllocClass::ScalarHeader => 1,
13471            AllocClass::HandleHeader => 2,
13472            AllocClass::MapScalarScalar => 3,
13473            AllocClass::MapScalarHandle => 4,
13474            AllocClass::MapHandleScalar => 5,
13475            AllocClass::MapHandleHandle => 6,
13476            AllocClass::TextHeader => 7,
13477            AllocClass::RecordHeader => 8,
13478            AllocClass::EnumHeader => 9,
13479            AllocClass::CounterHeader => 10,
13480            AllocClass::ClosureHeader => 11,
13481            AllocClass::ExactIntegerHeader => 12,
13482        }
13483    }
13484
13485    /// A collection's class from whether its elements are handles — `Set`/`Seq` share this rule
13486    /// (their `Kind` alone says which; see `kind::Kind::is_seq`'s siblings).
13487    fn of_elements(elements_are_handles: bool) -> AllocClass {
13488        if elements_are_handles {
13489            AllocClass::HandleHeader
13490        } else {
13491            AllocClass::ScalarHeader
13492        }
13493    }
13494
13495    /// A Map's class from its key/value handle-ness (see `lower_map_insert`, which is the only site
13496    /// that reliably knows both — an empty map's eventual key/value kind is not yet chosen).
13497    fn of_map(key_is_handle: bool, value_is_handle: bool) -> AllocClass {
13498        match (key_is_handle, value_is_handle) {
13499            (false, false) => AllocClass::MapScalarScalar,
13500            (false, true) => AllocClass::MapScalarHandle,
13501            (true, false) => AllocClass::MapHandleScalar,
13502            (true, true) => AllocClass::MapHandleHandle,
13503        }
13504    }
13505
13506    /// Which words of each slot of this block's data buffer hold a handle the block keeps:
13507    /// `(word 0, word 8)`. A sequence's slot is its 8-byte element; a map's is its 16-byte
13508    /// `[key][value]` entry.
13509    fn held_handles(self) -> (bool, bool) {
13510        match self {
13511            AllocClass::HandleHeader
13512            | AllocClass::MapHandleScalar
13513            | AllocClass::RecordHeader
13514            | AllocClass::EnumHeader
13515            | AllocClass::ClosureHeader => (true, false),
13516            AllocClass::MapScalarHandle => (false, true),
13517            AllocClass::MapHandleHandle => (true, true),
13518            AllocClass::Raw
13519            | AllocClass::ScalarHeader
13520            | AllocClass::MapScalarScalar
13521            | AllocClass::TextHeader
13522            | AllocClass::CounterHeader
13523            | AllocClass::ExactIntegerHeader => (false, false),
13524        }
13525    }
13526
13527    /// Whether the header has a true holder count at word 16 and participates in the
13528    /// turn-retained worklist and free-at-zero cascade. Empty maps are counted before insertion.
13529    fn is_counted(self) -> bool {
13530        matches!(
13531            self,
13532            AllocClass::ScalarHeader
13533                | AllocClass::HandleHeader
13534                | AllocClass::TextHeader
13535                | AllocClass::MapScalarScalar
13536                | AllocClass::MapScalarHandle
13537                | AllocClass::MapHandleScalar
13538                | AllocClass::MapHandleHandle
13539                | AllocClass::RecordHeader
13540                | AllocClass::EnumHeader
13541                | AllocClass::CounterHeader
13542                | AllocClass::ClosureHeader
13543                | AllocClass::ExactIntegerHeader
13544        )
13545    }
13546}
13547
13548/// Kinds whose standalone representation participates in true retain/release ownership.
13549/// Register roots, globals, captures, and container stores use this independently of COW:
13550/// immutable values still need to live until their last holder releases them.
13551/// Unresolved SeqAny and the remaining raw layouts require separate reclamation work.
13552fn counted_kind(k: Option<Kind>) -> bool {
13553    matches!(
13554        k,
13555        Some(Kind::SeqInt)
13556            | Some(Kind::SeqBool)
13557            | Some(Kind::SeqFloat)
13558            | Some(Kind::SeqWord32)
13559            | Some(Kind::SeqWord64)
13560            | Some(Kind::SeqText)
13561            | Some(Kind::SeqStruct)
13562            | Some(Kind::SeqEnum)
13563            | Some(Kind::SeqSeqInt)
13564            | Some(Kind::SeqHandle)
13565            | Some(Kind::Set)
13566            | Some(Kind::SetText)
13567            | Some(Kind::CrdtSetText)
13568            | Some(Kind::Text)
13569            | Some(Kind::Map)
13570            | Some(Kind::Struct)
13571            | Some(Kind::Tuple)
13572            | Some(Kind::Enum)
13573            | Some(Kind::Rational)
13574            | Some(Kind::CrdtCounter)
13575            | Some(Kind::Closure)
13576    )
13577}
13578
13579/// Whether a value of this `Kind`, held in a SLOT (a map's value, a future struct/tuple field, a
13580/// `Seq`/`Set` element), is an `i32` HANDLE to a separate heap object rather than a plain scalar
13581/// embedded in the slot itself. Exhaustive on purpose — an unmatched kind is a compile error, not a
13582/// silently-wrong guess, the way `k.wasm_valtype() == I32` alone would be: [`Kind::Date`] and
13583/// [`Kind::Word32`] are BOTH `i32`-valtype SCALARS (a day count, a wrapping ring word), the only two
13584/// exceptions to "i32 valtype means handle" in the whole enum.
13585///
13586/// The nine kinds documented "LINKER MODE ONLY" (`BigInt`/`Complex`/`Modular`/`Decimal`/`Money`/
13587/// `Quantity`/`Uuid`/`LanesV`/`Dynamic`) never reach a SELF-CONTAINED module at all, so their answer
13588/// here is moot — [`emit_alloc`] never stamps a class in linker mode regardless. They are still
13589/// matched by name, not `_`, so a kind added to the enum later cannot silently fall through unnoticed.
13590fn kind_is_handle(k: Kind) -> bool {
13591    match k {
13592        Kind::Nothing
13593        | Kind::Int
13594        | Kind::Bool
13595        | Kind::Char
13596        | Kind::Float
13597        | Kind::Date
13598        | Kind::Moment
13599        | Kind::Duration
13600        | Kind::Time
13601        | Kind::Span
13602        | Kind::Word32
13603        | Kind::Word64 => false,
13604        Kind::SeqInt
13605        | Kind::SeqBool
13606        | Kind::SeqFloat
13607        | Kind::SeqText
13608        | Kind::SeqStruct
13609        | Kind::SeqEnum
13610        | Kind::SeqSeqInt
13611        | Kind::SeqHandle
13612        | Kind::SeqAny
13613        | Kind::SeqWord32
13614        | Kind::SeqWord64
13615        | Kind::Text
13616        | Kind::Struct
13617        | Kind::Map
13618        | Kind::Set
13619        | Kind::SetText
13620        | Kind::CrdtSetText
13621        | Kind::CrdtCounter
13622        | Kind::Enum
13623        | Kind::Closure
13624        | Kind::Tuple
13625        | Kind::Rational
13626        | Kind::Optional
13627        | Kind::Lanes
13628        | Kind::BigInt
13629        | Kind::Complex
13630        | Kind::Modular
13631        | Kind::Decimal
13632        | Kind::Money
13633        | Kind::Quantity
13634        | Kind::Uuid
13635        | Kind::LanesV
13636        | Kind::Dynamic
13637        | Kind::Tower => true,
13638    }
13639}
13640
13641/// The class a freshly-created EMPTY collection header should carry, from its OWN `Kind` (the
13642/// register the header's handle is bound to — `Op::NewEmptyList`/`NewEmptySet`/a CRDT set/seq). A
13643/// `Kind::Map` or an unresolved [`Kind::SeqAny`] (refined by its first `Push`/insert) is empty and
13644/// inert either way, so `Raw` is exact, not merely safe, until that first write — see
13645/// `lower_map_insert` for a map's real, insert-time classification.
13646fn empty_collection_class(kind: Option<Kind>) -> AllocClass {
13647    match kind {
13648        // An empty map has no entries to scan; the first insert refines this class.
13649        // Its header must already carry a count before that insert.
13650        Some(Kind::Map) => AllocClass::MapScalarScalar,
13651        Some(Kind::SeqInt)
13652        | Some(Kind::SeqBool)
13653        | Some(Kind::SeqFloat)
13654        | Some(Kind::SeqWord32)
13655        | Some(Kind::SeqWord64)
13656        | Some(Kind::Set) => AllocClass::ScalarHeader,
13657        Some(Kind::SeqText)
13658        | Some(Kind::SeqStruct)
13659        | Some(Kind::SeqEnum)
13660        | Some(Kind::SeqSeqInt)
13661        | Some(Kind::SeqHandle)
13662        | Some(Kind::SetText)
13663        | Some(Kind::CrdtSetText) => AllocClass::HandleHeader,
13664        _ => AllocClass::Raw,
13665    }
13666}
13667
13668/// Every allocation site names its `AllocClass` explicitly — `wasm_alloc_site_lock::
13669/// every_allocation_site_is_classified` census-checks the source for exactly that.
13670fn emit_alloc(code: &mut Vec<u8>, ctx: &Ctx, dst_scratch: u32, class: AllocClass) {
13671    // stack: [size]
13672    if let Some(rt_alloc) = ctx.rt_alloc {
13673        // LINKER MODE: each block comes straight from the runtime allocator (`dlmalloc`, which grows
13674        // linear memory on demand), so the emitter heap is UNBOUNDED — a program allocating past any fixed
13675        // slab can't run off the end or collide with the runtime's region. The census/class scheme is a
13676        // self-contained-heap concern only (Tristen's ruling); `dlmalloc`'s blocks carry no class byte.
13677        code.push(0x10); // call logos_rt_alloc(size)
13678        leb_u32(code, rt_alloc);
13679        local_set(code, dst_scratch); // dst_scratch = ptr
13680    } else if let Some(alloc) = ctx.runtime.and_then(|r| r.index(RuntimeFn::Alloc)) {
13681        // Self-contained: `__logos_alloc(size)` — the free list first, then the bump.
13682        //
13683        // S8: a COUNTED class (`AllocClass::is_counted`) is born a true holder count of 1, credited
13684        // to THE TURN (the caller of whatever lowered op reaches this point) — so its header is 4
13685        // bytes wider than its class alone would need, requested here (before the call) rather than
13686        // at every one of this class's ~dozen call sites, and the fresh block is immediately listed
13687        // on the turn's retained list so a safepoint before it is ever stored anywhere durable still
13688        // frees it. Gated on `ctx.heap_counting()` (an interactive, self-contained, heap-using
13689        // module) so a batch module — which never runs a safepoint at all — pays nothing extra.
13690        let counted = class.is_counted() && ctx.heap_counting();
13691        if counted {
13692            i32_const(code, 4);
13693            code.push(0x6A); // i32.add — the header grows by exactly the new count word
13694        }
13695        code.push(0x10); // call
13696        leb_u32(code, alloc);
13697        local_set(code, dst_scratch);
13698        if class != AllocClass::Raw {
13699            local_get(code, dst_scratch);
13700            i32_const(code, class.code() as i32);
13701            i32_store(code, 12);
13702        }
13703        if counted {
13704            local_get(code, dst_scratch);
13705            i32_const(code, 1);
13706            i32_store(code, 16);
13707            if let Some(push) = ctx.runtime.and_then(|r| r.index(RuntimeFn::TurnRetain)) {
13708                local_get(code, dst_scratch);
13709                code.push(0x10);
13710                leb_u32(code, push);
13711            }
13712        }
13713    } else {
13714        // No heap helpers (a module that allocates nothing still reaches here harmlessly).
13715        global_get(code, ctx.heap_global);
13716        i32_const(code, 7);
13717        code.push(0x6A);
13718        i32_const(code, -8);
13719        code.push(0x71);
13720        local_tee(code, dst_scratch);
13721        code.push(0x6A);
13722        global_set(code, ctx.heap_global);
13723    }
13724}
13725
13726/// Give a block back. `ptr` and `size` are LOCALS; a no-op wherever the heap has no free list
13727/// (linker mode, where `dlmalloc` owns the memory and its `free` is not yet wired).
13728fn emit_free(
13729    code: &mut Vec<u8>,
13730    ctx: &Ctx,
13731    push_ptr: impl Fn(&mut Vec<u8>),
13732    push_size: impl Fn(&mut Vec<u8>),
13733) {
13734    let Some(free) = ctx.runtime.and_then(|r| r.index(RuntimeFn::Free)) else {
13735        return;
13736    };
13737    push_ptr(code);
13738    push_size(code);
13739    code.push(0x10); // call
13740    leb_u32(code, free);
13741}
13742
13743/// `Push value to seq` (Int sequence): append `value`, growing the data buffer when it is full and
13744/// updating the header in place (so the handle is stable).
13745///
13746/// ★ THE REFINEMENT THIS COMMENT USED TO PROMISE HAS LANDED. It said "O(n) per push — correctness
13747/// first; geometric capacity is a later refinement", and [`lower_list_push_at`] has tracked `cap`
13748/// and doubled for some time: a push with a slot free is O(1), and n pushes are O(n) in total. The
13749/// stale half sent a later reader (me) hunting an O(n²) that is not there. A comment that was true
13750/// once is not evidence.
13751fn lower_list_push(
13752    code: &mut Vec<u8>,
13753    kinds: &KindTable,
13754    ctx: &Ctx,
13755    num_regs: u32,
13756    list: u16,
13757    value: u16,
13758) -> R<()> {
13759    let elem =
13760        kinds
13761            .get(list as usize)
13762            .and_then(Kind::seq_elem)
13763            .ok_or(WasmLowerError::Unsupported(
13764                "push to a sequence of unknown element kind",
13765            ))?;
13766    lower_list_push_at(code, elem, ctx, num_regs, list as u32, value)
13767}
13768
13769/// The core of [`lower_list_push`], parameterized by the element kind and the LOCAL holding the seq
13770/// handle (rather than deriving them from a register) — so a struct FIELD seq (`ListPushField`, whose
13771/// handle lives in a struct slot, kind in the struct layout) can push through the same amortized path.
13772fn lower_list_push_at(
13773    code: &mut Vec<u8>,
13774    elem: Kind,
13775    ctx: &Ctx,
13776    num_regs: u32,
13777    lst: u32,
13778    value: u16,
13779) -> R<()> {
13780    // Int/Float/Text(handle) elements all occupy an 8-byte slot — only the load/store opcode differs.
13781    let elem_load = seq_elem_load(elem)?;
13782    let elem_store = seq_elem_store(elem)?;
13783    if let Some(push_slot) = ctx.runtime.and_then(|r| r.index(RuntimeFn::SeqPushSlot)) {
13784        if ctx.hot.get() {
13785            // In a loop ([`Ctx::hot`]): a push with room takes its slot inline; only a full buffer
13786            // calls the runtime to grow.
13787            let len = num_regs + 5;
13788            local_get(code, lst);
13789            i32_load(code, 0);
13790            local_tee(code, len);
13791            local_get(code, lst);
13792            i32_load(code, 4);
13793            code.push(0x48); // i32.lt_s → room
13794            code.push(0x04);
13795            code.push(I32);
13796            local_get(code, lst);
13797            local_get(code, len);
13798            i32_const(code, 1);
13799            code.push(0x6A);
13800            i32_store(code, 0); // len + 1
13801            local_get(code, lst);
13802            i32_load(code, 8);
13803            local_get(code, len);
13804            i32_const(code, 3);
13805            code.push(0x74); // i32.shl → len * 8
13806            code.push(0x6A);
13807            code.push(0x05);
13808            local_get(code, lst);
13809            code.push(0x10);
13810            leb_u32(code, push_slot);
13811            code.push(0x0B);
13812        } else {
13813            local_get(code, lst);
13814            code.push(0x10);
13815            leb_u32(code, push_slot);
13816        }
13817        local_get(code, value as u32);
13818        elem_store(code, 0);
13819        return Ok(());
13820    }
13821    // A linked module has no runtime of its own: the growth inline.
13822    let (hs_new, hs_i, hs_cap) = (num_regs + 5, num_regs + 6, num_regs + 7);
13823    // AMORTIZED growth. The header tracks `cap` (allocated element slots) alongside `len`; both
13824    // NewEmptyList (cap 0) and NewList (cap = count) set it to the true buffer size, so this stays
13825    // sound. When a slot is free we write in place (O(1)); otherwise we double the capacity, copy,
13826    // and repoint `data_ptr` — total work O(n) over n pushes, not the O(n²) a copy-every-push does
13827    // (which exhausts a small linear memory on a build-then-scan array like counting_sort's counts).
13828    //
13829    // if len < cap { in place } else { grow }
13830    local_get(code, lst);
13831    i32_load(code, 0); // len
13832    local_get(code, lst);
13833    i32_load(code, 4); // cap
13834    code.push(0x48); // i32.lt_s → len < cap
13835    code.push(0x04);
13836    code.push(0x40); // if (void)
13837    {
13838        // data_ptr + len*8 = value
13839        local_get(code, lst);
13840        i32_load(code, 8); // data_ptr
13841        local_get(code, lst);
13842        i32_load(code, 0); // len
13843        i32_const(code, 8);
13844        code.push(0x6C);
13845        code.push(0x6A); // data_ptr + len*8
13846        local_get(code, value as u32);
13847        elem_store(code, 0);
13848    }
13849    code.push(0x05); // else
13850    {
13851        // new_cap = cap == 0 ? 4 : cap * 2
13852        i32_const(code, 4);
13853        local_get(code, lst);
13854        i32_load(code, 4);
13855        i32_const(code, 2);
13856        code.push(0x6C); // cap * 2
13857        local_get(code, lst);
13858        i32_load(code, 4);
13859        code.push(0x45); // i32.eqz → cap == 0
13860        code.push(0x1B); // select → (cap==0) ? 4 : cap*2
13861        local_set(code, hs_cap);
13862        // new = alloc(new_cap * 8)
13863        local_get(code, hs_cap);
13864        i32_const(code, 8);
13865        code.push(0x6C);
13866        emit_alloc(code, ctx, hs_new, AllocClass::Raw);
13867        // for i in 0..len: new[i] = old[i]
13868        i32_const(code, 0);
13869        local_set(code, hs_i);
13870        code.push(0x02);
13871        code.push(0x40); // block $exit
13872        code.push(0x03);
13873        code.push(0x40); // loop $loop
13874        local_get(code, hs_i);
13875        local_get(code, lst);
13876        i32_load(code, 0); // len
13877        code.push(0x4E); // i32.ge_s → i >= len
13878        code.push(0x0D);
13879        leb_u32(code, 1); // br_if $exit
13880        local_get(code, hs_new);
13881        local_get(code, hs_i);
13882        i32_const(code, 8);
13883        code.push(0x6C);
13884        code.push(0x6A); // new + i*8
13885        local_get(code, lst);
13886        i32_load(code, 8); // old data_ptr
13887        local_get(code, hs_i);
13888        i32_const(code, 8);
13889        code.push(0x6C);
13890        code.push(0x6A); // old_data + i*8
13891        elem_load(code, 0);
13892        elem_store(code, 0); // new[i] = old[i]
13893        local_get(code, hs_i);
13894        i32_const(code, 1);
13895        code.push(0x6A);
13896        local_set(code, hs_i);
13897        code.push(0x0C);
13898        leb_u32(code, 0); // br $loop
13899        code.push(0x0B); // end loop
13900        code.push(0x0B); // end block
13901                         // new[len] = value
13902        local_get(code, hs_new);
13903        local_get(code, lst);
13904        i32_load(code, 0); // len
13905        i32_const(code, 8);
13906        code.push(0x6C);
13907        code.push(0x6A);
13908        local_get(code, value as u32);
13909        elem_store(code, 0);
13910        // ★ AND THE BUFFER THIS GROWTH LEAVES BEHIND GOES BACK TO THE ALLOCATOR. Read from the
13911        // header BEFORE it is repointed, so both the pointer and the size are still the old ones.
13912        // It is dead by construction: a data buffer belongs to exactly one header, this header is
13913        // about to stop pointing at it, and a shallow copy of the sequence shares the HEADER (so it
13914        // follows the new pointer too). No refcount is needed to know that, which is why this is
13915        // the first free the allocator gets — everything else waits for the release protocol.
13916        //
13917        // A `cap` of 0 means there is no buffer yet and `data_ptr` is null; the helper drops a null.
13918        emit_free(
13919            code,
13920            ctx,
13921            |c| {
13922                local_get(c, lst);
13923                i32_load(c, 8); // the OLD data_ptr
13924            },
13925            |c| {
13926                local_get(c, lst);
13927                i32_load(c, 4); // the OLD cap
13928                i32_const(c, 8);
13929                c.push(0x6C); // * 8 bytes an element
13930            },
13931        );
13932        // header: data_ptr = new
13933        local_get(code, lst);
13934        local_get(code, hs_new);
13935        i32_store(code, 8);
13936        // header: cap = new_cap
13937        local_get(code, lst);
13938        local_get(code, hs_cap);
13939        i32_store(code, 4);
13940    }
13941    code.push(0x0B); // end if
13942                     // header: len = len + 1
13943    local_get(code, lst);
13944    local_get(code, lst);
13945    i32_load(code, 0);
13946    i32_const(code, 1);
13947    code.push(0x6A);
13948    i32_store(code, 0);
13949    Ok(())
13950}
13951
13952/// `Pop from list into dst` (`ListPop`) — remove and return the last element. Mirror of
13953/// `list_pop`: load `data_ptr[(len-1)]` at the element width, then decrement the header `len`
13954/// (leaving `cap`/`data_ptr` intact — the slot is simply no longer live, exactly as `Vec::pop`
13955/// shrinks length without freeing). A source program never pops an empty list here: `resolve_program`
13956/// stops it first with the sentence naming the list. Hand-built bytecode can, and the guarded `else`
13957/// keeps the load in bounds and yields a typed zero.
13958fn lower_list_pop(code: &mut Vec<u8>, kinds: &KindTable, dst: u16, list: u16) -> R<()> {
13959    let elem =
13960        kinds
13961            .get(list as usize)
13962            .and_then(Kind::seq_elem)
13963            .ok_or(WasmLowerError::Unsupported(
13964                "pop from a sequence of unknown element kind",
13965            ))?;
13966    let elem_load = seq_elem_load(elem)?;
13967    let vt = elem.wasm_valtype();
13968    let lst = list as u32;
13969    // if len > 0 { dst = data_ptr[(len-1)*8]; len -= 1 } else { dst = <typed zero> }
13970    local_get(code, lst);
13971    i32_load(code, 0); // len
13972    i32_const(code, 0);
13973    code.push(0x4A); // i32.gt_s → len > 0
13974    code.push(0x04);
13975    code.push(vt); // if (result <element valtype>)
13976    {
13977        // data_ptr + (len-1)*8 → load the last element (left on the stack as the `if` result)
13978        local_get(code, lst);
13979        i32_load(code, 8); // data_ptr
13980        local_get(code, lst);
13981        i32_load(code, 0); // len
13982        i32_const(code, 1);
13983        code.push(0x6B); // i32.sub → len-1
13984        i32_const(code, 8);
13985        code.push(0x6C); // *8
13986        code.push(0x6A); // data_ptr + (len-1)*8
13987        elem_load(code, 0);
13988        // header: len = len - 1
13989        local_get(code, lst);
13990        local_get(code, lst);
13991        i32_load(code, 0);
13992        i32_const(code, 1);
13993        code.push(0x6B); // i32.sub
13994        i32_store(code, 0);
13995    }
13996    code.push(0x05); // else
13997    match vt {
13998        F64 => {
13999            code.push(0x44);
14000            code.extend_from_slice(&0.0f64.to_le_bytes());
14001        }
14002        I64 => {
14003            code.push(0x42);
14004            leb_i64(code, 0);
14005        }
14006        _ => i32_const(code, 0),
14007    }
14008    code.push(0x0B); // end if
14009    local_set(code, dst as u32);
14010    Ok(())
14011}
14012
14013/// Bounds-check a 1-based `index` into the Int sequence `collection` (trap on `index < 1` or
14014/// `index > len`, as the standalone module has no VM to surface the error), then leave the
14015/// element address `data_ptr + (index-1)*8` on the stack.
14016fn emit_seq_elem_addr(
14017    code: &mut Vec<u8>,
14018    ctx: &Ctx,
14019    kinds: &KindTable,
14020    collection: u16,
14021    index: u16,
14022) -> R<()> {
14023    // Every element (scalar OR handle) occupies an 8-byte slot, so the address arithmetic is the
14024    // same — only the caller's load/store width differs. A heterogeneous `Tuple` has the identical
14025    // header+slot layout (the caller picks the width from the static position kind).
14026    match kinds.get(collection as usize) {
14027        Some(Kind::Tuple) => {}
14028        other if other.and_then(Kind::seq_elem).is_some() => {}
14029        _ => {
14030            return Err(WasmLowerError::Unsupported(
14031                "index of a non-scalar sequence",
14032            ))
14033        }
14034    }
14035    let col = collection as u32;
14036    let slot = if ctx.hot.get() {
14037        None
14038    } else {
14039        ctx.runtime.and_then(|r| r.index(RuntimeFn::SeqSlot))
14040    };
14041    if let Some(slot) = slot {
14042        local_get(code, col);
14043        local_get(code, index as u32);
14044        code.push(0x10);
14045        leb_u32(code, slot);
14046        return Ok(());
14047    }
14048    // In a loop ([`Ctx::hot`]), or in a linked module (no runtime of its own): the check and the
14049    // address inline.
14050    // trap if index < 1 || index > len
14051    local_get(code, index as u32);
14052    code.push(0x42);
14053    leb_i64(code, 1);
14054    code.push(0x53); // i64.lt_s
14055    local_get(code, index as u32);
14056    local_get(code, col);
14057    i32_load(code, 0);
14058    code.push(0xAD); // len → i64
14059    code.push(0x55); // i64.gt_s
14060    code.push(0x72); // i32.or
14061    code.push(0x04);
14062    code.push(0x40); // if
14063                     // Say WHICH index, in the reference tier's own words. There is no message constant to hand
14064                     // over here — the sentence needs the value, which only exists now — so the module reports the
14065                     // CODE and the VALUE and the host renders it through `semantics::failcode::message`, the one
14066                     // definition the interpreter also formats with.
14067    if let Some(fail_at) = (ctx.host_index)(HostFn::LogosRtFailAt) {
14068        i32_const(
14069            code,
14070            crate::semantics::failcode::FailCode::IndexOutOfBounds.code(),
14071        );
14072        local_get(code, index as u32);
14073        code.push(0x10); // call logos_rt_fail_at(code, value)
14074        leb_u32(code, fail_at);
14075    }
14076    code.push(0x00); // unreachable
14077    code.push(0x0B); // end
14078                     // address = data_ptr + (index-1)*8
14079    local_get(code, col);
14080    i32_load(code, 8); // data_ptr
14081    local_get(code, index as u32);
14082    code.push(0x42);
14083    leb_i64(code, 1);
14084    code.push(0x7D); // i64.sub
14085    code.push(0xA7); // i32.wrap_i64
14086    i32_const(code, 8);
14087    code.push(0x6C); // i32.mul
14088    code.push(0x6A); // i32.add
14089    Ok(())
14090}
14091
14092/// The element kind of the sequence in `collection` (Int or Float), for load/store width.
14093fn seq_elem_kind(kinds: &KindTable, collection: u16) -> R<Kind> {
14094    kinds
14095        .get(collection as usize)
14096        .and_then(Kind::seq_elem)
14097        .ok_or(WasmLowerError::Unsupported(
14098            "sequence of unknown element kind",
14099        ))
14100}
14101
14102/// The load opcode for a sequence element of `elem` kind: `Float` → `f64`, `Int`/`Bool`/`Moment` →
14103/// `i64`, a heap kind (`Text`/`Struct`/…) → `i32` (the handle in the slot's low word). Each slot is
14104/// 8 bytes regardless (so the `i64`-stride `emit_seq_copy`/`emit_seq_elem_addr` are kind-agnostic).
14105fn seq_elem_load(elem: Kind) -> R<fn(&mut Vec<u8>, u32)> {
14106    Ok(match elem.wasm_valtype() {
14107        F64 => f64_load,
14108        I64 => i64_load,
14109        _ => i32_load,
14110    })
14111}
14112
14113/// The store opcode mirroring [`seq_elem_load`].
14114fn seq_elem_store(elem: Kind) -> R<fn(&mut Vec<u8>, u32)> {
14115    Ok(match elem.wasm_valtype() {
14116        F64 => f64_store,
14117        I64 => i64_store,
14118        _ => i32_store,
14119    })
14120}
14121
14122/// `item index of seq` / `item N of tuple` — load the (bounds-checked) element at its kind's width.
14123/// For a heterogeneous `Tuple` the width is the constant position's element kind, which is the
14124/// inferred kind of `dst` (resolved via the `tuple_value` track); otherwise it's the seq element.
14125fn lower_index(
14126    code: &mut Vec<u8>,
14127    ctx: &Ctx,
14128    kinds: &KindTable,
14129    dst: u16,
14130    collection: u16,
14131    index: u16,
14132) -> R<()> {
14133    let elem = if kinds.get(collection as usize) == Some(Kind::Tuple) {
14134        kinds
14135            .get(dst as usize)
14136            .ok_or(WasmLowerError::Unsupported("tuple element of unknown kind"))?
14137    } else {
14138        seq_elem_kind(kinds, collection)?
14139    };
14140    let load = seq_elem_load(elem)?;
14141    emit_seq_elem_addr(code, ctx, kinds, collection, index)?;
14142    load(code, 0);
14143    local_set(code, dst as u32);
14144    Ok(())
14145}
14146
14147/// `item index of text` — a one-character `Text` cut from `text` at the (1-based, bounds-checked)
14148/// BYTE position, matching the VM's ASCII fast path (`item i of "abc"` → `RuntimeValue::Text` of one
14149/// byte). A fresh 16-byte header + 1-byte data buffer holds the extracted byte; the result compares
14150/// to a literal (`item i of text equals " "`) through the existing `Text` byte-equality path. (A
14151/// multi-byte UTF-8 string would need a char decode to match the VM's general path — ASCII only here,
14152/// which is every string the corpus indexes.)
14153fn lower_text_index(
14154    code: &mut Vec<u8>,
14155    ctx: &Ctx,
14156    num_regs: u32,
14157    dst: u16,
14158    collection: u16,
14159    index: u16,
14160) -> R<()> {
14161    let (hdr, data) = (num_regs + 5, num_regs + 6);
14162    let col = collection as u32;
14163    // trap if index < 1 || index > byte_len
14164    local_get(code, index as u32);
14165    code.push(0x42);
14166    leb_i64(code, 1);
14167    code.push(0x53); // i64.lt_s → index < 1
14168    local_get(code, index as u32);
14169    local_get(code, col);
14170    i32_load(code, 0); // byte len
14171    code.push(0xAD); // i64.extend_i32_u
14172    code.push(0x55); // i64.gt_s → index > len
14173    code.push(0x72); // i32.or
14174    code.push(0x04);
14175    code.push(0x40); // if
14176    code.push(0x00); // unreachable
14177    code.push(0x0B); // end
14178                     // hdr = alloc(16); data = alloc(1)
14179    i32_const(code, 16);
14180    emit_alloc(code, ctx, hdr, AllocClass::TextHeader);
14181    i32_const(code, 1);
14182    emit_alloc(code, ctx, data, AllocClass::Raw);
14183    // data[0] = byte at (text.data_ptr + (index - 1))
14184    local_get(code, data); // store8 destination
14185    local_get(code, col);
14186    i32_load(code, 8); // text data_ptr
14187    local_get(code, index as u32);
14188    code.push(0x42);
14189    leb_i64(code, 1);
14190    code.push(0x7D); // i64.sub → index - 1
14191    code.push(0xA7); // i32.wrap_i64
14192    code.push(0x6A); // text data_ptr + (index - 1)
14193    i32_load8_u(code, 0);
14194    i32_store8(code, 0);
14195    // header: len = 1, cap = 1, data_ptr = data
14196    local_get(code, hdr);
14197    i32_const(code, 1);
14198    i32_store(code, 0);
14199    local_get(code, hdr);
14200    i32_const(code, 1);
14201    i32_store(code, 4);
14202    local_get(code, hdr);
14203    local_get(code, data);
14204    i32_store(code, 8);
14205    local_get(code, hdr);
14206    local_set(code, dst as u32);
14207    Ok(())
14208}
14209
14210/// Build a fresh `Seq of Int` from `len_reg` raw bytes at `base_reg` (each byte → one i64 element), the
14211/// emitter-heap `[len][cap][data_ptr]` seq with an i64 element buffer. Shared by `text_bytes` (a Text's
14212/// data_ptr) and `uuid_bytes` (the 16 bytes at a Uuid handle). Leaves the seq handle in `dst`.
14213fn emit_bytes_to_seq(
14214    code: &mut Vec<u8>,
14215    ctx: &Ctx,
14216    num_regs: u32,
14217    dst: u16,
14218    base_reg: u32,
14219    len_reg: u32,
14220) {
14221    let (hdr, data, i) = (num_regs + 7, num_regs + 8, num_regs + 9);
14222    i32_const(code, 16);
14223    emit_alloc(code, ctx, hdr, AllocClass::ScalarHeader); // always builds a `Seq of Int`
14224                                                          // data = alloc(len * 8) — one i64 element per byte.
14225    local_get(code, len_reg);
14226    i32_const(code, 8);
14227    code.push(0x6C); // i32.mul
14228    emit_alloc(code, ctx, data, AllocClass::Raw);
14229    // header: len = cap = len_reg, data_ptr = data
14230    local_get(code, hdr);
14231    local_get(code, len_reg);
14232    i32_store(code, 0);
14233    local_get(code, hdr);
14234    local_get(code, len_reg);
14235    i32_store(code, 4);
14236    local_get(code, hdr);
14237    local_get(code, data);
14238    i32_store(code, 8);
14239    // for i in 0..len { data[i] = (i64) base[i] }
14240    i32_const(code, 0);
14241    local_set(code, i);
14242    code.push(0x02);
14243    code.push(0x40); // block
14244    code.push(0x03);
14245    code.push(0x40); // loop
14246    local_get(code, i);
14247    local_get(code, len_reg);
14248    code.push(0x4E); // i32.ge_s
14249    code.push(0x0D);
14250    leb_u32(code, 1); // br_if block (done)
14251                      // dst addr = data + i*8
14252    local_get(code, data);
14253    local_get(code, i);
14254    i32_const(code, 8);
14255    code.push(0x6C); // i32.mul
14256    code.push(0x6A); // i32.add
14257                     // value = base[i] zero-extended to i64 (a byte is 0..255)
14258    local_get(code, base_reg);
14259    local_get(code, i);
14260    code.push(0x6A); // i32.add
14261    i32_load8_u(code, 0);
14262    code.push(0xAD); // i64.extend_i32_u
14263    i64_store(code, 0);
14264    local_get(code, i);
14265    i32_const(code, 1);
14266    code.push(0x6A); // i32.add
14267    local_set(code, i);
14268    code.push(0x0C);
14269    leb_u32(code, 0); // br loop
14270    code.push(0x0B); // end loop
14271    code.push(0x0B); // end block
14272    local_get(code, hdr);
14273    local_set(code, dst as u32);
14274}
14275
14276/// `text_bytes(text)` — the Text's UTF-8 bytes as a `Seq of Int`.
14277fn lower_text_bytes(code: &mut Vec<u8>, ctx: &Ctx, num_regs: u32, dst: u16, text: u16) {
14278    let (base, len) = (num_regs + 5, num_regs + 6);
14279    local_get(code, text as u32);
14280    i32_load(code, 8); // text data_ptr
14281    local_set(code, base);
14282    local_get(code, text as u32);
14283    i32_load(code, 0); // text byte len
14284    local_set(code, len);
14285    emit_bytes_to_seq(code, ctx, num_regs, dst, base, len);
14286}
14287
14288/// `uuid_bytes(u)` — the 16 raw bytes of a Uuid (the handle is a `Box<[u8; 16]>`, bytes at `*handle`).
14289fn lower_uuid_bytes(code: &mut Vec<u8>, ctx: &Ctx, num_regs: u32, dst: u16, uuid: u16) {
14290    let (base, len) = (num_regs + 5, num_regs + 6);
14291    local_get(code, uuid as u32);
14292    local_set(code, base);
14293    i32_const(code, 16);
14294    local_set(code, len);
14295    emit_bytes_to_seq(code, ctx, num_regs, dst, base, len);
14296}
14297
14298/// `text_from_bytes(seq)` — a `Text` from the low byte of each `Seq of Int` element.
14299/// Resolve the wasm function index of a compiled LOGOS function by name, checking that it has the
14300/// signature the caller intends to use — because "declarer wins" lets a program define its own
14301/// function of that name, and the loader then never splices the stdlib's. A compiler-written call
14302/// that lands on somebody else's function of the same name is worse than no call at all.
14303/// The signature is compared as WASM TYPES — the parameter valtypes and the result valtype — not as
14304/// `Kind` labels. A `-> Bool` may plan as `Kind::Int`: both ride an `i64`, the two collapse in the
14305/// register unifier wherever nothing observes the label, and a caller emitting `call` needs the
14306/// types to line up, not the names.
14307fn compiled_fn_by_name(ctx: &Ctx, name: &str, params: &[u8], result_valtype: u8) -> Option<u32> {
14308    let idx = ctx
14309        .functions
14310        .iter()
14311        .position(|f| ctx.interner.resolve(f.name) == name)?;
14312    if ctx.fn_param_valtypes.get(idx).map(Vec::as_slice) != Some(params) {
14313        return None;
14314    }
14315    if ctx.fn_inout.get(idx).is_some_and(|ps| !ps.is_empty()) {
14316        return None;
14317    }
14318    if ctx
14319        .fn_results
14320        .get(idx)
14321        .copied()
14322        .flatten()
14323        .map(Kind::wasm_valtype)
14324        != Some(result_valtype)
14325    {
14326        return None;
14327    }
14328    Some(ctx.fn_base + idx as u32)
14329}
14330
14331fn lower_text_from_bytes(
14332    code: &mut Vec<u8>,
14333    ctx: &Ctx,
14334    num_regs: u32,
14335    dst: u16,
14336    seq: u16,
14337) -> R<()> {
14338    // ★ THE ERROR-PARITY OBLIGATION. The tree-walker and the VM raise `text_from_bytes(): invalid
14339    // UTF-8` and the AOT tier panics with the same sentence, so a standalone module must TRAP —
14340    // that is `wasm_aot_lock::wasm_traps_where_treewalker_errors`, and this lowering used to be its
14341    // one violation: it copied the low byte of each element into linear memory and validated
14342    // nothing, so a browser answered U+FFFD where every other tier stopped.
14343    //
14344    // The rules are subtle — the 0xC2 floor, the 0xF4 ceiling, overlong forms, the surrogate hole —
14345    // and they are ALREADY WRITTEN, in LOGOS: `strings.lg`'s `validUtf8 (data: Seq of Int) -> Bool`
14346    // takes exactly the value this builtin is handed. So the module CALLS them rather than carrying
14347    // a second copy of the table to rot beside the first. `validUtf8` is demanded by the loader the
14348    // way `matchRoute` is (see `loader.rs`) — the BUILTIN is the reference, and the author never
14349    // types the name.
14350    let check = compiled_fn_by_name(ctx, crate::vm::reach::UTF8_VALIDATOR, &[I32], I64)
14351        .ok_or(WasmLowerError::Unsupported(
14352            "text_from_bytes cannot validate: `validUtf8 (data: Seq of Int) -> Bool` was not loaded. \
14353             The loader demands it whenever `text_from_bytes` is reachable (see `loader.rs`); if a \
14354             program declares its own `validUtf8` with another shape, that one wins and this refuses \
14355             rather than calling it.",
14356        ))?;
14357    // The callee becomes a second holder of the sequence, exactly as `Op::Call` treats every
14358    // heap argument. `validUtf8` only reads it — but that is a premise held in another file, and
14359    // an unnecessary copy-on-write is a cost while a missed one is a wrong answer.
14360    emit_retain(code, ctx, seq);
14361    local_get(code, seq as u32);
14362    code.push(0x10); // call validUtf8 → i64 (Bool)
14363    leb_u32(code, check);
14364    code.push(0x50); // i64.eqz — "not valid"
14365    code.push(0x04);
14366    code.push(0x40); // if
14367    if let Some(fail_at) = (ctx.host_index)(HostFn::LogosRtFailAt) {
14368        i32_const(
14369            code,
14370            crate::semantics::failcode::FailCode::InvalidUtf8.code(),
14371        );
14372        code.push(0x42);
14373        leb_i64(code, 0); // no value: the sentence needs none
14374        code.push(0x10); // call logos_rt_fail_at
14375        leb_u32(code, fail_at);
14376    }
14377    code.push(0x00); // unreachable
14378    code.push(0x0B); // end
14379    let (hdr, data, i, len, src) = (
14380        num_regs + 7,
14381        num_regs + 8,
14382        num_regs + 9,
14383        num_regs + 6,
14384        num_regs + 5,
14385    );
14386    local_get(code, seq as u32);
14387    i32_load(code, 0); // element count
14388    local_set(code, len);
14389    local_get(code, seq as u32);
14390    i32_load(code, 8); // seq data_ptr
14391    local_set(code, src);
14392    i32_const(code, 16);
14393    emit_alloc(code, ctx, hdr, AllocClass::TextHeader);
14394    local_get(code, len); // data = alloc(len) — one byte each
14395    emit_alloc(code, ctx, data, AllocClass::Raw);
14396    local_get(code, hdr);
14397    local_get(code, len);
14398    i32_store(code, 0);
14399    local_get(code, hdr);
14400    local_get(code, len);
14401    i32_store(code, 4);
14402    local_get(code, hdr);
14403    local_get(code, data);
14404    i32_store(code, 8);
14405    // for i in 0..len { data[i] = low byte of seq[i] (= src[i*8], little-endian) }
14406    i32_const(code, 0);
14407    local_set(code, i);
14408    code.push(0x02);
14409    code.push(0x40);
14410    code.push(0x03);
14411    code.push(0x40);
14412    local_get(code, i);
14413    local_get(code, len);
14414    code.push(0x4E);
14415    code.push(0x0D);
14416    leb_u32(code, 1);
14417    local_get(code, data);
14418    local_get(code, i);
14419    code.push(0x6A); // data + i
14420    local_get(code, src);
14421    local_get(code, i);
14422    i32_const(code, 8);
14423    code.push(0x6C);
14424    code.push(0x6A); // src + i*8
14425    if ctx.exact.sequence_ints() {
14426        i64_load(code, 0);
14427        exact::narrow_sequence_slot(code, ctx, num_regs, seq as u32)?;
14428        code.push(0xa7);
14429    } else {
14430        i32_load8_u(code, 0);
14431    }
14432    i32_store8(code, 0);
14433    local_get(code, i);
14434    i32_const(code, 1);
14435    code.push(0x6A);
14436    local_set(code, i);
14437    code.push(0x0C);
14438    leb_u32(code, 0);
14439    code.push(0x0B);
14440    code.push(0x0B);
14441    local_get(code, hdr);
14442    local_set(code, dst as u32);
14443    Ok(())
14444}
14445
14446/// `uuid_from_bytes(seq)` — pack the low byte of the first 16 `Seq of Int` elements into a contiguous
14447/// 16-byte block, then hand it to `logos_rt_uuid_from_ptr` to box a `base::Uuid` (LINKER MODE only).
14448fn lower_uuid_from_bytes(
14449    code: &mut Vec<u8>,
14450    ctx: &Ctx,
14451    num_regs: u32,
14452    dst: u16,
14453    seq: u16,
14454) -> R<Flow> {
14455    let from_ptr = (ctx.host_index)(HostFn::UuidFromPtr)
14456        .ok_or(WasmLowerError::Unsupported("uuid_from_ptr not imported"))?;
14457    let (block, i, src) = (num_regs + 7, num_regs + 9, num_regs + 5);
14458    local_get(code, seq as u32);
14459    i32_load(code, 8); // seq data_ptr
14460    local_set(code, src);
14461    i32_const(code, 16);
14462    emit_alloc(code, ctx, block, AllocClass::Raw);
14463    // for i in 0..16 { block[i] = low byte of seq[i] }
14464    i32_const(code, 0);
14465    local_set(code, i);
14466    code.push(0x02);
14467    code.push(0x40);
14468    code.push(0x03);
14469    code.push(0x40);
14470    local_get(code, i);
14471    i32_const(code, 16);
14472    code.push(0x4E);
14473    code.push(0x0D);
14474    leb_u32(code, 1);
14475    local_get(code, block);
14476    local_get(code, i);
14477    code.push(0x6A);
14478    local_get(code, src);
14479    local_get(code, i);
14480    i32_const(code, 8);
14481    code.push(0x6C);
14482    code.push(0x6A);
14483    i32_load8_u(code, 0);
14484    i32_store8(code, 0);
14485    local_get(code, i);
14486    i32_const(code, 1);
14487    code.push(0x6A);
14488    local_set(code, i);
14489    code.push(0x0C);
14490    leb_u32(code, 0);
14491    code.push(0x0B);
14492    code.push(0x0B);
14493    // dst = logos_rt_uuid_from_ptr(block)
14494    local_get(code, block);
14495    code.push(0x10);
14496    leb_u32(code, from_ptr);
14497    local_set(code, dst as u32);
14498    Ok(Flow::Straight)
14499}
14500
14501/// `lanes4Of(a, b, c, d)` — pack four `Word32` (i32) into a fresh 16-byte `[u32; 4]` lane block, lane
14502/// `i` at byte `i*4` (the `base::Lanes4Word32` layout the SHA-1 runtime reads).
14503fn lower_lanes4_of(code: &mut Vec<u8>, ctx: &Ctx, num_regs: u32, dst: u16, words: [u16; 4]) {
14504    let block = num_regs + 7;
14505    i32_const(code, 16);
14506    emit_alloc(code, ctx, block, AllocClass::Raw);
14507    for (i, w) in words.iter().enumerate() {
14508        local_get(code, block);
14509        local_get(code, *w as u32);
14510        i32_store(code, (i * 4) as u32);
14511    }
14512    local_get(code, block);
14513    local_set(code, dst as u32);
14514}
14515
14516/// `lanes4Word32(seq)` — pack the first four `Word32` elements of a `Seq of Word32` (each an i32 in the
14517/// low word of its 8-byte slot) into a lane block.
14518fn lower_lanes4_word32(code: &mut Vec<u8>, ctx: &Ctx, num_regs: u32, dst: u16, seq: u16) {
14519    let block = num_regs + 7;
14520    i32_const(code, 16);
14521    emit_alloc(code, ctx, block, AllocClass::Raw);
14522    for i in 0..4u32 {
14523        local_get(code, block);
14524        // value = seq.data_ptr[i] (i32 at data_ptr + i*8)
14525        local_get(code, seq as u32);
14526        i32_load(code, 8);
14527        i32_const(code, (i * 8) as i32);
14528        code.push(0x6A); // i32.add
14529        i32_load(code, 0);
14530        i32_store(code, i * 4);
14531    }
14532    local_get(code, block);
14533    local_set(code, dst as u32);
14534}
14535
14536/// `seqOfLanes4W32(lanes)` — unpack a lane block back into a fresh `Seq of Word32` (4 elements, each the
14537/// lane's i32 in the low word of an 8-byte slot).
14538fn lower_seq_of_lanes4(code: &mut Vec<u8>, ctx: &Ctx, num_regs: u32, dst: u16, lanes: u16) {
14539    let (hdr, data) = (num_regs + 7, num_regs + 8);
14540    i32_const(code, 16);
14541    emit_alloc(code, ctx, hdr, AllocClass::ScalarHeader); // `Seq of Word32` — scalar elements
14542    i32_const(code, 32); // 4 elements × 8-byte slots
14543    emit_alloc(code, ctx, data, AllocClass::Raw);
14544    local_get(code, hdr);
14545    i32_const(code, 4);
14546    i32_store(code, 0);
14547    local_get(code, hdr);
14548    i32_const(code, 4);
14549    i32_store(code, 4);
14550    local_get(code, hdr);
14551    local_get(code, data);
14552    i32_store(code, 8);
14553    for i in 0..4u32 {
14554        local_get(code, data);
14555        local_get(code, lanes as u32);
14556        i32_load(code, i * 4); // lane i
14557        i32_store(code, i * 8); // element i slot
14558    }
14559    local_get(code, hdr);
14560    local_set(code, dst as u32);
14561}
14562
14563/// The four SHA-1 SHA-NI ops — direct `logos_rt_sha1*` calls over lane-block handles. `Sha1Rnds4` also
14564/// takes the round-function selector (an `Int`, i64); the others are binary.
14565fn lower_sha1_op(
14566    code: &mut Vec<u8>,
14567    ctx: &Ctx,
14568    dst: u16,
14569    args_start: u16,
14570    host: HostFn,
14571    ternary: bool,
14572) -> R<Flow> {
14573    let idx = (ctx.host_index)(host).ok_or(WasmLowerError::Unsupported("sha1 op not imported"))?;
14574    local_get(code, args_start as u32);
14575    local_get(code, (args_start + 1) as u32);
14576    if ternary {
14577        local_get(code, (args_start + 2) as u32); // func selector (i64)
14578    }
14579    code.push(0x10);
14580    leb_u32(code, idx);
14581    local_set(code, dst as u32);
14582    Ok(Flow::Straight)
14583}
14584
14585/// `Set item index of seq to value` — store into the (bounds-checked) element.
14586fn lower_set_index(
14587    code: &mut Vec<u8>,
14588    ctx: &Ctx,
14589    kinds: &KindTable,
14590    num_regs: u32,
14591    collection: u16,
14592    index: u16,
14593    value: u16,
14594) -> R<()> {
14595    let elem = seq_elem_kind(kinds, collection)?;
14596    let store = seq_elem_store(elem)?;
14597    let elem_is_counted = counted_kind(Some(elem));
14598    let addr_local = num_regs + 5;
14599    emit_seq_elem_addr(code, ctx, kinds, collection, index)?; // [addr]
14600    if ctx.heap_counting() && elem_is_counted {
14601        local_tee(code, addr_local); // keep the address for the store below too
14602                                     // S8's true-count release: the element about to be OVERWRITTEN stops being held by this
14603                                     // slot right here — read as a plain i32 handle (this arm only runs for a `Seq`, never a
14604                                     // `Map`, and every counted element kind is `i32`-valtype by `kind_is_handle`'s own contract).
14605        i32_load(code, 0);
14606        emit_true_release(code, ctx, |_| {});
14607        local_get(code, addr_local);
14608    }
14609    local_get(code, value as u32); // [addr, value]
14610    store(code, 0);
14611    Ok(())
14612}
14613
14614/// `start to end` (inclusive Int range): bump-allocate a header + a `count`-element data buffer
14615/// and fill it with `start, start+1, …, end` (empty when `end < start`).
14616fn lower_new_range(code: &mut Vec<u8>, ctx: &Ctx, num_regs: u32, dst: u16, start: u16, end: u16) {
14617    let (hdr, data, idx) = (num_regs + 5, num_regs + 6, num_regs + 7); // i32 scratch
14618    let cnt = num_regs + 1; // reuse an i64 (pow) scratch
14619                            // cnt = max(0, end - start + 1)
14620    local_get(code, end as u32);
14621    local_get(code, start as u32);
14622    code.push(0x7D); // i64.sub
14623    code.push(0x42);
14624    leb_i64(code, 1);
14625    code.push(0x7C); // i64.add → end-start+1
14626    local_set(code, cnt);
14627    local_get(code, cnt);
14628    code.push(0x42);
14629    leb_i64(code, 0);
14630    code.push(0x53); // i64.lt_s
14631    code.push(0x04);
14632    code.push(0x40); // if (cnt < 0)
14633    code.push(0x42);
14634    leb_i64(code, 0);
14635    local_set(code, cnt); // cnt = 0
14636    code.push(0x0B);
14637    // header = alloc(16); data = alloc(cnt*8)
14638    i32_const(code, 16);
14639    emit_alloc(code, ctx, hdr, AllocClass::ScalarHeader); // a numeric range is always `Seq of Int`
14640    local_get(code, cnt);
14641    code.push(0xA7); // i32.wrap_i64
14642    i32_const(code, 8);
14643    code.push(0x6C); // i32.mul
14644    emit_alloc(code, ctx, data, AllocClass::Raw);
14645    // header: len, cap = cnt; data_ptr = data
14646    local_get(code, hdr);
14647    local_get(code, cnt);
14648    code.push(0xA7);
14649    i32_store(code, 0);
14650    local_get(code, hdr);
14651    local_get(code, cnt);
14652    code.push(0xA7);
14653    i32_store(code, 4);
14654    local_get(code, hdr);
14655    local_get(code, data);
14656    i32_store(code, 8);
14657    // for i in 0..cnt: data[i] = start + i
14658    i32_const(code, 0);
14659    local_set(code, idx);
14660    code.push(0x02);
14661    code.push(0x40); // block
14662    code.push(0x03);
14663    code.push(0x40); // loop
14664    local_get(code, idx);
14665    local_get(code, cnt);
14666    code.push(0xA7);
14667    code.push(0x4E); // i32.ge_s → i >= cnt
14668    code.push(0x0D);
14669    leb_u32(code, 1); // br_if exit
14670    local_get(code, data);
14671    local_get(code, idx);
14672    i32_const(code, 8);
14673    code.push(0x6C);
14674    code.push(0x6A); // data + i*8
14675    local_get(code, start as u32);
14676    local_get(code, idx);
14677    code.push(0xAC); // i64.extend_i32_s
14678    code.push(0x7C); // i64.add → start + i
14679    i64_store(code, 0);
14680    local_get(code, idx);
14681    i32_const(code, 1);
14682    code.push(0x6A);
14683    local_set(code, idx); // i++
14684    code.push(0x0C);
14685    leb_u32(code, 0); // br loop
14686    code.push(0x0B);
14687    code.push(0x0B); // end loop, end block
14688    local_get(code, hdr);
14689    local_set(code, dst as u32);
14690}
14691
14692/// `repeatSeq(x, n)` — a fresh `n`-element sequence, each slot a copy of the SCALAR `x` (the WASM
14693/// mirror of `[x] * n` / `n copies of x`). Bump-allocate a header + `n*8` data buffer and fill each
14694/// 8-byte slot with `x` in a runtime loop (`n < 0` → empty). Scalar element kinds only — a reference
14695/// element (whose per-slot copy must be an INDEPENDENT deep copy) defers to the VM.
14696fn lower_repeat_seq(
14697    code: &mut Vec<u8>,
14698    kinds: &KindTable,
14699    ctx: &Ctx,
14700    num_regs: u32,
14701    dst: u16,
14702    args_start: u16,
14703) -> R<()> {
14704    let value = args_start; // the element x
14705    let n = args_start + 1; // the count (i64)
14706    let is_float = matches!(kinds.get(value as usize), Some(Kind::Float));
14707    if !matches!(
14708        kinds.get(value as usize),
14709        Some(Kind::Int) | Some(Kind::Float)
14710    ) {
14711        return Err(WasmLowerError::Unsupported(
14712            "repeatSeq of a non-scalar element (deep-copy)",
14713        ));
14714    }
14715    let (hdr, data, idx) = (num_regs + 5, num_regs + 6, num_regs + 7); // i32 scratch
14716    let cnt = num_regs + 1; // reuse an i64 (pow) scratch
14717                            // cnt = max(0, n)
14718    local_get(code, n as u32);
14719    local_set(code, cnt);
14720    local_get(code, cnt);
14721    code.push(0x42);
14722    leb_i64(code, 0);
14723    code.push(0x53); // i64.lt_s
14724    code.push(0x04);
14725    code.push(0x40); // if (cnt < 0)
14726    code.push(0x42);
14727    leb_i64(code, 0);
14728    local_set(code, cnt); // cnt = 0
14729    code.push(0x0B);
14730    // header = alloc(16); data = alloc(cnt*8)
14731    i32_const(code, 16);
14732    emit_alloc(code, ctx, hdr, AllocClass::ScalarHeader); // repeatSeq refuses a non-scalar element above
14733    local_get(code, cnt);
14734    code.push(0xA7); // i32.wrap_i64
14735    i32_const(code, 8);
14736    code.push(0x6C); // i32.mul
14737    emit_alloc(code, ctx, data, AllocClass::Raw);
14738    // header: len = cap = cnt; data_ptr = data
14739    local_get(code, hdr);
14740    local_get(code, cnt);
14741    code.push(0xA7);
14742    i32_store(code, 0);
14743    local_get(code, hdr);
14744    local_get(code, cnt);
14745    code.push(0xA7);
14746    i32_store(code, 4);
14747    local_get(code, hdr);
14748    local_get(code, data);
14749    i32_store(code, 8);
14750    // for i in 0..cnt: data[i] = value
14751    i32_const(code, 0);
14752    local_set(code, idx);
14753    code.push(0x02);
14754    code.push(0x40); // block
14755    code.push(0x03);
14756    code.push(0x40); // loop
14757    local_get(code, idx);
14758    local_get(code, cnt);
14759    code.push(0xA7);
14760    code.push(0x4E); // i32.ge_s → i >= cnt
14761    code.push(0x0D);
14762    leb_u32(code, 1); // br_if exit
14763    local_get(code, data);
14764    local_get(code, idx);
14765    i32_const(code, 8);
14766    code.push(0x6C);
14767    code.push(0x6A); // data + i*8
14768    local_get(code, value as u32);
14769    if is_float {
14770        f64_store(code, 0);
14771    } else {
14772        i64_store(code, 0);
14773    }
14774    local_get(code, idx);
14775    i32_const(code, 1);
14776    code.push(0x6A);
14777    local_set(code, idx); // i++
14778    code.push(0x0C);
14779    leb_u32(code, 0); // br loop
14780    code.push(0x0B);
14781    code.push(0x0B); // end loop, end block
14782    local_get(code, hdr);
14783    local_set(code, dst as u32);
14784    Ok(())
14785}
14786
14787/// `[e0, e1, …]` (list / homogeneous tuple literal): bump-allocate a header + a `count`-element data
14788/// buffer and store the registers `start..start+count` (unrolled, no loop — `count` is a compile
14789/// constant). Elements are Int, Float, or Text(handle); mixed-kind elements are rejected.
14790fn lower_new_list(
14791    code: &mut Vec<u8>,
14792    kinds: &KindTable,
14793    ctx: &Ctx,
14794    num_regs: u32,
14795    dst: u16,
14796    start: u16,
14797    count: u16,
14798) -> R<()> {
14799    let want = if count > 0 {
14800        kinds
14801            .get(start as usize)
14802            .ok_or(WasmLowerError::Unsupported(
14803                "list literal of unknown element kind",
14804            ))?
14805    } else {
14806        Kind::Int
14807    };
14808    let elem_store = seq_elem_store(want)?;
14809    for j in 0..count {
14810        if kinds.get((start + j) as usize) != Some(want) {
14811            return Err(WasmLowerError::Unsupported(
14812                "list literal with mixed element kinds",
14813            ));
14814        }
14815    }
14816    let (hdr, data) = (num_regs + 5, num_regs + 6);
14817    i32_const(code, 16);
14818    emit_alloc(
14819        code,
14820        ctx,
14821        hdr,
14822        AllocClass::of_elements(kind_is_handle(want)),
14823    );
14824    i32_const(code, i32::from(count) * 8);
14825    emit_alloc(code, ctx, data, AllocClass::Raw);
14826    // header: len = cap = count; data_ptr = data
14827    local_get(code, hdr);
14828    i32_const(code, i32::from(count));
14829    i32_store(code, 0);
14830    local_get(code, hdr);
14831    i32_const(code, i32::from(count));
14832    i32_store(code, 4);
14833    local_get(code, hdr);
14834    local_get(code, data);
14835    i32_store(code, 8);
14836    // data[j] = R[start+j]  (the store's offset field carries j*8)
14837    for j in 0..count {
14838        local_get(code, data);
14839        local_get(code, (start + j) as u32);
14840        elem_store(code, u32::from(j) * 8);
14841    }
14842    // S8's true count, when the ELEMENT kind is itself counted (a matrix literal `[[1,2],[3,4]]`'s
14843    // rows, a list of Texts): this fresh header is a brand-new holder of each element the moment the
14844    // literal is built. One walk of the header it just stamped, so a literal of a thousand elements
14845    // costs the code of one.
14846    if count > 0 && counted_kind(Some(want)) {
14847        emit_retain_children(code, ctx, hdr);
14848    }
14849    local_get(code, hdr);
14850    local_set(code, dst as u32);
14851    Ok(())
14852}
14853
14854/// `Let (a, b, …) be t` (`DestructureTuple`) — bind each destructured register `start + i` to tuple
14855/// slot `i`, loaded at that target's own width (`emit_slot_load` by the register's kind). Both a
14856/// heterogeneous tuple and a homogeneous one (which rides a `SeqX`) lay their elements out at 8-byte
14857/// slots, so `data_ptr + i*8` is the slot address in both.
14858fn lower_destructure_tuple(
14859    code: &mut Vec<u8>,
14860    kinds: &KindTable,
14861    src: u16,
14862    start: u16,
14863    count: u16,
14864) -> R<()> {
14865    for i in 0..count {
14866        let dst = start + i;
14867        local_get(code, src as u32);
14868        i32_load(code, 8); // data_ptr
14869        emit_slot_load(code, kinds.get(dst as usize), u32::from(i) * 8)?;
14870        local_set(code, dst as u32);
14871    }
14872    Ok(())
14873}
14874
14875/// A HETEROGENEOUS tuple `(a, b, …)` — like [`lower_new_list`] but each slot stores its element at
14876/// that element's OWN width (`emit_slot_store` by the register's kind); `item N of t` reads it back
14877/// at the matching width. Header `[len][cap][data_ptr]`, `len = cap = count`.
14878fn lower_new_tuple_het(
14879    code: &mut Vec<u8>,
14880    kinds: &KindTable,
14881    ctx: &Ctx,
14882    num_regs: u32,
14883    dst: u16,
14884    start: u16,
14885    count: u16,
14886) -> R<()> {
14887    let (hdr, data) = (num_regs + 5, num_regs + 6);
14888    i32_const(code, 16);
14889    emit_alloc(code, ctx, hdr, AllocClass::RecordHeader);
14890    i32_const(
14891        code,
14892        i32::from(count) * if ctx.heap_counting() { 9 } else { 8 },
14893    );
14894    emit_alloc(code, ctx, data, AllocClass::Raw);
14895    for (off, v) in [(0u32, i32::from(count)), (4, i32::from(count))] {
14896        local_get(code, hdr);
14897        i32_const(code, v);
14898        i32_store(code, off);
14899    }
14900    local_get(code, hdr);
14901    local_get(code, data);
14902    i32_store(code, 8);
14903    for j in 0..count {
14904        local_get(code, data);
14905        local_get(code, (start + j) as u32);
14906        emit_slot_store(code, kinds.get((start + j) as usize), u32::from(j) * 8)?;
14907        if ctx.heap_counting() {
14908            local_get(code, data);
14909            i32_const(
14910                code,
14911                i32::from(kinds.get((start + j) as usize).is_some_and(kind_is_handle)),
14912            );
14913            i32_store8(code, u32::from(count) * 8 + u32::from(j));
14914        }
14915    }
14916    local_get(code, hdr);
14917    local_set(code, dst as u32);
14918    Ok(())
14919}
14920
14921/// Turn the enum handle on the stack into the address its payload slots are read from: a standalone
14922/// enum's data buffer (its header holds the pointer at 8), or the linked object itself, whose payload
14923/// follows the inline tag. [`enum_payload_offset`] gives each payload's byte offset from it.
14924fn emit_enum_payload_base(code: &mut Vec<u8>, ctx: &Ctx) {
14925    if !ctx.linked {
14926        i32_load(code, 8);
14927    }
14928}
14929
14930/// The byte offset of payload `index` from the address [`emit_enum_payload_base`] leaves.
14931fn enum_payload_offset(ctx: &Ctx, index: u32) -> u32 {
14932    8 * (index + u32::from(ctx.linked))
14933}
14934
14935/// Construct an enum. A standalone EnumHeader keeps tag@0, payload length@4, data@8,
14936/// class@12, and (when counting) holders@16. The payload buffer has eight-byte values
14937/// followed by one ownership byte per value. Linked modules retain their inline-payload ABI.
14938fn lower_new_inductive(
14939    code: &mut Vec<u8>,
14940    kinds: &KindTable,
14941    ctx: &Ctx,
14942    num_regs: u32,
14943    dst: u16,
14944    ctor: u32,
14945    args_start: u16,
14946    count: u16,
14947) -> R<()> {
14948    let (hdr, data) = (num_regs + 5, num_regs + 6);
14949    if ctx.linked {
14950        // The linked runtime's enum ABI remains tag + inline payload.
14951        i32_const(code, 8 * (1 + i32::from(count)));
14952        emit_alloc(code, ctx, hdr, AllocClass::Raw);
14953        local_get(code, hdr);
14954        i32_const(code, ctor as i32);
14955        i32_store(code, 0);
14956        for k in 0..count {
14957            let arg = args_start + k;
14958            local_get(code, hdr);
14959            local_get(code, arg as u32);
14960            emit_slot_store(code, kinds.get(arg as usize), 8 * (1 + u32::from(k)))?;
14961        }
14962    } else {
14963        // A standalone enum has a counted header. The payload's kinds are kept separately
14964        // from its bits, so an integer payload can never impersonate a reference count.
14965        i32_const(code, 16);
14966        emit_alloc(code, ctx, hdr, AllocClass::EnumHeader);
14967        if count == 0 {
14968            i32_const(code, 0);
14969            local_set(code, data);
14970        } else {
14971            i32_const(
14972                code,
14973                i32::from(count) * if ctx.heap_counting() { 9 } else { 8 },
14974            );
14975            emit_alloc(code, ctx, data, AllocClass::Raw);
14976        }
14977        local_get(code, hdr);
14978        i32_const(code, ctor as i32);
14979        i32_store(code, 0);
14980        local_get(code, hdr);
14981        i32_const(code, i32::from(count));
14982        i32_store(code, 4);
14983        local_get(code, hdr);
14984        local_get(code, data);
14985        i32_store(code, 8);
14986        for k in 0..count {
14987            let arg = args_start + k;
14988            let kind = kinds.get(arg as usize);
14989            local_get(code, data);
14990            local_get(code, arg as u32);
14991            emit_slot_store(code, kind, u32::from(k) * 8)?;
14992            if ctx.heap_counting() {
14993                local_get(code, data);
14994                i32_const(code, i32::from(kind.is_some_and(kind_is_handle)));
14995                i32_store8(code, u32::from(count) * 8 + u32::from(k));
14996            }
14997        }
14998    }
14999    local_get(code, hdr);
15000    local_set(code, dst as u32);
15001    Ok(())
15002}
15003
15004/// Read a matched enum payload at its inferred value width. Standalone payloads live in
15005/// the header's data buffer; linked payloads follow the inline tag. Transparent Options
15006/// retain their existing value/sentinel representation.
15007fn lower_bind_arm(
15008    code: &mut Vec<u8>,
15009    kinds: &KindTable,
15010    ctx: &Ctx,
15011    dst: u16,
15012    target: u16,
15013    index: u16,
15014) -> R<()> {
15015    // ★ AN `Option` IS TRANSPARENT, so its payload is the value itself.
15016    //
15017    // `Expr::OptionSome { value }` compiles to `compile_expr_into(value, dst)` — `some 3` IS `3`,
15018    // with `nothing` as a sentinel — so an `Option` register never carries `Kind::Enum` and this
15019    // check refused every `Inspect` over one. That took out `{inspect}` in a `View:` and the
15020    // ordinary statement alike; `lgx_wasm_lock` proved the fault was the BACKEND's by showing
15021    // hand-written LOGOS failing identically, which is exactly the evidence that said where to fix
15022    // it. (`Inspect` over a `Result` always worked: a `Result` IS a real enum with real slots.)
15023    //
15024    // For the transparent encoding the bind is a copy of the same value at the same valtype — the
15025    // arm only runs on the matching variant, and `Some`'s single payload is the register itself.
15026    // Restricted to index 0 so a genuine multi-payload bind on a non-enum target is still refused
15027    // rather than silently reading the target as its own first field.
15028    //
15029    // ★ COMPARED BY VALTYPE, NOT BY KIND, and the first attempt got this wrong. The two registers
15030    // hold the SAME value, so what the copy needs is that they are the same wasm type — the `Kind`
15031    // LABELS can legitimately differ, because the unifier types the binding from its uses while the
15032    // scrutinee is typed from its construction. Demanding equal kinds refused the very case this
15033    // arm exists for and reported it as a backend gap.
15034    let target_kind = kinds.get(target as usize);
15035    if target_kind != Some(Kind::Enum) {
15036        // Gated to `I32` to agree with `lower_test_arm`: an `Option` whose arms cannot be told
15037        // apart must not have a binding lowered for it either, or the refusal moves from the test
15038        // to whatever the bound name is used for and stops naming the real reason.
15039        if index == 0
15040            && kinds.valtype(target as usize) == I32
15041            && kinds.valtype(target as usize) == kinds.valtype(dst as usize)
15042        {
15043            local_get(code, target as u32);
15044            local_set(code, dst as u32);
15045            return Ok(());
15046        }
15047        return Err(WasmLowerError::Unsupported(
15048            "payload binding on a non-enum target",
15049        ));
15050    }
15051    // A `When V (binds)` arm for a variant the target is NOT runs dead — the preceding `TestArm` +
15052    // `JumpIfFalse` skip it — and may bind an index past the actual variant's arity, so the bound
15053    // payload has no kind. The load never executes; default it to the `i64` the `None`-kind local is
15054    // declared as (`valtype`) so the slot load is merely valtype-consistent, not a refusal. (A live
15055    // bind always resolves a concrete kind from the construction site, so this only hits dead arms —
15056    // register splitting can isolate such a dead bind whose kind register-reuse formerly supplied.)
15057    let kind = kinds.get(dst as usize).or(Some(Kind::Int));
15058    local_get(code, target as u32);
15059    emit_enum_payload_base(code, ctx);
15060    emit_slot_load(code, kind, enum_payload_offset(ctx, u32::from(index)))?;
15061    local_set(code, dst as u32);
15062    Ok(())
15063}
15064
15065/// `(x) -> …` (`MakeClosure`) — bump-allocate the closure object `[func_idx:i32][value_k:i64 ×
15066/// cap_n][flag_k:i64 × cap_n]` and hand back its handle. `func_idx` (word 0) is the table slot
15067/// `CallValue` `call_indirect`s. Each capture's VALUE is snapshotted now — a global capture from
15068/// `GlobalGet`, a local one from its moved-into register `locals_start + local_k` — and its
15069/// present-FLAG is set to 1 (a wasm global is always initialized, so always "captured"). The body
15070/// reads value/flag back as trailing parameters (see [`plan_function`]).
15071/// The wasm valtype of function `func`'s capture `k` — a captured GLOBAL's kind (so a composite
15072/// handle stores/loads as `i32`), else `I64` (a captured local, or an unknown kind). `MakeClosure`'s
15073/// store, `CallValue`'s load, and the closure body's seeded signature all read it, so they agree.
15074fn capture_valtype(ctx: &Ctx, func: u16, k: usize) -> u8 {
15075    ctx.capture_kinds
15076        .get(func as usize)
15077        .and_then(|v| v.get(k))
15078        .copied()
15079        .flatten()
15080        .map(Kind::wasm_valtype)
15081        .unwrap_or(I64)
15082}
15083
15084fn lower_make_closure(
15085    code: &mut Vec<u8>,
15086    ctx: &Ctx,
15087    num_regs: u32,
15088    dst: u16,
15089    func: u16,
15090    locals_start: u16,
15091) -> R<()> {
15092    let caps = ctx
15093        .functions
15094        .get(func as usize)
15095        .map(|f| f.captures.as_slice())
15096        .ok_or(WasmLowerError::Unsupported("closure of unknown function"))?;
15097    let cap_n = caps.len() as u32;
15098    let hs = num_regs + 5;
15099    let data = num_regs + 6;
15100    i32_const(
15101        code,
15102        if ctx.linked {
15103            8 * (1 + 2 * cap_n) as i32
15104        } else {
15105            16
15106        },
15107    );
15108    emit_alloc(
15109        code,
15110        ctx,
15111        hs,
15112        if ctx.linked {
15113            AllocClass::Raw
15114        } else {
15115            AllocClass::ClosureHeader
15116        },
15117    );
15118    local_get(code, hs);
15119    i32_const(code, i32::from(func));
15120    i32_store(code, 0);
15121    if ctx.linked {
15122        local_get(code, hs);
15123        i32_const(code, 8);
15124        code.push(0x6A);
15125        local_set(code, data);
15126    } else {
15127        local_get(code, hs);
15128        i32_const(code, cap_n as i32);
15129        i32_store(code, 4);
15130        if cap_n != 0 {
15131            i32_const(code, (17 * cap_n) as i32);
15132            emit_alloc(code, ctx, data, AllocClass::Raw);
15133        } else {
15134            i32_const(code, 0);
15135            local_set(code, data);
15136        }
15137        local_get(code, hs);
15138        local_get(code, data);
15139        i32_store(code, 8);
15140    }
15141    let mut local_k = 0_u16;
15142    for (k, (_sym, global)) in caps.iter().enumerate() {
15143        local_get(code, data);
15144        match global {
15145            Some(gidx) => global_get(code, u32::from(*gidx)),
15146            None => {
15147                local_get(code, u32::from(locals_start + local_k));
15148                local_k += 1;
15149            }
15150        }
15151        let off = 8 * k as u32;
15152        match capture_valtype(ctx, func, k) {
15153            I32 => i32_store(code, off),
15154            F64 => f64_store(code, off),
15155            _ => i64_store(code, off),
15156        }
15157        local_get(code, data);
15158        i64c(code, 1);
15159        i64_store(code, 8 * cap_n + off);
15160        let kind = ctx
15161            .capture_kinds
15162            .get(func as usize)
15163            .and_then(|v| v.get(k))
15164            .copied()
15165            .flatten();
15166        if !ctx.linked {
15167            local_get(code, data);
15168            i32_const(code, i32::from(counted_kind(kind)));
15169            i32_store8(code, 16 * cap_n + k as u32);
15170        }
15171        if counted_kind(kind) {
15172            if let Some(f) = ctx.runtime.and_then(|r| r.index(RuntimeFn::Retain)) {
15173                match global {
15174                    Some(gidx) => global_get(code, u32::from(*gidx)),
15175                    None => local_get(code, u32::from(locals_start + local_k - 1)),
15176                }
15177                code.push(0x10);
15178                leb_u32(code, f);
15179            }
15180        }
15181    }
15182    local_get(code, hs);
15183    local_set(code, u32::from(dst));
15184    Ok(())
15185}
15186
15187/// `f(args)` (`CallValue`) — push the arguments, then (for a capturing closure) each capture's
15188/// stored value and present-flag, then the closure's function index (the table slot), and
15189/// `call_indirect` through the module's function table. The push order matches the callee body's
15190/// parameter layout `[args][values][flags]`. The static signature is the callee body's own type
15191/// (resolved via the closure's statically-traced construction site); a value result binds to `dst`.
15192fn lower_call_value(
15193    code: &mut Vec<u8>,
15194    plan: &Plan,
15195    ctx: &Ctx,
15196    pc: usize,
15197    dst: u16,
15198    callee: u16,
15199    args_start: u16,
15200    arg_count: u16,
15201) -> R<()> {
15202    let func =
15203        plan.structs
15204            .callee_func
15205            .get(pc)
15206            .copied()
15207            .flatten()
15208            .ok_or(WasmLowerError::Unsupported(
15209                "indirect call to a closure of unknown origin",
15210            ))?;
15211    let type_idx = *ctx
15212        .fn_type
15213        .get(func as usize)
15214        .ok_or(WasmLowerError::Unsupported(
15215            "closure call: unknown callee type",
15216        ))?;
15217    let cap_n = ctx
15218        .functions
15219        .get(func as usize)
15220        .map(|f| f.captures.len() as u32)
15221        .unwrap_or(0);
15222    for k in 0..arg_count {
15223        exact::push_closure_argument(code, plan, ctx, func, k, args_start + k)?;
15224    }
15225    // capture values (each at its own kind), then present flags, from the closure object
15226    for k in 0..cap_n {
15227        local_get(code, callee as u32);
15228        if !ctx.linked {
15229            i32_load(code, 8);
15230        }
15231        let off = u32::from(ctx.linked) * 8 + 8 * k;
15232        match capture_valtype(ctx, func, k as usize) {
15233            I32 => i32_load(code, off),
15234            F64 => f64_load(code, off),
15235            _ => i64_load(code, off),
15236        }
15237    }
15238    for k in 0..cap_n {
15239        local_get(code, callee as u32);
15240        if !ctx.linked {
15241            i32_load(code, 8);
15242        }
15243        i64_load(code, u32::from(ctx.linked) * 8 + 8 * cap_n + 8 * k);
15244    }
15245    // The callee body `func` is statically known here (an unresolvable origin was already refused), so
15246    // LINKER MODE emits a DIRECT `call` — no function table, no `call_indirect` type, and therefore no
15247    // element/table sections the reloc transform can't yet relocate. The self-contained path keeps the
15248    // fully-general `call_indirect` through the module's table.
15249    if ctx.linked {
15250        code.push(0x10); // call fn_base+func (direct)
15251        leb_u32(code, ctx.fn_base + func as u32);
15252    } else {
15253        local_get(code, callee as u32);
15254        i32_load(code, 0); // closure.func_idx = table slot
15255        code.push(0x11); // call_indirect
15256        leb_u32(code, type_idx);
15257        leb_u32(code, 0); // table 0
15258    }
15259    // Bind the result iff the callee returns one (else the call leaves nothing on the stack).
15260    if ctx
15261        .fn_results
15262        .get(func as usize)
15263        .copied()
15264        .flatten()
15265        .is_some()
15266    {
15267        exact::take_closure_result(code, plan, ctx, func, dst)?;
15268    }
15269    Ok(())
15270}
15271
15272/// The exported `__logos_call_closure(identity: i32, arg: i64) -> i64` callback bridge.
15273/// Counted modules resolve an opaque host-registration identity to its live closure before dispatch.
15274/// The closure records its function index and points to capture values followed by present flags.
15275/// Unknown or released identities trap, including after the allocator reuses their old storage.
15276/// Uncounted modules retain direct handles. Linked modules call statically resolved closure bodies.
15277fn emit_closure_trampoline(
15278    fns: &[Plan],
15279    program: &CompiledProgram,
15280    fn_types: &[u32],
15281    ctx: &Ctx,
15282    callback_base: Option<u32>,
15283) -> R<Vec<u8>> {
15284    let n = fns.len();
15285    let mut body = Vec::new();
15286    // Exact argument/result helpers own i64 locals 2 and 3; registration lookup uses its own i32.
15287    let registration = if fns.iter().any(exact::on) {
15288        body.extend_from_slice(&[0x02, 0x02, I64, 0x01, I32]);
15289        4
15290    } else {
15291        body.extend_from_slice(&[0x01, 0x01, I32]);
15292        2
15293    };
15294    if let Some(base) = callback_base {
15295        global_get(&mut body, base);
15296        local_set(&mut body, registration);
15297        body.extend([0x02, 0x40, 0x03, 0x40]);
15298        local_get(&mut body, registration);
15299        body.push(0x45);
15300        body.extend([0x04, 0x40, 0x00, 0x0B]); // unknown or released ticket traps
15301        local_get(&mut body, registration);
15302        i32_load(&mut body, 0);
15303        local_get(&mut body, 0);
15304        body.push(0x46);
15305        body.push(0x0D);
15306        leb_u32(&mut body, 1);
15307        local_get(&mut body, registration);
15308        i32_load(&mut body, 8);
15309        local_set(&mut body, registration);
15310        body.push(0x0C);
15311        leb_u32(&mut body, 0);
15312        body.extend([0x0B, 0x0B]);
15313        local_get(&mut body, registration);
15314        i32_load(&mut body, 4);
15315        local_set(&mut body, 0);
15316    }
15317    for _ in 0..=n {
15318        body.extend([0x02, 0x40]);
15319    }
15320    local_get(&mut body, 0);
15321    i32_load(&mut body, 0);
15322    body.push(0x0E);
15323    leb_u32(&mut body, n as u32);
15324    for i in 0..n as u32 {
15325        leb_u32(&mut body, i);
15326    }
15327    leb_u32(&mut body, n as u32);
15328    for fi in 0..n {
15329        body.push(0x0B); // end block → arm fi lands here
15330        emit_trampoline_arm(&mut body, fi, fns, program, fn_types, ctx)?;
15331    }
15332    body.push(0x0B); // end default block
15333    body.push(0x00); // unreachable: unknown func_idx
15334    body.push(0x0B); // end function
15335    Ok(body)
15336}
15337
15338/// One `br_table` arm: invoke closure `fi` with the event arg (local 1) and `fi`'s
15339/// captures loaded from the object at `handle` (local 0), then widen the result.
15340fn emit_trampoline_arm(
15341    body: &mut Vec<u8>,
15342    fi: usize,
15343    fns: &[Plan],
15344    program: &CompiledProgram,
15345    fn_types: &[u32],
15346    ctx: &Ctx,
15347) -> R<()> {
15348    let f = &program.functions[fi];
15349    let plan = &fns[fi];
15350    let param_count = f.param_count as usize;
15351    let cap_n = f.captures.len();
15352    // Only single-`Int` (`i64`) argument closures are callable through the fixed
15353    // trampoline signature; any other shape traps rather than mismatch its type.
15354    if param_count != 1 || plan.kinds.valtype(0) != I64 {
15355        body.push(0x00); // unreachable
15356        return Ok(());
15357    }
15358    // Push the event argument (the closure's sole user parameter), in its parameter's form.
15359    local_get(body, 1);
15360    exact::trampoline_argument(body, ctx, fi, 2)?;
15361    // Push each capture VALUE, then each present-FLAG — exactly as `lower_call_value`
15362    // frames a call to `fi`, but read from the object at `handle`.
15363    for k in 0..cap_n {
15364        local_get(body, 0);
15365        i32_load(body, 8);
15366        let off = 8 * k as u32;
15367        match plan.kinds.valtype(param_count + k) {
15368            v if v == I32 => i32_load(body, off),
15369            v if v == F64 => f64_load(body, off),
15370            _ => i64_load(body, off),
15371        }
15372    }
15373    for k in 0..cap_n {
15374        local_get(body, 0);
15375        i32_load(body, 8);
15376        i64_load(body, 8 * cap_n as u32 + 8 * k as u32);
15377    }
15378    // call_indirect `fi` through the table, using its real signature.
15379    local_get(body, 0);
15380    i32_load(body, 0); // func_idx = table slot
15381    body.push(0x11); // call_indirect
15382    leb_u32(body, fn_types[fi]);
15383    leb_u32(body, 0); // table 0
15384                      // Widen the closure's result to the trampoline's i64 (void → 0).
15385    match result_valtypes(plan.result).first().copied() {
15386        None => {
15387            body.push(0x42); // i64.const 0
15388            leb_i64(body, 0);
15389        }
15390        Some(v) if v == I64 => exact::trampoline_result(body, ctx, fi, 2, 3)?,
15391        Some(v) if v == I32 => body.push(0xAD), // i64.extend_i32_u
15392        Some(v) if v == F64 => body.push(0xBD), // i64.reinterpret_f64
15393        Some(_) => {}
15394    }
15395    body.push(0x0F); // return
15396    Ok(())
15397}
15398
15399/// Lower a DOM builtin to its `dom_*` host call: push `arg_count` argument
15400/// registers, `call` the host, then bind `dst` — the returned value for a
15401/// creator/getter, or Nothing (`0`) for an effect op whose host returns void.
15402
15403fn lower_dom_call(
15404    code: &mut Vec<u8>,
15405    ctx: &Ctx,
15406    dst: u16,
15407    host: HostFn,
15408    args_start: u16,
15409    arg_count: u16,
15410    returns_value: bool,
15411) -> R<Flow> {
15412    let idx = (ctx.host_index)(host).ok_or(WasmLowerError::Unsupported("dom host not imported"))?;
15413    for i in 0..arg_count {
15414        local_get(code, args_start as u32 + i as u32);
15415        if host
15416            .retained_params()
15417            .into_iter()
15418            .any(|kept| kept == usize::from(i))
15419        {
15420            if let Some(retain) = ctx.runtime.and_then(|r| r.index(RuntimeFn::ClosureRetain)) {
15421                code.push(0x10);
15422                leb_u32(code, retain);
15423            }
15424        }
15425    }
15426    // Registration exists before the host can synchronously invoke the callback.
15427    code.push(0x10);
15428    leb_u32(code, idx);
15429    if !returns_value {
15430        i32_const(code, 0);
15431    }
15432    local_set(code, dst as u32);
15433    Ok(Flow::Straight)
15434}
15435
15436/// `dispatchEntry(dispatcher, context, hook, node, event, value)` — the page's dispatcher entered
15437/// through its host (`dom_page_entry(node, event, value)`), which runs it as an entry of its
15438/// own and hears a failure through the page's failure door by the module's exports; the three
15439/// function indices are the bytecode tier's own. An entry that traps leaves the loop frames it had
15440/// pushed on the iterator stack, so the stack's top is put back to where it stood before it.
15441fn lower_dispatch_entry(
15442    code: &mut Vec<u8>,
15443    ctx: &Ctx,
15444    num_regs: u32,
15445    dst: u16,
15446    args_start: u16,
15447) -> R<Flow> {
15448    let idx = (ctx.host_index)(HostFn::DomPageEntry)
15449        .ok_or(WasmLowerError::Unsupported("dom host not imported"))?;
15450    let saved = num_regs + 5;
15451    if ctx.uses_iter {
15452        global_get(code, ctx.iter_global);
15453        local_set(code, saved);
15454    }
15455    for k in 3..6 {
15456        local_get(code, u32::from(args_start) + k);
15457    }
15458    code.push(0x10); // call
15459    leb_u32(code, idx);
15460    local_set(code, u32::from(dst));
15461    if ctx.uses_iter {
15462        local_get(code, saved);
15463        global_set(code, ctx.iter_global);
15464    }
15465    Ok(Flow::Straight)
15466}
15467
15468/// `storageGet(area, key)` — the host's answer, boxed as the `Optional` this backend represents
15469/// an `Option` with: `0` means `Nothing`, and anything else is a pointer to an 8-byte box holding
15470/// the present value (the same shape a non-blocking `Try to receive` produces).
15471///
15472/// ★ THE ABSENCE IS THE WHOLE POINT. A host that answered `""` for a missing key would make a
15473/// page unable to tell "nothing is saved" from "an empty string is saved" — and an empty draft is
15474/// exactly what a cleared form field stores. So the host answers handle `0` and this turns it
15475/// into a real `Nothing` that `Inspect` and `is none` can see.
15476fn lower_storage_get(
15477    code: &mut Vec<u8>,
15478    ctx: &Ctx,
15479    num_regs: u32,
15480    dst: u16,
15481    args_start: u16,
15482) -> R<Flow> {
15483    let idx = (ctx.host_index)(HostFn::StorageGet)
15484        .ok_or(WasmLowerError::Unsupported("storage_get host not imported"))?;
15485    let boxp = num_regs + 6; // i32 Optional box pointer
15486    let val = num_regs + 7; // i32 Text handle the host answered
15487    local_get(code, args_start as u32);
15488    local_get(code, args_start as u32 + 1);
15489    code.push(0x10); // call storage_get
15490    leb_u32(code, idx);
15491    local_set(code, val);
15492    local_get(code, val);
15493    code.push(0x45); // i32.eqz — was the key absent?
15494    code.push(0x04);
15495    code.push(0x40); // if (void)
15496    i32_const(code, 0);
15497    local_set(code, dst as u32); // Nothing
15498    code.push(0x05); // else
15499    i32_const(code, 8);
15500    emit_alloc(code, ctx, boxp, AllocClass::Raw);
15501    local_get(code, boxp);
15502    local_get(code, val);
15503    emit_slot_store(code, Some(Kind::Text), 0)?;
15504    local_get(code, boxp);
15505    local_set(code, dst as u32);
15506    code.push(0x0B); // end if
15507    Ok(Flow::Straight)
15508}
15509
15510/// Whether the environment sets the variable the Text in `args_start` names: `env_len` answers `-1`
15511/// for one it does not, so the Bool is `env_len(name) >= 0`.
15512fn lower_env_has(code: &mut Vec<u8>, ctx: &Ctx, dst: u16, args_start: u16) -> R<Flow> {
15513    let idx = (ctx.host_index)(HostFn::EnvLen)
15514        .ok_or(WasmLowerError::Unsupported("env_len host not imported"))?;
15515    local_get(code, args_start as u32);
15516    code.push(0x10); // call env_len
15517    leb_u32(code, idx);
15518    i32_const(code, 0);
15519    code.push(0x4E); // i32.ge_s
15520    code.push(0xAD); // i64.extend_i32_u → Bool
15521    local_set(code, dst as u32);
15522    Ok(Flow::Straight)
15523}
15524
15525/// The text of the variable the Text in `args_start` names, `""` when it is unset: the module sizes a
15526/// buffer by `env_len`, the host writes the bytes with `env_into`, and the module builds the Text
15527/// header over them — the shape `fmt_align_into` uses, so a linked module needs no allocator export.
15528fn lower_env_value(
15529    code: &mut Vec<u8>,
15530    ctx: &Ctx,
15531    num_regs: u32,
15532    dst: u16,
15533    args_start: u16,
15534) -> R<Flow> {
15535    let len_idx = (ctx.host_index)(HostFn::EnvLen)
15536        .ok_or(WasmLowerError::Unsupported("env_len host not imported"))?;
15537    let into_idx = (ctx.host_index)(HostFn::EnvInto)
15538        .ok_or(WasmLowerError::Unsupported("env_into host not imported"))?;
15539    let (hdr, data, len) = (num_regs + 5, num_regs + 6, num_regs + 7);
15540    // len = max(env_len(name), 0)
15541    local_get(code, args_start as u32);
15542    code.push(0x10); // call env_len
15543    leb_u32(code, len_idx);
15544    local_set(code, len);
15545    local_get(code, len);
15546    i32_const(code, 0);
15547    local_get(code, len);
15548    i32_const(code, 0);
15549    code.push(0x4A); // i32.gt_s
15550    code.push(0x1B); // select
15551    local_set(code, len);
15552    // data = alloc(len); the host writes the bytes and answers how many
15553    local_get(code, len);
15554    emit_alloc(code, ctx, data, AllocClass::Raw);
15555    local_get(code, data);
15556    local_get(code, args_start as u32);
15557    code.push(0x10); // call env_into
15558    leb_u32(code, into_idx);
15559    code.push(0x1A); // drop — the length the module sized the buffer by
15560    // hdr = alloc(16); header = [len, cap = len, data_ptr = data]
15561    i32_const(code, 16);
15562    emit_alloc(code, ctx, hdr, AllocClass::TextHeader);
15563    local_get(code, hdr);
15564    local_get(code, len);
15565    i32_store(code, 0);
15566    local_get(code, hdr);
15567    local_get(code, len);
15568    i32_store(code, 4);
15569    local_get(code, hdr);
15570    local_get(code, data);
15571    i32_store(code, 8);
15572    local_get(code, hdr);
15573    local_set(code, dst as u32);
15574    Ok(Flow::Straight)
15575}
15576
15577/// `storageGetOr(area, key, fallback)` — the stored Text handle, or the fallback's handle when
15578/// the host answers `0`. NO NEW IMPORT: it is `storage_get` and a test of the handle it answered.
15579///
15580/// This is how a lowering that must USE a stored value reads one. An `Option of Text` is a boxed
15581/// handle on this tier — its presence can be tested but its value cannot be taken out — so a
15582/// store's read-back goes through here and no Option crosses the boundary at all.
15583fn lower_storage_get_or(
15584    code: &mut Vec<u8>,
15585    ctx: &Ctx,
15586    num_regs: u32,
15587    dst: u16,
15588    args_start: u16,
15589) -> R<Flow> {
15590    let idx = (ctx.host_index)(HostFn::StorageGet)
15591        .ok_or(WasmLowerError::Unsupported("storage_get host not imported"))?;
15592    let val = num_regs + 7; // i32 Text handle the host answered
15593    local_get(code, args_start as u32);
15594    local_get(code, args_start as u32 + 1);
15595    code.push(0x10); // call storage_get
15596    leb_u32(code, idx);
15597    local_set(code, val);
15598    local_get(code, val);
15599    code.push(0x45); // i32.eqz — was the key absent?
15600    code.push(0x04);
15601    code.push(0x7F); // if (result i32)
15602    local_get(code, args_start as u32 + 2); // the fallback's handle
15603    code.push(0x05); // else
15604    local_get(code, val);
15605    code.push(0x0B); // end
15606    local_set(code, dst as u32);
15607    Ok(Flow::Straight)
15608}
15609
15610/// `it is Variant` (`TestArm`) — compare the target's tag (constructor constant index) against
15611/// `variant` (the same constant index for that name, by dedup) → Bool. An `i32.eq` on tags is the
15612/// VM's constructor-name string compare.
15613fn lower_test_arm(
15614    code: &mut Vec<u8>,
15615    kinds: &KindTable,
15616    ctx: &Ctx,
15617    dst: u16,
15618    target: u16,
15619    variant: u32,
15620) -> R<()> {
15621    // ★ A TRANSPARENT `Option` CARRIES NO TAG TO READ, so the enum path below is not merely
15622    // unhelpful for one — it is wrong in a way that VALIDATES. `some x` IS `x` (`vm/compiler.rs`:
15623    // `Expr::OptionSome { value } => compile_expr_into(value, dst)`), so an `Option of Text` reaches
15624    // here as a bare Text handle. `i32_load(target, 0)` then reads that Text object's own first
15625    // word as if it were a variant tag and compares it to a constant index. The types line up, the
15626    // module passes validation, and the arm chosen is arbitrary. That is the worst shape a backend
15627    // gap takes: a wrong answer with nothing to catch it.
15628    //
15629    // The reference tier's rule is presence, not tag (`machine.rs`'s `Op::TestArm`):
15630    // `RuntimeValue::Nothing` matches `None`, and anything else matches `Some`.
15631    let target_kind = kinds.get(target as usize);
15632    if target_kind != Some(Kind::Enum) {
15633        let name = match ctx.constants.get(variant as usize) {
15634            Some(Constant::Text(t)) => t.as_str(),
15635            _ => {
15636                return Err(WasmLowerError::Unsupported(
15637                    "an arm's variant name is not a Text constant",
15638                ))
15639            }
15640        };
15641        // ★ AND THE SENTINEL IS WHERE THIS STOPS. `nothing` lowers to the scalar `0`
15642        // (`Constant::Nothing` → `i64.const 0`), so for an `Option of Int` the value `some 0` and
15643        // `nothing` are the SAME BITS and no test can separate them. A heap handle cannot collide:
15644        // the bump allocator never hands out 0, so `!= 0` is exactly "present".
15645        //
15646        // So the handle kinds lower — which covers the case the VM's own comment calls
15647        // load-bearing, `Option of <record>` and `Option of Text`, the shape a middleware
15648        // `-> Option of Response` has — and a scalar payload is refused BY NAME rather than
15649        // answered with a coin flip. Closing that needs a boxed `Option` in the BYTECODE, which is
15650        // a representation change the tree-walker and VM share; it is not a wasm-local decision.
15651        if kinds.valtype(target as usize) != I32 {
15652            return Err(WasmLowerError::Unsupported(
15653                "`Inspect` over an `Option` of a scalar (Int/Bool/Float): `nothing` and `some 0` are \
15654                 the same bits in a compiled module, so the arms cannot be told apart. Inspect an \
15655                 `Option` of a record, of Text, or of a sequence — or use a `Result`, which carries a \
15656                 real tag.",
15657            ));
15658        }
15659        match name {
15660            "Some" | "None" => {
15661                local_get(code, target as u32);
15662                i32_const(code, 0);
15663                code.push(if name == "None" { 0x46 } else { 0x47 }); // i32.eq : i32.ne
15664                code.push(0xAD); // i64.extend_i32_u → Bool
15665                local_set(code, dst as u32);
15666                return Ok(());
15667            }
15668            _ => return Err(WasmLowerError::Unsupported(
15669                "a variant arm on a value that carries no variant tag — only `Some` and `None` \
15670                     match a transparent `Option`",
15671            )),
15672        }
15673    }
15674    local_get(code, target as u32);
15675    i32_load(code, 0); // tag
15676    i32_const(code, variant as i32);
15677    code.push(0x46); // i32.eq
15678    code.push(0xAD); // i64.extend_i32_u → Bool
15679    local_set(code, dst as u32);
15680    Ok(())
15681}
15682
15683/// Bump-allocate a zeroed 16-byte collection header `[len/num=0][cap=0][data_ptr=0]` and store its
15684/// handle in `dst` — the empty form of a sequence or a map (their element/entry shape differs only
15685/// at use, not at creation). `class` is the caller's best knowledge at THIS point: a Map passes
15686/// `Raw` regardless (its key/value handle-ness is only known at the first insert — see
15687/// `lower_map_insert`), harmless since an empty map's `len` is 0 either way.
15688fn emit_empty_header(code: &mut Vec<u8>, ctx: &Ctx, num_regs: u32, dst: u32, class: AllocClass) {
15689    if let Some(f) = ctx
15690        .rt_alloc
15691        .is_none()
15692        .then(|| ctx.runtime.and_then(|r| r.index(RuntimeFn::NewHeader)))
15693        .flatten()
15694    {
15695        i32_const(code, class.code() as i32);
15696        code.push(0x10);
15697        leb_u32(code, f);
15698        local_set(code, dst);
15699        return;
15700    }
15701    let hs = num_regs + 5;
15702    i32_const(code, 16);
15703    emit_alloc(code, ctx, hs, class);
15704    for off in [0u32, 4, 8] {
15705        local_get(code, hs);
15706        i32_const(code, 0);
15707        i32_store(code, off);
15708    }
15709    local_get(code, hs);
15710    local_set(code, dst);
15711}
15712
15713/// Allocate an empty sequence header plus its proof-sized element buffer.
15714/// Unlike the generic empty-header path, this preserves the shared fixed-size
15715/// proof in both linked and self-contained modules, so its pushes never grow.
15716fn emit_fixed_header(
15717    code: &mut Vec<u8>,
15718    ctx: &Ctx,
15719    num_regs: u32,
15720    dst: u32,
15721    class: AllocClass,
15722    capacity: u32,
15723) {
15724    let header = num_regs + 5;
15725    let data = num_regs + 6;
15726    i32_const(code, 16);
15727    emit_alloc(code, ctx, header, class);
15728    i32_const(code, (capacity as i64 * 8) as i32);
15729    emit_alloc(code, ctx, data, AllocClass::Raw);
15730    local_get(code, header);
15731    i32_const(code, 0);
15732    i32_store(code, 0);
15733    local_get(code, header);
15734    i32_const(code, capacity as i32);
15735    i32_store(code, 4);
15736    local_get(code, header);
15737    local_get(code, data);
15738    i32_store(code, 8);
15739    local_get(code, header);
15740    local_set(code, dst);
15741}
15742
15743/// Allocate an empty collection header plus a buffer sized by a runtime Int
15744/// capacity. Negative hints become zero; oversized hints clamp to the largest
15745/// representable linear-memory allocation for this element stride.
15746fn emit_capacity_header(
15747    code: &mut Vec<u8>,
15748    ctx: &Ctx,
15749    num_regs: u32,
15750    dst: u32,
15751    capacity: u32,
15752    class: AllocClass,
15753    stride: i32,
15754) {
15755    let header = num_regs + 5;
15756    let data = num_regs + 6;
15757    let cap = num_regs + 7;
15758    let limit = i32::MAX / stride;
15759
15760    local_get(code, capacity);
15761    code.push(0x42); // i64.const 0
15762    leb_i64(code, 0);
15763    code.push(0x55); // i64.gt_s
15764    code.push(0x04); // if (result i32)
15765    code.push(I32);
15766    local_get(code, capacity);
15767    code.push(0x42); // i64.const limit
15768    leb_i64(code, limit as i64);
15769    code.push(0x53); // i64.lt_s
15770    code.push(0x04); // if (result i32)
15771    code.push(I32);
15772    local_get(code, capacity);
15773    code.push(0xA7); // i32.wrap_i64
15774    code.push(0x05); // else
15775    i32_const(code, limit);
15776    code.push(0x0B); // end inner if
15777    code.push(0x05); // else
15778    i32_const(code, 0);
15779    code.push(0x0B); // end outer if
15780    local_set(code, cap);
15781
15782    i32_const(code, 16);
15783    emit_alloc(code, ctx, header, class);
15784    local_get(code, cap);
15785    i32_const(code, stride);
15786    code.push(0x6C); // i32.mul
15787    emit_alloc(code, ctx, data, AllocClass::Raw);
15788    local_get(code, header);
15789    i32_const(code, 0);
15790    i32_store(code, 0);
15791    local_get(code, header);
15792    local_get(code, cap);
15793    i32_store(code, 4);
15794    local_get(code, header);
15795    local_get(code, data);
15796    i32_store(code, 8);
15797    local_get(code, header);
15798    local_set(code, dst);
15799}
15800
15801/// COPY-ON-WRITE reference counting mirrors the VM's `Rc` so value semantics (`LOGOS_VALUE_SEMANTICS`,
15802/// now default-on in the tree-walker/VM) holds in native wasm. The 4th header word (offset 12, the
15803/// spare slot past `[len][cap][data_ptr]`) holds the count of EXTRA references beyond the owner in
15804/// bits 8–31 — so 0 means "uniquely owned": a header is born with its class byte and a zero count, and
15805/// `__logos_free` zeroes word 12 of every block it takes back, so a recycled header starts at zero too.
15806/// A `Call` argument RETAINS (`++`, gaining the callee's parameter as a second holder); a mutation op
15807/// checks the count and clones first when it is nonzero, so the write can't be seen through the other
15808/// holder. Outside a loop ([`Ctx::hot`]) the retain is a call to `__logos_share`; inside one it stays
15809/// inline, where a call would be paid per iteration.
15810fn emit_retain(code: &mut Vec<u8>, ctx: &Ctx, reg: u16) {
15811    if let Some(f) = (!ctx.hot.get())
15812        .then(|| ctx.runtime.and_then(|r| r.index(RuntimeFn::Share)))
15813        .flatten()
15814    {
15815        local_get(code, reg as u32);
15816        code.push(0x10);
15817        leb_u32(code, f);
15818        return;
15819    }
15820    emit_share_inline(code, |c| local_get(c, reg as u32));
15821}
15822
15823/// `extra_refs + 1` at word 12 of the header `push` leaves on the stack.
15824fn emit_share_inline(code: &mut Vec<u8>, push: impl Fn(&mut Vec<u8>)) {
15825    push(code);
15826    push(code);
15827    i32_load(code, 12);
15828    i32_const(code, 0x100); // extra_refs occupies bits 8-31; the class byte (bits 0-7) is untouched
15829    code.push(0x6A); // extra_refs + 1
15830    i32_store(code, 12);
15831}
15832
15833/// S8's true-count RETAIN: `call __logos_retain(reg)` — a NEW, second holder of a counted value at
15834/// a genuine heap-resident slot (a global, a `Seq`/`Set` element, a struct field, a closure
15835/// capture). Deliberately NOT the same call as [`emit_retain`] above (word 12, COW-only, gated on
15836/// [`cow_clonable`] — a narrower, register-aliasing concern this is not): this is gated on
15837/// [`counted_kind`] and a no-op module-wide when `!ctx.heap_counting()` (a batch/linked module).
15838fn emit_true_retain(code: &mut Vec<u8>, ctx: &Ctx, reg: u16) {
15839    emit_true_retain_of(code, ctx, |c| local_get(c, reg as u32));
15840}
15841
15842/// [`emit_true_retain`] of the handle `push_handle` leaves on the stack.
15843fn emit_true_retain_of(code: &mut Vec<u8>, ctx: &Ctx, push_handle: impl Fn(&mut Vec<u8>)) {
15844    let Some(f) = ctx.runtime.and_then(|r| r.index(RuntimeFn::Retain)) else {
15845        return;
15846    };
15847    push_handle(code);
15848    code.push(0x10);
15849    leb_u32(code, f);
15850}
15851
15852/// Every element handle of the list in local `hdr` gains a copy-on-write hold (header word 12, the
15853/// count above the class byte) — the other list sharing it is a second holder. `counter` is a free
15854/// i32 scratch local.
15855fn emit_cow_retain_each_element(code: &mut Vec<u8>, hdr: u32, counter: u32) {
15856    i32_const(code, 0);
15857    local_set(code, counter);
15858    code.push(0x02);
15859    code.push(0x40); // block
15860    code.push(0x03);
15861    code.push(0x40); // loop
15862    local_get(code, counter);
15863    local_get(code, hdr);
15864    i32_load(code, 0); // element count
15865    code.push(0x4E); // i32.ge_s
15866    code.push(0x0D);
15867    leb_u32(code, 1); // br_if exit
15868    for _ in 0..2 {
15869        local_get(code, hdr);
15870        i32_load(code, 8); // data_ptr
15871        local_get(code, counter);
15872        i32_const(code, 8);
15873        code.push(0x6C);
15874        code.push(0x6A);
15875        i32_load(code, 0); // the element handle, twice: address and value
15876    }
15877    i32_load(code, 12);
15878    i32_const(code, 0x100);
15879    code.push(0x6A);
15880    i32_store(code, 12);
15881    local_get(code, counter);
15882    i32_const(code, 1);
15883    code.push(0x6A);
15884    local_set(code, counter);
15885    code.push(0x0C);
15886    leb_u32(code, 0); // br loop
15887    code.push(0x0B); // end loop
15888    code.push(0x0B); // end block
15889}
15890
15891/// S8's true count for a container that has just become a further holder of everything it holds —
15892/// a copy sharing its source's elements or entries, a literal built from registers: `call
15893/// __logos_retain_children(local hdr)`, which walks the slots the block's class names. One call
15894/// whatever the length. A no-op module-wide when `!ctx.heap_counting()`.
15895fn emit_retain_children(code: &mut Vec<u8>, ctx: &Ctx, hdr: u32) {
15896    let Some(f) = ctx.runtime.and_then(|r| r.index(RuntimeFn::RetainChildren)) else {
15897        return;
15898    };
15899    local_get(code, hdr);
15900    code.push(0x10);
15901    leb_u32(code, f);
15902}
15903
15904/// S8's true-count MID-TURN RELEASE: `call __logos_release(handle)`, `handle` computed by
15905/// `push_handle` (a closure so the caller can load a value OUT OF MEMORY — the slot a store is
15906/// about to overwrite — rather than only ever a register). A no-op module-wide when
15907/// `!ctx.heap_counting()`.
15908fn emit_true_release(code: &mut Vec<u8>, ctx: &Ctx, push_handle: impl Fn(&mut Vec<u8>)) {
15909    let Some(f) = ctx.runtime.and_then(|r| r.index(RuntimeFn::Release)) else {
15910        return;
15911    };
15912    push_handle(code);
15913    code.push(0x10);
15914    leb_u32(code, f);
15915}
15916
15917/// The kinds whose values count their extra holders (header word 12) — every copy-on-write kind, and
15918/// a record, whose writes copy it only while another holder shares it.
15919fn counts_aliases(k: Option<Kind>) -> bool {
15920    cow_clonable(k) || k == Some(Kind::Struct)
15921}
15922
15923/// The mutable heap kinds a copy-on-write clone can currently reproduce (everything `lower_deep_clone`
15924/// handles). A kind outside this set skips the COW guard and mutates in place — sound as long as no
15925/// aliasing test exercises it (`Map` COW is added in a follow-up).
15926fn cow_clonable(k: Option<Kind>) -> bool {
15927    matches!(
15928        k,
15929        Some(Kind::SeqInt)
15930            | Some(Kind::SeqBool)
15931            | Some(Kind::SeqFloat)
15932            | Some(Kind::SeqWord32)
15933            | Some(Kind::SeqWord64)
15934            | Some(Kind::SeqAny)
15935            | Some(Kind::Set)
15936            | Some(Kind::SetText)
15937            | Some(Kind::SeqSeqInt)
15938            | Some(Kind::Map)
15939            | Some(Kind::SeqText)
15940            | Some(Kind::SeqStruct)
15941            | Some(Kind::SeqEnum)
15942            | Some(Kind::SeqHandle)
15943    )
15944}
15945
15946/// The `__logos_seq_clone` mode of a kind whose copy is its slots as they are — its header's class,
15947/// and what each element gains from the copy (the same holds [`emit_collection_clone`]'s inline arms
15948/// give) — or `None` for one whose copy is not flat: a Text's bytes, a map's entries, a matrix's rows
15949/// each copied.
15950fn seq_clone_mode(k: Kind) -> Option<i32> {
15951    let handles = i32::from(AllocClass::HandleHeader.code()) | CLONE_RETAINS;
15952    Some(match k {
15953        Kind::SeqInt
15954        | Kind::SeqBool
15955        | Kind::SeqFloat
15956        | Kind::SeqWord32
15957        | Kind::SeqWord64
15958        | Kind::Set => i32::from(AllocClass::ScalarHeader.code()),
15959        Kind::SeqAny | Kind::SetText | Kind::SeqText | Kind::SeqEnum => handles,
15960        Kind::SeqStruct | Kind::SeqHandle => handles | CLONE_SHARES,
15961        _ => return None,
15962    })
15963}
15964
15965/// `cow(reg)` — the copy-on-write guard emitted before a mutation. If the object has any extra
15966/// reference (header word 12 nonzero) it is replaced by a fresh deep clone (word 12 == 0), so the
15967/// mutation stays private — exactly as the VM's `maybe_cow` clones an `Rc` whose `strong_count > 1`.
15968/// A uniquely-owned object mutates in place (the common build-then-scan case pays only a load+branch).
15969fn emit_cow(
15970    code: &mut Vec<u8>,
15971    kinds: &KindTable,
15972    structs: &kind::StructLayout,
15973    ctx: &Ctx,
15974    num_regs: u32,
15975    reg: u16,
15976) -> R<()> {
15977    if !cow_clonable(kinds.get(reg as usize)) {
15978        return Ok(());
15979    }
15980    if let Some(mode) = kinds.get(reg as usize).and_then(seq_clone_mode) {
15981        if ctx.hot.get() {
15982            // In a loop ([`Ctx::hot`]): the test inline, the copy the runtime's.
15983            if let Some(clone) = ctx.runtime.and_then(|r| r.index(RuntimeFn::SeqClone)) {
15984                emit_should_clone(code, reg as u32);
15985                code.push(0x04);
15986                code.push(0x40);
15987                local_get(code, reg as u32);
15988                i32_const(code, mode);
15989                code.push(0x10);
15990                leb_u32(code, clone);
15991                local_set(code, reg as u32);
15992                code.push(0x0B);
15993                return Ok(());
15994            }
15995        } else if let Some(own) = ctx.runtime.and_then(|r| r.index(RuntimeFn::SeqOwn)) {
15996            local_get(code, reg as u32);
15997            i32_const(code, mode);
15998            code.push(0x10);
15999            leb_u32(code, own);
16000            local_set(code, reg as u32);
16001            return Ok(());
16002        }
16003    }
16004    if kinds.get(reg as usize) == Some(Kind::Map) {
16005        if let Some(own) = ctx.runtime.and_then(|r| r.index(RuntimeFn::MapOwn)) {
16006            local_get(code, reg as u32);
16007            code.push(0x10);
16008            leb_u32(code, own);
16009            local_set(code, reg as u32);
16010            return Ok(());
16011        }
16012    }
16013    emit_should_clone(code, reg as u32);
16014    code.push(0x04);
16015    code.push(0x40); // if should_clone
16016    lower_deep_clone(code, kinds, structs, ctx, num_regs, reg, reg)?;
16017    code.push(0x0B); // end
16018    Ok(())
16019}
16020
16021/// `[] -> [should_clone]` for the copy-on-write value whose handle is in `local`: word 12 ≥ 256,
16022/// signed. A `SharedMap`'s word 12 is deeply negative (`SHARED_MAP_MARK`) and never clones whatever
16023/// its extra-refs count; anything else clones exactly when its extra-refs count (bits 8-31, above the
16024/// class byte in bits 0-7) is non-zero — which, for a non-negative word, is the word reaching 256. One
16025/// signed compare reads both: an ordinary map's class byte (`MapScalarScalar` = 3 through
16026/// `MapHandleHandle` = 6) alone stays below 256, so it is not mistaken for an extra holder.
16027fn emit_should_clone(code: &mut Vec<u8>, local: u32) {
16028    local_get(code, local);
16029    i32_load(code, 12);
16030    i32_const(code, 0x100);
16031    code.push(0x4E); // i32.ge_s
16032}
16033
16034/// A record's copy-on-write, for a write to the record in `obj` that another holder may share: when
16035/// its count of extra holders (header word 12) is nonzero, `obj` takes a fresh record with the same
16036/// fields. Every field whose value counts its holders (a list, a set, a map, a record) is then held
16037/// by both records and gains a hold, so a later write through either record's field copies that
16038/// value first. The field `overwritten` names — which the write that needed the copy replaces in the
16039/// copy — is not shared by the copy and gains nothing. A record nobody else holds is written in place.
16040fn emit_record_copy(
16041    code: &mut Vec<u8>,
16042    ctx: &Ctx,
16043    kinds: &KindTable,
16044    structs: &kind::StructLayout,
16045    num_regs: u32,
16046    obj: u16,
16047    overwritten: Option<usize>,
16048) -> R<()> {
16049    let (hdr, data, idx) = (num_regs + 5, num_regs + 6, num_regs + 7);
16050    emit_should_clone(code, obj as u32);
16051    code.push(0x04);
16052    code.push(0x40); // if another holder shares the record
16053                     // A copy carries the source's field-kind bytes alongside its heterogeneous values.
16054    emit_buffer_clone(
16055        code,
16056        ctx,
16057        hdr,
16058        data,
16059        idx,
16060        obj as u32,
16061        false,
16062        AllocClass::RecordHeader,
16063    );
16064    local_get(code, hdr);
16065    local_set(code, obj as u32);
16066    if ctx.heap_counting() {
16067        emit_retain_children(code, ctx, obj as u32);
16068    }
16069    if let Some(slot_kinds) = record_slot_kinds(kinds, structs, obj) {
16070        for (slot, k) in slot_kinds.iter().enumerate() {
16071            // A field holding a value of the exact extension is a handle the copy owns: it takes a copy
16072            // of the value, so a change in place through either record reaches only its own.
16073            if *k == Some(Kind::Tower) && overwritten != Some(slot) {
16074                tower::own_field(code, ctx, obj, slot as u32)?;
16075                continue;
16076            }
16077            // The overwritten field gains no copy-on-write hold (the copy will not share it), but it
16078            // does gain its true count: the write releases the value it overwrites, from the copy.
16079            let cow_hold = counts_aliases(*k) && overwritten != Some(slot);
16080            if !cow_hold {
16081                continue;
16082            }
16083            local_get(code, obj as u32);
16084            i32_load(code, 8); // data_ptr
16085            i32_load(code, slot as u32 * 8);
16086            local_tee(code, idx);
16087            code.push(0x04);
16088            code.push(0x40); // if the field holds a value
16089            if cow_hold {
16090                local_get(code, idx);
16091                local_get(code, idx);
16092                i32_load(code, 12);
16093                i32_const(code, 0x100); // extra_refs occupies bits 8-31; the class byte is untouched
16094                code.push(0x6A);
16095                i32_store(code, 12);
16096            }
16097            code.push(0x0B);
16098        }
16099    }
16100    code.push(0x0B); // end if shared
16101    Ok(())
16102}
16103
16104/// The copy-on-write count a `SharedMap` starts with. A CRDT map is one replica shared by every
16105/// holder (the reference tiers keep it behind an `Rc<RefCell>`), so a write through any holder must
16106/// land in it rather than in a private copy. A count this far below zero stays negative under every
16107/// retain and release a program can perform, and [`emit_cow`] clones only a positive count. The same
16108/// mark keeps the map's entries sorted by key ([`lower_map_insert`]), which is the order a CRDT map
16109/// displays in on every tier.
16110const SHARED_MAP_MARK: i32 = -(1 << 30);
16111
16112/// Is a `Map`'s key an `Int` (i64, false) or `Text` (i32 handle, true)? Other key kinds are refused.
16113fn map_key_text(kinds: &KindTable, key: u16) -> R<bool> {
16114    match kinds.get(key as usize) {
16115        Some(Kind::Int) => Ok(false),
16116        Some(Kind::Text) => Ok(true),
16117        _ => Err(WasmLowerError::Unsupported("map key must be Int or Text")),
16118    }
16119}
16120
16121/// Leave on the stack `1`/`0` for whether map entry `idx`'s key equals the query register `key` —
16122/// `i64.eq` for an Int key, or a `Text` byte-equality ([`emit_text_eq`], the entry's key in scratch
16123/// +8) for a Text key. `idx_local` is the entry index local.
16124fn emit_map_key_compare(
16125    code: &mut Vec<u8>,
16126    ctx: &Ctx,
16127    num_regs: u32,
16128    key_text: bool,
16129    m: u32,
16130    idx_local: u32,
16131    key: u16,
16132) {
16133    if key_text {
16134        let entry_key = num_regs + 8;
16135        emit_map_entry_addr(code, m, idx_local);
16136        i32_load(code, 0); // entry key handle
16137        local_set(code, entry_key);
16138        emit_text_eq(code, ctx, num_regs, key as u32, entry_key);
16139    } else {
16140        emit_map_entry_addr(code, m, idx_local);
16141        i64_load(code, 0); // entry key
16142        local_get(code, key as u32);
16143        code.push(0x51); // i64.eq
16144    }
16145}
16146
16147/// The store opcode for a map's VALUE slot (offset 8 of a 16-byte entry), by the value's kind: a
16148/// `Float` is an `f64`, an `Int`/`Bool` an `i64`. Any other kind (a handle-valued map) is deferred.
16149fn map_value_store(k: Option<Kind>) -> R<fn(&mut Vec<u8>, u32)> {
16150    match k {
16151        Some(Kind::Float) => Ok(f64_store),
16152        Some(Kind::Int) | Some(Kind::Bool) | Some(Kind::Moment) | Some(Kind::Duration)
16153        | Some(Kind::Time) | Some(Kind::Span) => Ok(i64_store),
16154        // A handle-valued map (`Map of K to Seq`/Struct/Text/…): the i32 handle rides the low word of
16155        // the 8-byte value slot; the entry copy in `emit_map_clone` moves the whole slot as an i64.
16156        Some(vk) if vk.wasm_valtype() == I32 => Ok(i32_store),
16157        _ => Err(WasmLowerError::Unsupported(
16158            "map value of an unsupported kind",
16159        )),
16160    }
16161}
16162
16163/// The load opcode mirroring [`map_value_store`] (the value's kind is the `Index` destination's).
16164fn map_value_load(k: Option<Kind>) -> R<fn(&mut Vec<u8>, u32)> {
16165    match k {
16166        Some(Kind::Float) => Ok(f64_load),
16167        Some(Kind::Int) | Some(Kind::Bool) | Some(Kind::Moment) | Some(Kind::Duration)
16168        | Some(Kind::Time) | Some(Kind::Span) => Ok(i64_load),
16169        Some(vk) if vk.wasm_valtype() == I32 => Ok(i32_load),
16170        _ => Err(WasmLowerError::Unsupported(
16171            "map value of unknown/unsupported kind",
16172        )),
16173    }
16174}
16175
16176/// Push the map key in register `key` as the i64 the map runtime takes: an Int as it is, a Text's
16177/// handle zero-extended.
16178fn emit_map_key_i64(code: &mut Vec<u8>, key: u16, key_text: bool) {
16179    local_get(code, key as u32);
16180    if key_text {
16181        code.push(0xAD); // i64.extend_i32_u
16182    }
16183}
16184
16185/// Leave `data_ptr + idx*16` (the address of map entry `idx`, a `[key:i64][value:i64]` pair) on
16186/// the stack.
16187fn emit_map_entry_addr(code: &mut Vec<u8>, m: u32, idx: u32) {
16188    local_get(code, m);
16189    i32_load(code, 8); // data_ptr
16190    local_get(code, idx);
16191    i32_const(code, 16);
16192    code.push(0x6C); // i32.mul
16193    code.push(0x6A); // i32.add
16194}
16195
16196/// `Map of {Int,Text} to Int` insert (`Set item key of m to value`): linear-scan for `key` (i64.eq
16197/// for an Int key, byte-equality for a Text key); if present overwrite its value, else append a new
16198/// `[key][value]` entry (reallocating the entry buffer, like `ListPush`). The value must be `Int`.
16199fn lower_map_insert(
16200    code: &mut Vec<u8>,
16201    kinds: &KindTable,
16202    ctx: &Ctx,
16203    num_regs: u32,
16204    map: u16,
16205    key: u16,
16206    value: u16,
16207) -> R<()> {
16208    let key_text = map_key_text(kinds, key)?;
16209    let val_store = map_value_store(kinds.get(value as usize))?;
16210    let m = map as u32;
16211    // A map's key/value handle-ness is not known at `NewEmptyMap` (it starts empty and inert either
16212    // way) — the first insert is where it is FIRST reliably visible, from the actual key/value
16213    // registers being inserted, so it is stamped/re-stamped here. Idempotent: a statically-typed
16214    // map's key/value KINDS never change across inserts, so every call writes the same class. Only
16215    // the low byte (bits 0-7) is touched — bits 8-31 keep whatever the header already carries there,
16216    // an ordinary count or (for a `SharedMap`) the deeply-negative `SHARED_MAP_MARK` sign.
16217    let value_is_handle = kinds
16218        .get(value as usize)
16219        .map(|k| kind_is_handle(k))
16220        .unwrap_or(false);
16221    let class = AllocClass::of_map(key_text, value_is_handle);
16222    let put = if ctx.shared_maps {
16223        None
16224    } else {
16225        ctx.runtime.and_then(|r| r.index(RuntimeFn::MapPut))
16226    };
16227    if let Some(put) = put {
16228        local_get(code, m);
16229        emit_map_key_i64(code, key, key_text);
16230        i32_const(code, i32::from(class.code()));
16231        code.push(0x10);
16232        leb_u32(code, put);
16233        if ctx.heap_counting() && counted_kind(kinds.get(value as usize)) {
16234            // S8's true count: the entry stops holding the value it overwrites (none, for an entry
16235            // the put just appended: its value slot starts empty).
16236            let entry = num_regs + 5;
16237            local_tee(code, entry);
16238            emit_true_release(code, ctx, |c| {
16239                local_get(c, entry);
16240                i32_load(c, 8);
16241            });
16242        }
16243        local_get(code, value as u32);
16244        val_store(code, 8);
16245        return Ok(());
16246    }
16247    // A linked module, or a program with `SharedMap`s (whose entries stay sorted), inserts inline.
16248    local_get(code, m);
16249    local_get(code, m);
16250    i32_load(code, 12);
16251    i32_const(code, !0xFFu32 as i32); // 0xFFFFFF00 — clears the class byte, keeps count/sign
16252    code.push(0x71); // i32.and
16253    i32_const(code, class.code() as i32);
16254    code.push(0x72); // i32.or
16255    i32_store(code, 12);
16256    let (idx, found, new) = (num_regs + 5, num_regs + 6, num_regs + 7);
16257    // scan for an existing key
16258    i32_const(code, 0);
16259    local_set(code, idx);
16260    i32_const(code, 0);
16261    local_set(code, found);
16262    code.push(0x02);
16263    code.push(0x40); // block
16264    code.push(0x03);
16265    code.push(0x40); // loop
16266    local_get(code, idx);
16267    local_get(code, m);
16268    i32_load(code, 0); // num_entries
16269    code.push(0x4E); // i32.ge_s → idx >= num
16270    code.push(0x0D);
16271    leb_u32(code, 1); // br_if block
16272    emit_map_key_compare(code, ctx, num_regs, key_text, m, idx, key);
16273    code.push(0x04);
16274    code.push(0x40); // if (key matches)
16275    if ctx.heap_counting() && counted_kind(kinds.get(value as usize)) {
16276        // S8's true count: the entry stops holding the value it is about to overwrite. (A copy of the
16277        // map holds that value too, and counted it when it was made — `emit_map_clone`.)
16278        emit_true_release(code, ctx, |c| {
16279            emit_map_entry_addr(c, m, idx);
16280            i32_load(c, 8);
16281        });
16282    }
16283    emit_map_entry_addr(code, m, idx);
16284    local_get(code, value as u32);
16285    val_store(code, 8); // entry.value = value (at the value kind's width)
16286    i32_const(code, 1);
16287    local_set(code, found);
16288    code.push(0x0C);
16289    leb_u32(code, 2); // br block (out of if→loop→block)
16290    code.push(0x0B); // end if
16291    local_get(code, idx);
16292    i32_const(code, 1);
16293    code.push(0x6A);
16294    local_set(code, idx);
16295    code.push(0x0C);
16296    leb_u32(code, 0); // br loop
16297    code.push(0x0B); // end loop
16298    code.push(0x0B); // end block
16299                     // if not found: append a new entry — write in place when a slot is free (num < cap);
16300                     // otherwise double the capacity, copy the old entries across, and free the buffer growth
16301                     // abandons — dead by construction, exactly as `lower_list_push_at` grows a sequence.
16302    let new_cap = num_regs + 23; // dedicated, alongside the matching risk in `emit_set_add_elem`
16303    local_get(code, found);
16304    code.push(0x45); // i32.eqz
16305    code.push(0x04);
16306    code.push(0x40); // if (!found)
16307    local_get(code, m);
16308    i32_load(code, 0); // num
16309    local_get(code, m);
16310    i32_load(code, 4); // cap
16311    code.push(0x4E); // i32.ge_s → num >= cap
16312    code.push(0x04);
16313    code.push(0x40); // if (grow)
16314    {
16315        // new_cap = cap == 0 ? 4 : cap * 2
16316        i32_const(code, 4);
16317        local_get(code, m);
16318        i32_load(code, 4);
16319        i32_const(code, 2);
16320        code.push(0x6C);
16321        local_get(code, m);
16322        i32_load(code, 4);
16323        code.push(0x45); // i32.eqz → cap == 0
16324        code.push(0x1B); // select
16325        local_set(code, new_cap);
16326        // new = alloc(new_cap * 16)
16327        local_get(code, new_cap);
16328        i32_const(code, 16);
16329        code.push(0x6C);
16330        emit_alloc(code, ctx, new, AllocClass::Raw);
16331        // copy old entries: for i in 0..num: new[i] = old[i] (key then value)
16332        i32_const(code, 0);
16333        local_set(code, idx);
16334        code.push(0x02);
16335        code.push(0x40);
16336        code.push(0x03);
16337        code.push(0x40);
16338        local_get(code, idx);
16339        local_get(code, m);
16340        i32_load(code, 0);
16341        code.push(0x4E);
16342        code.push(0x0D);
16343        leb_u32(code, 1);
16344        for field in [0u32, 8] {
16345            // new[idx].field = old[idx].field
16346            local_get(code, new);
16347            local_get(code, idx);
16348            i32_const(code, 16);
16349            code.push(0x6C);
16350            code.push(0x6A); // new entry addr
16351            emit_map_entry_addr(code, m, idx); // old entry addr
16352            i64_load(code, field);
16353            i64_store(code, field);
16354        }
16355        local_get(code, idx);
16356        i32_const(code, 1);
16357        code.push(0x6A);
16358        local_set(code, idx);
16359        code.push(0x0C);
16360        leb_u32(code, 0);
16361        code.push(0x0B);
16362        code.push(0x0B);
16363        // The old entry buffer is dead by construction: this header is the only holder and is
16364        // about to stop pointing at it, read before the header is repointed.
16365        emit_free(
16366            code,
16367            ctx,
16368            |c| {
16369                local_get(c, m);
16370                i32_load(c, 8); // the OLD data_ptr
16371            },
16372            |c| {
16373                local_get(c, m);
16374                i32_load(c, 4); // the OLD cap
16375                i32_const(c, 16);
16376                c.push(0x6C);
16377            },
16378        );
16379        // header: data_ptr = new; cap = new_cap
16380        local_get(code, m);
16381        local_get(code, new);
16382        i32_store(code, 8);
16383        local_get(code, m);
16384        local_get(code, new_cap);
16385        i32_store(code, 4);
16386    }
16387    code.push(0x0B); // end if (grow)
16388                     // entry[num] = (key, value) — the key is an i64 (Int) or an i32 handle (Text); `m`'s
16389                     // data_ptr already names the buffer with room, whichever branch above ran.
16390    local_get(code, m);
16391    i32_load(code, 8);
16392    local_get(code, m);
16393    i32_load(code, 0);
16394    i32_const(code, 16);
16395    code.push(0x6C);
16396    code.push(0x6A); // addr of new entry slot
16397    local_get(code, key as u32);
16398    if key_text {
16399        i32_store(code, 0);
16400        // S8's true count: the map holds the Text key it now keeps (a map never releases what it
16401        // holds, so a counted key simply lives as long as it could be read).
16402        if ctx.heap_counting() {
16403            emit_true_retain(code, ctx, key);
16404        }
16405    } else {
16406        i64_store(code, 0);
16407    }
16408    local_get(code, m);
16409    i32_load(code, 8);
16410    local_get(code, m);
16411    i32_load(code, 0);
16412    i32_const(code, 16);
16413    code.push(0x6C);
16414    code.push(0x6A);
16415    local_get(code, value as u32);
16416    val_store(code, 8);
16417    // header: num_entries += 1
16418    local_get(code, m);
16419    local_get(code, m);
16420    i32_load(code, 0);
16421    i32_const(code, 1);
16422    code.push(0x6A);
16423    i32_store(code, 0);
16424    if ctx.shared_maps {
16425        // A shared (CRDT) map keeps its entries sorted by key: move the new entry down to its place.
16426        local_get(code, m);
16427        i32_load(code, 12);
16428        i32_const(code, 0);
16429        code.push(0x48); // i32.lt_s — marked shared
16430        code.push(0x04);
16431        code.push(0x40); // if
16432        emit_sink_last_entry_to_sorted_place(code, num_regs, m, key as u32, key_text, None);
16433        code.push(0x0B); // end if
16434    }
16435    code.push(0x0B); // end if (!found)
16436    Ok(())
16437}
16438
16439/// Move the entry just appended to the map in local `m` (its last slot; key in register `key`) down
16440/// to its sorted place: every earlier entry whose key is greater moves up one slot, whole — key and
16441/// value. A Text key orders by bytes, an Int numerically, as `CrdtScalar`'s `Ord` does. Scratch
16442/// `+11` is the slot being filled, the key it is compared against waits in `+8` (Text) or `+16`
16443/// (Int), and the new entry's value rides the i64 scratch `+15` across the shift.
16444fn emit_sink_last_entry_to_sorted_place(
16445    code: &mut Vec<u8>,
16446    num_regs: u32,
16447    m: u32,
16448    key: u32,
16449    key_text: bool,
16450    exact_cmp: Option<u32>,
16451) {
16452    let at = num_regs + 11;
16453    let prev_key = if key_text || exact_cmp.is_some() {
16454        num_regs + 8
16455    } else {
16456        num_regs + 16
16457    };
16458    let new_value = num_regs + 15;
16459    let entry_at = |code: &mut Vec<u8>, minus_one: bool| {
16460        local_get(code, m);
16461        i32_load(code, 8);
16462        local_get(code, at);
16463        if minus_one {
16464            i32_const(code, 1);
16465            code.push(0x6B);
16466        }
16467        i32_const(code, 16);
16468        code.push(0x6C);
16469        code.push(0x6A);
16470    };
16471    // at = num - 1; hold the new entry's value slot (8 raw bytes) while earlier entries shift up
16472    local_get(code, m);
16473    i32_load(code, 0);
16474    i32_const(code, 1);
16475    code.push(0x6B);
16476    local_set(code, at);
16477    entry_at(code, false);
16478    i64_load(code, 8);
16479    local_set(code, new_value);
16480    code.push(0x02);
16481    code.push(0x40); // block $placed
16482    code.push(0x03);
16483    code.push(0x40); // loop $sink
16484    local_get(code, at);
16485    code.push(0x45); // i32.eqz
16486    code.push(0x0D);
16487    leb_u32(code, 1); // br_if $placed
16488    entry_at(code, true);
16489    if let Some(cmp) = exact_cmp {
16490        i32_load(code, 0);
16491        i32_load(code, 8);
16492        i64_load(code, 0);
16493        local_get(code, key);
16494        i32_load(code, 8);
16495        i64_load(code, 0);
16496        code.push(0x10);
16497        leb_u32(code, cmp);
16498        i32_const(code, 0);
16499        code.push(0x48);
16500    } else if key_text {
16501        i32_load(code, 0);
16502        local_set(code, prev_key);
16503        emit_text_handles_lt(code, num_regs, prev_key, key as u32);
16504    } else {
16505        i64_load(code, 0);
16506        local_set(code, prev_key);
16507        local_get(code, prev_key);
16508        local_get(code, key as u32);
16509        code.push(0x53); // i64.lt_s
16510    }
16511    code.push(0x0D);
16512    leb_u32(code, 1); // br_if $placed — the previous key sorts first
16513    for off in [0u32, 8] {
16514        entry_at(code, false);
16515        entry_at(code, true);
16516        i64_load(code, off);
16517        i64_store(code, off);
16518    }
16519    local_get(code, at);
16520    i32_const(code, 1);
16521    code.push(0x6B);
16522    local_set(code, at);
16523    code.push(0x0C);
16524    leb_u32(code, 0); // br $sink
16525    code.push(0x0B); // end loop
16526    code.push(0x0B); // end block
16527                     // entry[at] = (key, value)
16528    entry_at(code, false);
16529    local_get(code, key as u32);
16530    if key_text || exact_cmp.is_some() {
16531        i32_store(code, 0);
16532    } else {
16533        i64_store(code, 0);
16534    }
16535    entry_at(code, false);
16536    local_get(code, new_value);
16537    i64_store(code, 8);
16538}
16539
16540/// `Map of Int to Int` get (`item key of m`): linear-scan for `key`, load its value into `dst`;
16541/// trap if absent (the tree-walker raises "Key not found", and the standalone module has no VM).
16542fn lower_map_get(
16543    code: &mut Vec<u8>,
16544    kinds: &KindTable,
16545    ctx: &Ctx,
16546    num_regs: u32,
16547    dst: u16,
16548    map: u16,
16549    key: u16,
16550) -> R<()> {
16551    let key_text = map_key_text(kinds, key)?;
16552    let val_load = map_value_load(kinds.get(dst as usize))?;
16553    let m = map as u32;
16554    if let Some(at) = ctx.runtime.and_then(|r| r.index(RuntimeFn::MapAt)) {
16555        local_get(code, m);
16556        emit_map_key_i64(code, key, key_text);
16557        i32_const(code, i32::from(key_text));
16558        code.push(0x10);
16559        leb_u32(code, at);
16560        val_load(code, 8);
16561        local_set(code, dst as u32);
16562        return Ok(());
16563    }
16564    // A linked module has no runtime of its own: the scan inline.
16565    let (idx, found) = (num_regs + 5, num_regs + 6);
16566    i32_const(code, 0);
16567    local_set(code, idx);
16568    i32_const(code, 0);
16569    local_set(code, found);
16570    code.push(0x02);
16571    code.push(0x40);
16572    code.push(0x03);
16573    code.push(0x40);
16574    local_get(code, idx);
16575    local_get(code, m);
16576    i32_load(code, 0);
16577    code.push(0x4E);
16578    code.push(0x0D);
16579    leb_u32(code, 1);
16580    emit_map_key_compare(code, ctx, num_regs, key_text, m, idx, key);
16581    code.push(0x04);
16582    code.push(0x40); // if (match)
16583    emit_map_entry_addr(code, m, idx);
16584    val_load(code, 8); // value (at the value kind's width)
16585    local_set(code, dst as u32);
16586    i32_const(code, 1);
16587    local_set(code, found);
16588    code.push(0x0C);
16589    leb_u32(code, 2);
16590    code.push(0x0B); // end if
16591    local_get(code, idx);
16592    i32_const(code, 1);
16593    code.push(0x6A);
16594    local_set(code, idx);
16595    code.push(0x0C);
16596    leb_u32(code, 0);
16597    code.push(0x0B);
16598    code.push(0x0B);
16599    // absent key → trap
16600    local_get(code, found);
16601    code.push(0x45); // i32.eqz
16602    code.push(0x04);
16603    code.push(0x40);
16604    code.push(0x00); // unreachable
16605    code.push(0x0B);
16606    Ok(())
16607}
16608
16609/// `m contains key` (Map): linear-scan for the key → Bool i64 0/1 in `dst`.
16610fn lower_map_contains(
16611    code: &mut Vec<u8>,
16612    kinds: &KindTable,
16613    ctx: &Ctx,
16614    num_regs: u32,
16615    dst: u16,
16616    map: u16,
16617    key: u16,
16618) -> R<()> {
16619    let key_text = map_key_text(kinds, key)?;
16620    let m = map as u32;
16621    if let Some(find) = ctx.runtime.and_then(|r| r.index(RuntimeFn::MapFind)) {
16622        local_get(code, m);
16623        emit_map_key_i64(code, key, key_text);
16624        i32_const(code, i32::from(key_text));
16625        code.push(0x10);
16626        leb_u32(code, find);
16627        i32_const(code, 0);
16628        code.push(0x47); // i32.ne — an entry holds the key
16629        code.push(0xAD); // i64.extend_i32_u
16630        local_set(code, dst as u32);
16631        return Ok(());
16632    }
16633    // A linked module has no runtime of its own: the scan inline.
16634    let idx = num_regs + 5;
16635    code.push(0x42);
16636    leb_i64(code, 0);
16637    local_set(code, dst as u32); // dst = 0
16638    i32_const(code, 0);
16639    local_set(code, idx);
16640    code.push(0x02);
16641    code.push(0x40);
16642    code.push(0x03);
16643    code.push(0x40);
16644    local_get(code, idx);
16645    local_get(code, m);
16646    i32_load(code, 0);
16647    code.push(0x4E);
16648    code.push(0x0D);
16649    leb_u32(code, 1);
16650    emit_map_key_compare(code, ctx, num_regs, key_text, m, idx, key);
16651    code.push(0x04);
16652    code.push(0x40); // if (match)
16653    code.push(0x42);
16654    leb_i64(code, 1);
16655    local_set(code, dst as u32); // dst = 1
16656    code.push(0x0C);
16657    leb_u32(code, 2); // break (found)
16658    code.push(0x0B);
16659    local_get(code, idx);
16660    i32_const(code, 1);
16661    code.push(0x6A);
16662    local_set(code, idx);
16663    code.push(0x0C);
16664    leb_u32(code, 0);
16665    code.push(0x0B);
16666    code.push(0x0B);
16667    Ok(())
16668}
16669
16670/// Byte-equality of two `Text` handles in locals `a`/`b`, leaving an i32 (1 = equal, 0 = not) on the
16671/// wasm stack, so it drops into a scan's comparison exactly where an `i64.eq` would: a call of
16672/// `__logos_text_eq`, or — in a linked module, which has no runtime of its own — the byte loop
16673/// inline, in the `+9` (byte index) and `+10` (result) scratch, distinct from a set scan's
16674/// `+5`/`+6`/`+7` and the `+8` slot-handle temp.
16675fn emit_text_eq(code: &mut Vec<u8>, ctx: &Ctx, num_regs: u32, a: u32, b: u32) {
16676    if let Some(eq) = ctx.runtime.and_then(|r| r.index(RuntimeFn::TextEq)) {
16677        local_get(code, a);
16678        local_get(code, b);
16679        code.push(0x10);
16680        leb_u32(code, eq);
16681        return;
16682    }
16683    let (idx, res) = (num_regs + 9, num_regs + 10);
16684    i32_const(code, 1);
16685    local_set(code, res); // assume equal
16686                          // if len_a != len_b → not equal
16687    local_get(code, a);
16688    i32_load(code, 0);
16689    local_get(code, b);
16690    i32_load(code, 0);
16691    code.push(0x47); // i32.ne
16692    code.push(0x04);
16693    code.push(0x40); // if (lengths differ)
16694    i32_const(code, 0);
16695    local_set(code, res);
16696    code.push(0x05); // else — compare bytes
16697    i32_const(code, 0);
16698    local_set(code, idx);
16699    code.push(0x02);
16700    code.push(0x40); // block $done
16701    code.push(0x03);
16702    code.push(0x40); // loop
16703    local_get(code, idx);
16704    local_get(code, a);
16705    i32_load(code, 0); // len
16706    code.push(0x4E); // i32.ge_s → idx >= len (all matched)
16707    code.push(0x0D);
16708    leb_u32(code, 1); // br_if $done
16709                      // a.data[idx] != b.data[idx] ?
16710    local_get(code, a);
16711    i32_load(code, 8);
16712    local_get(code, idx);
16713    code.push(0x6A);
16714    i32_load8_u(code, 0);
16715    local_get(code, b);
16716    i32_load(code, 8);
16717    local_get(code, idx);
16718    code.push(0x6A);
16719    i32_load8_u(code, 0);
16720    code.push(0x47); // i32.ne
16721    code.push(0x04);
16722    code.push(0x40); // if (byte differs)
16723    i32_const(code, 0);
16724    local_set(code, res);
16725    code.push(0x0C);
16726    leb_u32(code, 2); // br $done (mismatch)
16727    code.push(0x0B); // end if
16728    local_get(code, idx);
16729    i32_const(code, 1);
16730    code.push(0x6A);
16731    local_set(code, idx);
16732    code.push(0x0C);
16733    leb_u32(code, 0); // br loop
16734    code.push(0x0B); // end loop
16735    code.push(0x0B); // end block
16736    code.push(0x0B); // end outer if
16737    local_get(code, res); // leave the result on the stack
16738}
16739
16740/// Emit "does `set[idx]` equal `value`?", leaving an i32 (1/0) on the wasm stack — the element
16741/// comparison shared by the set scans. Int: `i64.eq` of the slot element and `value`. `SetText`:
16742/// byte-equality of the slot's `Text` handle and `value`'s (`emit_text_handles_eq`, via the `+8`
16743/// slot-handle temp). Both read the 8-byte slot at `data_ptr + idx*8`.
16744fn emit_set_elem_eq(
16745    code: &mut Vec<u8>,
16746    ctx: &Ctx,
16747    num_regs: u32,
16748    set: u32,
16749    idx: u32,
16750    value: u32,
16751    is_text: bool,
16752) {
16753    local_get(code, set);
16754    i32_load(code, 8); // data_ptr
16755    local_get(code, idx);
16756    i32_const(code, 8);
16757    code.push(0x6C);
16758    code.push(0x6A); // slot addr = data_ptr + idx*8
16759    if is_text {
16760        i32_load(code, 0); // the slot's Text handle
16761        local_set(code, num_regs + 8);
16762        emit_text_eq(code, ctx, num_regs, num_regs + 8, value);
16763    } else {
16764        i64_load(code, 0); // the slot's i64 element
16765        local_get(code, value);
16766        code.push(0x51); // i64.eq
16767    }
16768}
16769
16770/// `Remove value from c` (`RemoveFrom`) on a `Set of Int`/`Set of Text` or a `Map` keyed by Int or
16771/// Text — linear-scan for the value (a Set element, or a Map key at entry offset 0); if found, close the gap
16772/// by moving every later slot down one and decrement the count. The elements keep their order — a
16773/// `Set`/`Map` displays in insertion order and a CRDT set in sorted order, and a removal changes
16774/// neither. A Text element or key compares by BYTE equality, not handle identity.
16775fn lower_remove_from(
16776    code: &mut Vec<u8>,
16777    kinds: &KindTable,
16778    ctx: &Ctx,
16779    num_regs: u32,
16780    collection: u16,
16781    value: u16,
16782) -> R<()> {
16783    let set_text = matches!(
16784        kinds.get(collection as usize),
16785        Some(Kind::SetText) | Some(Kind::CrdtSetText)
16786    );
16787    let map_text_key = kinds.get(collection as usize) == Some(Kind::Map)
16788        && kinds.get(value as usize) == Some(Kind::Text);
16789    if !set_text && !map_text_key && kinds.get(value as usize) != Some(Kind::Int) {
16790        return Err(WasmLowerError::Unsupported("remove of a non-Int value"));
16791    }
16792    let stride: i32 = match kinds.get(collection as usize) {
16793        Some(Kind::Set) | Some(Kind::SetText) | Some(Kind::CrdtSetText) => 8,
16794        Some(Kind::Map) => 16,
16795        _ => {
16796            return Err(WasmLowerError::Unsupported(
16797                "remove from a non-set/map collection",
16798            ))
16799        }
16800    };
16801    let c = collection as u32;
16802    let (idx, found) = (num_regs + 5, num_regs + 6);
16803    i32_const(code, 0);
16804    local_set(code, idx);
16805    i32_const(code, 0);
16806    local_set(code, found);
16807    code.push(0x02);
16808    code.push(0x40);
16809    code.push(0x03);
16810    code.push(0x40);
16811    local_get(code, idx);
16812    local_get(code, c);
16813    i32_load(code, 0); // num
16814    code.push(0x4E); // i32.ge_s
16815    code.push(0x0D);
16816    leb_u32(code, 1); // br_if block
16817                      // data[idx] (element / key at offset 0) == value ? — a Text element or key compares by bytes,
16818                      // an Int set / Map key by `i64.eq` at its stride.
16819    if set_text {
16820        emit_set_elem_eq(code, ctx, num_regs, c, idx, value as u32, true);
16821    } else if map_text_key {
16822        emit_map_key_compare(code, ctx, num_regs, true, c, idx, value);
16823    } else {
16824        local_get(code, c);
16825        i32_load(code, 8);
16826        local_get(code, idx);
16827        i32_const(code, stride);
16828        code.push(0x6C);
16829        code.push(0x6A);
16830        i64_load(code, 0);
16831        local_get(code, value as u32);
16832        code.push(0x51); // i64.eq
16833    }
16834    code.push(0x04);
16835    code.push(0x40); // if (match)
16836                     // Removing a slot ends its ownership of each handle before the following slots move.
16837                     // Read the collection's class: the value kind is not present on RemoveFrom itself.
16838    if ctx.heap_counting() {
16839        for off in (0..stride as u32).step_by(8) {
16840            let mask: i32 = AllocClass::ALL
16841                .iter()
16842                .filter(|class| {
16843                    let (first, second) = class.held_handles();
16844                    if off == 0 {
16845                        first
16846                    } else {
16847                        second
16848                    }
16849                })
16850                .map(|class| 1i32 << class.code())
16851                .sum();
16852            i32_const(code, mask);
16853            local_get(code, c);
16854            i32_load(code, 12);
16855            i32_const(code, 0xFF);
16856            code.push(0x71);
16857            code.push(0x76); // i32.shr_u
16858            i32_const(code, 1);
16859            code.push(0x71);
16860            code.push(0x04);
16861            code.push(0x40);
16862            emit_true_release(code, ctx, |code| {
16863                local_get(code, c);
16864                i32_load(code, 8);
16865                local_get(code, idx);
16866                i32_const(code, stride);
16867                code.push(0x6C);
16868                code.push(0x6A);
16869                i32_load(code, off);
16870            });
16871            code.push(0x0B);
16872        }
16873    }
16874    // Close the gap: for idx in idx..num-1, slot[idx] = slot[idx+1] (one i64 for a Set, two for a
16875    // Map entry). `idx` is the loop counter from here; the scan is over.
16876    code.push(0x02);
16877    code.push(0x40); // block $shifted
16878    code.push(0x03);
16879    code.push(0x40); // loop $shift
16880    local_get(code, idx);
16881    i32_const(code, 1);
16882    code.push(0x6A);
16883    local_get(code, c);
16884    i32_load(code, 0);
16885    code.push(0x4E); // i32.ge_s → idx + 1 >= num
16886    code.push(0x0D);
16887    leb_u32(code, 1); // br_if $shifted
16888    let offs: &[u32] = if stride == 16 { &[0, 8] } else { &[0] };
16889    for &off in offs {
16890        local_get(code, c);
16891        i32_load(code, 8);
16892        local_get(code, idx);
16893        i32_const(code, stride);
16894        code.push(0x6C);
16895        code.push(0x6A); // slot idx
16896        local_get(code, c);
16897        i32_load(code, 8);
16898        local_get(code, idx);
16899        i32_const(code, 1);
16900        code.push(0x6A);
16901        i32_const(code, stride);
16902        code.push(0x6C);
16903        code.push(0x6A); // slot idx + 1
16904        i64_load(code, off);
16905        i64_store(code, off);
16906    }
16907    local_get(code, idx);
16908    i32_const(code, 1);
16909    code.push(0x6A);
16910    local_set(code, idx);
16911    code.push(0x0C);
16912    leb_u32(code, 0); // br $shift
16913    code.push(0x0B); // end loop
16914    code.push(0x0B); // end block
16915                     // num -= 1
16916    local_get(code, c);
16917    local_get(code, c);
16918    i32_load(code, 0);
16919    i32_const(code, 1);
16920    code.push(0x6B);
16921    i32_store(code, 0);
16922    i32_const(code, 1);
16923    local_set(code, found);
16924    code.push(0x0C);
16925    leb_u32(code, 2); // br block (removed)
16926    code.push(0x0B); // end if
16927    local_get(code, idx);
16928    i32_const(code, 1);
16929    code.push(0x6A);
16930    local_set(code, idx);
16931    code.push(0x0C);
16932    leb_u32(code, 0);
16933    code.push(0x0B);
16934    code.push(0x0B);
16935    Ok(())
16936}
16937
16938/// `Set of Int` add (`Add value to s`): linear-scan for `value`; if already present do nothing,
16939/// else append it (reallocating the element buffer, like `ListPush`). `value` must be `Int`.
16940fn lower_set_add(
16941    code: &mut Vec<u8>,
16942    kinds: &KindTable,
16943    ctx: &Ctx,
16944    num_regs: u32,
16945    set: u16,
16946    value: u16,
16947) -> R<()> {
16948    let is_text = matches!(
16949        kinds.get(set as usize),
16950        Some(Kind::SetText) | Some(Kind::CrdtSetText)
16951    );
16952    if is_text {
16953        if kinds.get(value as usize) != Some(Kind::Text) {
16954            return Err(WasmLowerError::Unsupported(
16955                "adding a non-Text value to a Set of Text",
16956            ));
16957        }
16958    } else if kinds.get(value as usize) != Some(Kind::Int) {
16959        return Err(WasmLowerError::Unsupported(
16960            "set with a non-Int value (only Set of Int/Text)",
16961        ));
16962    }
16963    let order = if kinds.get(set as usize) == Some(Kind::CrdtSetText) {
16964        SetOrder::Sorted
16965    } else {
16966        SetOrder::Insertion
16967    };
16968    emit_set_add_elem(
16969        code,
16970        ctx,
16971        num_regs,
16972        set as u32,
16973        value as u32,
16974        is_text,
16975        order,
16976    );
16977    Ok(())
16978}
16979
16980/// Where a set keeps a new element: at the end (a `Set`, which displays in insertion order), or at its
16981/// sorted position (a CRDT set, whose replicas agree on contents and not on arrival order, and which
16982/// displays sorted on every tier).
16983#[derive(Clone, Copy, PartialEq, Eq)]
16984enum SetOrder {
16985    Insertion,
16986    Sorted,
16987}
16988
16989/// The add-if-absent core of [`lower_set_add`], over raw locals: scan the set whose handle is in
16990/// `set` for the value already held in `elem`; if absent, append it (realloc, like `ListPush`) and,
16991/// for a [`SetOrder::Sorted`] set, move it down to its sorted place. Uses the `+5`/`+6`/`+7` i32
16992/// scratch (`idx`/`found`/`new`), and `+8..+11` for a sorted insert, over an 8-byte stride. `set`
16993/// and `elem` must be locals untouched by those scratch slots — so union/intersect can drive it in a
16994/// loop with their own outer counter (`+9`) and loaded element (`+1`). `is_text` selects BYTE
16995/// equality (a `Set of Text`; the slot's low word is a Text handle) over `i64.eq`; a sorted set is a
16996/// set of Text, ordered by bytes as `String`'s `Ord` is.
16997fn emit_set_add_elem(
16998    code: &mut Vec<u8>,
16999    ctx: &Ctx,
17000    num_regs: u32,
17001    s: u32,
17002    elem: u32,
17003    is_text: bool,
17004    order: SetOrder,
17005) {
17006    let (idx, found, new) = (num_regs + 5, num_regs + 6, num_regs + 7);
17007    // scan for an existing equal value
17008    i32_const(code, 0);
17009    local_set(code, idx);
17010    i32_const(code, 0);
17011    local_set(code, found);
17012    code.push(0x02);
17013    code.push(0x40);
17014    code.push(0x03);
17015    code.push(0x40);
17016    local_get(code, idx);
17017    local_get(code, s);
17018    i32_load(code, 0); // num
17019    code.push(0x4E); // i32.ge_s
17020    code.push(0x0D);
17021    leb_u32(code, 1); // br_if block
17022    emit_set_elem_eq(code, ctx, num_regs, s, idx, elem, is_text); // set[idx] == elem ?
17023    code.push(0x04);
17024    code.push(0x40); // if (present)
17025    i32_const(code, 1);
17026    local_set(code, found);
17027    code.push(0x0C);
17028    leb_u32(code, 2); // br block (already a member)
17029    code.push(0x0B);
17030    local_get(code, idx);
17031    i32_const(code, 1);
17032    code.push(0x6A);
17033    local_set(code, idx);
17034    code.push(0x0C);
17035    leb_u32(code, 0);
17036    code.push(0x0B);
17037    code.push(0x0B);
17038    // if not present: append — write in place when a slot is free (num < cap); otherwise double
17039    // the capacity, copy the existing elements across, and free the buffer growth abandons —
17040    // dead by construction, exactly as `lower_list_push_at` grows a sequence.
17041    //
17042    // ★ +8/+9 ARE LIVE ACROSS THIS CALL IN A CALLER, NOT MERELY SCRATCH. `a union b` /
17043    // `a intersection b` (`emit_set_copy_loop`) build their result set through `s` itself
17044    // aliasing +8 and keep their outer scan counter in +9 across every element add — a growth
17045    // scratch at either would corrupt the set being built rather than a spare temp, which is
17046    // why the new capacity gets its own dedicated local instead.
17047    let new_cap = num_regs + 23;
17048    local_get(code, found);
17049    code.push(0x45); // i32.eqz
17050    code.push(0x04);
17051    code.push(0x40); // if (!present)
17052    local_get(code, s);
17053    i32_load(code, 0); // num
17054    local_get(code, s);
17055    i32_load(code, 4); // cap
17056    code.push(0x4E); // i32.ge_s → num >= cap
17057    code.push(0x04);
17058    code.push(0x40); // if (grow)
17059    {
17060        // new_cap = cap == 0 ? 4 : cap * 2
17061        i32_const(code, 4);
17062        local_get(code, s);
17063        i32_load(code, 4);
17064        i32_const(code, 2);
17065        code.push(0x6C);
17066        local_get(code, s);
17067        i32_load(code, 4);
17068        code.push(0x45); // i32.eqz → cap == 0
17069        code.push(0x1B); // select
17070        local_set(code, new_cap);
17071        local_get(code, new_cap);
17072        i32_const(code, 8);
17073        code.push(0x6C);
17074        emit_alloc(code, ctx, new, AllocClass::Raw); // new = alloc(new_cap * 8)
17075        emit_seq_copy(code, idx, new, s, s, false); // copy the num existing values
17076                                                    // The old element buffer is dead by construction: this header is the only holder and is
17077                                                    // about to stop pointing at it, read before the header is repointed.
17078        emit_free(
17079            code,
17080            ctx,
17081            |c| {
17082                local_get(c, s);
17083                i32_load(c, 8); // the OLD data_ptr
17084            },
17085            |c| {
17086                local_get(c, s);
17087                i32_load(c, 4); // the OLD cap
17088                i32_const(c, 8);
17089                c.push(0x6C);
17090            },
17091        );
17092        local_get(code, s);
17093        local_get(code, new);
17094        i32_store(code, 8); // data_ptr = new
17095        local_get(code, s);
17096        local_get(code, new_cap);
17097        i32_store(code, 4); // cap = new_cap
17098    }
17099    code.push(0x0B); // end if (grow)
17100                     // slot[num] = elem — `s`'s data_ptr already names the buffer with room, whichever branch
17101                     // above ran. A Text value's slot high word is never read (only its low-word handle is), so
17102                     // whatever a reused block leaves there does not matter.
17103    local_get(code, s);
17104    i32_load(code, 8);
17105    local_get(code, s);
17106    i32_load(code, 0);
17107    i32_const(code, 8);
17108    code.push(0x6C);
17109    code.push(0x6A);
17110    local_get(code, elem);
17111    if is_text {
17112        i32_store(code, 0); // slot[num] = handle
17113                            // S8's true count: the set is a further holder of the Text it now keeps.
17114        if ctx.heap_counting() {
17115            emit_true_retain_of(code, ctx, |c| local_get(c, elem));
17116        }
17117    } else {
17118        i64_store(code, 0); // slot[num] = value
17119    }
17120    local_get(code, s);
17121    local_get(code, s);
17122    i32_load(code, 0);
17123    i32_const(code, 1);
17124    code.push(0x6A);
17125    i32_store(code, 0); // num += 1
17126    if order == SetOrder::Sorted {
17127        emit_sink_last_to_sorted_place(code, num_regs, s, elem, is_text);
17128    }
17129    code.push(0x0B); // end if (!present)
17130}
17131
17132/// Move the element just appended to the set in `s` (its last slot, value in `elem`) down to its
17133/// sorted place: every earlier element greater than it moves up one slot. A Text orders by bytes, an
17134/// Int numerically — `CrdtScalar`'s `Ord`. Scratch `+11` is the slot being filled; the previous
17135/// element sits in `+8` (a Text handle) or `+16` (an Int), and `+9`/`+10` serve the byte comparison.
17136fn emit_sink_last_to_sorted_place(
17137    code: &mut Vec<u8>,
17138    num_regs: u32,
17139    s: u32,
17140    elem: u32,
17141    is_text: bool,
17142) {
17143    let at = num_regs + 11;
17144    let prev = if is_text { num_regs + 8 } else { num_regs + 16 };
17145    let slot_at = |code: &mut Vec<u8>, minus_one: bool| {
17146        local_get(code, s);
17147        i32_load(code, 8);
17148        local_get(code, at);
17149        if minus_one {
17150            i32_const(code, 1);
17151            code.push(0x6B);
17152        }
17153        i32_const(code, 8);
17154        code.push(0x6C);
17155        code.push(0x6A);
17156    };
17157    // at = num - 1
17158    local_get(code, s);
17159    i32_load(code, 0);
17160    i32_const(code, 1);
17161    code.push(0x6B);
17162    local_set(code, at);
17163    code.push(0x02);
17164    code.push(0x40); // block $placed
17165    code.push(0x03);
17166    code.push(0x40); // loop $sink
17167    local_get(code, at);
17168    code.push(0x45); // i32.eqz → at == 0
17169    code.push(0x0D);
17170    leb_u32(code, 1); // br_if $placed
17171                      // prev = slot[at - 1]; stop once prev < elem (no two elements are equal: the add scanned first)
17172    slot_at(code, true);
17173    if is_text {
17174        i32_load(code, 0);
17175        local_set(code, prev);
17176        emit_text_handles_lt(code, num_regs, prev, elem);
17177    } else {
17178        i64_load(code, 0);
17179        local_set(code, prev);
17180        local_get(code, prev);
17181        local_get(code, elem);
17182        code.push(0x53); // i64.lt_s
17183    }
17184    code.push(0x0D);
17185    leb_u32(code, 1); // br_if $placed
17186                      // slot[at] = prev; at -= 1
17187    slot_at(code, false);
17188    local_get(code, prev);
17189    if is_text {
17190        i32_store(code, 0);
17191    } else {
17192        i64_store(code, 0);
17193    }
17194    local_get(code, at);
17195    i32_const(code, 1);
17196    code.push(0x6B);
17197    local_set(code, at);
17198    code.push(0x0C);
17199    leb_u32(code, 0); // br $sink
17200    code.push(0x0B); // end loop
17201    code.push(0x0B); // end block
17202                     // slot[at] = elem
17203    slot_at(code, false);
17204    local_get(code, elem);
17205    if is_text {
17206        i32_store(code, 0);
17207    } else {
17208        i64_store(code, 0);
17209    }
17210}
17211
17212/// Whether the Text in local `a` sorts before the Text in local `b`, as an i32 on the stack: the
17213/// first differing byte decides (compared unsigned, so UTF-8 orders as code points), and a proper
17214/// prefix sorts first — `String`'s `Ord`. Scratch `+9` (byte index) and `+10` (answer).
17215fn emit_text_handles_lt(code: &mut Vec<u8>, num_regs: u32, a: u32, b: u32) {
17216    let (i, res) = (num_regs + 9, num_regs + 10);
17217    i32_const(code, 0);
17218    local_set(code, i);
17219    code.push(0x02);
17220    code.push(0x40); // block $decided
17221    code.push(0x03);
17222    code.push(0x40); // loop $bytes
17223                     // one of them ran out: the shorter sorts first
17224    local_get(code, i);
17225    local_get(code, a);
17226    i32_load(code, 0);
17227    code.push(0x4F); // i32.ge_u → i >= len_a
17228    local_get(code, i);
17229    local_get(code, b);
17230    i32_load(code, 0);
17231    code.push(0x4F); // i32.ge_u → i >= len_b
17232    code.push(0x72); // i32.or
17233    code.push(0x04);
17234    code.push(0x40); // if
17235    local_get(code, a);
17236    i32_load(code, 0);
17237    local_get(code, b);
17238    i32_load(code, 0);
17239    code.push(0x49); // i32.lt_u → len_a < len_b
17240    local_set(code, res);
17241    code.push(0x0C);
17242    leb_u32(code, 2); // br $decided
17243    code.push(0x0B); // end if
17244                     // the bytes at i differ: that byte decides
17245    local_get(code, a);
17246    i32_load(code, 8);
17247    local_get(code, i);
17248    code.push(0x6A);
17249    i32_load8_u(code, 0);
17250    local_get(code, b);
17251    i32_load(code, 8);
17252    local_get(code, i);
17253    code.push(0x6A);
17254    i32_load8_u(code, 0);
17255    code.push(0x47); // i32.ne
17256    code.push(0x04);
17257    code.push(0x40); // if
17258    local_get(code, a);
17259    i32_load(code, 8);
17260    local_get(code, i);
17261    code.push(0x6A);
17262    i32_load8_u(code, 0);
17263    local_get(code, b);
17264    i32_load(code, 8);
17265    local_get(code, i);
17266    code.push(0x6A);
17267    i32_load8_u(code, 0);
17268    code.push(0x49); // i32.lt_u
17269    local_set(code, res);
17270    code.push(0x0C);
17271    leb_u32(code, 2); // br $decided
17272    code.push(0x0B); // end if
17273    local_get(code, i);
17274    i32_const(code, 1);
17275    code.push(0x6A);
17276    local_set(code, i);
17277    code.push(0x0C);
17278    leb_u32(code, 0); // br $bytes
17279    code.push(0x0B); // end loop
17280    code.push(0x0B); // end block
17281    local_get(code, res);
17282}
17283
17284/// Set membership of the i64 in `elem` against the set whose handle is in `set` → `1`/`0` in `out`
17285/// (using `idx` as the byte-loop counter). The value-local form of [`lower_contains`]'s scan, so
17286/// it can gate per-element copies inside the intersection loop.
17287fn emit_set_contains_to(code: &mut Vec<u8>, set: u32, elem: u32, out: u32, idx: u32) {
17288    i32_const(code, 0);
17289    local_set(code, out); // assume absent
17290    i32_const(code, 0);
17291    local_set(code, idx);
17292    code.push(0x02);
17293    code.push(0x40); // block $exit
17294    code.push(0x03);
17295    code.push(0x40); // loop $loop
17296    local_get(code, idx);
17297    local_get(code, set);
17298    i32_load(code, 0); // num
17299    code.push(0x4E); // i32.ge_s
17300    code.push(0x0D);
17301    leb_u32(code, 1); // br_if $exit
17302    local_get(code, set);
17303    i32_load(code, 8); // data_ptr
17304    local_get(code, idx);
17305    i32_const(code, 8);
17306    code.push(0x6C);
17307    code.push(0x6A);
17308    i64_load(code, 0); // element
17309    local_get(code, elem);
17310    code.push(0x51); // i64.eq
17311    code.push(0x04);
17312    code.push(0x40); // if (present)
17313    i32_const(code, 1);
17314    local_set(code, out);
17315    code.push(0x0C);
17316    leb_u32(code, 2); // br $exit
17317    code.push(0x0B); // end if
17318    local_get(code, idx);
17319    i32_const(code, 1);
17320    code.push(0x6A);
17321    local_set(code, idx);
17322    code.push(0x0C);
17323    leb_u32(code, 0); // br $loop
17324    code.push(0x0B); // end loop
17325    code.push(0x0B); // end block
17326}
17327
17328/// Walk the source set `src` element-by-element (outer counter in `+9`, each element loaded into the
17329/// i64 scratch `+1`) and feed each through [`emit_set_add_elem`] into `result` (whose add-if-absent
17330/// dedups). With `filter = Some(other)`, only elements also present in `other` are copied — the
17331/// intersection gate. The inner add uses `+5`/`+6`/`+7`; the membership scan uses `+10`/`+11`; none
17332/// collide with the outer counter, the element, or `result` (`+8`), so the nest is sound.
17333fn emit_set_copy_loop(
17334    code: &mut Vec<u8>,
17335    ctx: &Ctx,
17336    num_regs: u32,
17337    result: u32,
17338    src: u32,
17339    filter: Option<u32>,
17340) {
17341    let outer = num_regs + 9;
17342    let elem = num_regs + 1;
17343    let (cidx, cfound) = (num_regs + 10, num_regs + 11);
17344    i32_const(code, 0);
17345    local_set(code, outer);
17346    code.push(0x02);
17347    code.push(0x40); // block $exit
17348    code.push(0x03);
17349    code.push(0x40); // loop $loop
17350    local_get(code, outer);
17351    local_get(code, src);
17352    i32_load(code, 0); // len(src)
17353    code.push(0x4E); // i32.ge_s
17354    code.push(0x0D);
17355    leb_u32(code, 1); // br_if $exit
17356                      // elem = src.data[outer*8]
17357    local_get(code, src);
17358    i32_load(code, 8);
17359    local_get(code, outer);
17360    i32_const(code, 8);
17361    code.push(0x6C);
17362    code.push(0x6A);
17363    i64_load(code, 0);
17364    local_set(code, elem);
17365    match filter {
17366        None => emit_set_add_elem(
17367            code,
17368            ctx,
17369            num_regs,
17370            result,
17371            elem,
17372            false,
17373            SetOrder::Insertion,
17374        ),
17375        Some(other) => {
17376            emit_set_contains_to(code, other, elem, cfound, cidx);
17377            local_get(code, cfound);
17378            code.push(0x04);
17379            code.push(0x40); // if (in `other`)
17380            emit_set_add_elem(
17381                code,
17382                ctx,
17383                num_regs,
17384                result,
17385                elem,
17386                false,
17387                SetOrder::Insertion,
17388            );
17389            code.push(0x0B); // end if
17390        }
17391    }
17392    // outer++
17393    local_get(code, outer);
17394    i32_const(code, 1);
17395    code.push(0x6A);
17396    local_set(code, outer);
17397    code.push(0x0C);
17398    leb_u32(code, 0); // br $loop
17399    code.push(0x0B); // end loop
17400    code.push(0x0B); // end block
17401}
17402
17403/// `a union b` — a fresh `Set` of `a`'s elements (in `a`'s order) followed by `b`'s not-already-
17404/// present elements (in `b`'s order), matching `semantics::collections::union` byte-for-byte
17405/// (`add`'s dedup makes empty-then-add-all-of-a-then-add-all-of-b equal to clone-a-then-add-b,
17406/// since a Set has no internal duplicates). Built into the `+8` scratch handle, then bound to
17407/// `dst` — so a `dst` aliasing `lhs`/`rhs` reads the originals fully before being overwritten.
17408fn lower_union(
17409    code: &mut Vec<u8>,
17410    kinds: &KindTable,
17411    ctx: &Ctx,
17412    num_regs: u32,
17413    dst: u16,
17414    lhs: u16,
17415    rhs: u16,
17416) -> R<()> {
17417    require_set(kinds, lhs)?;
17418    require_set(kinds, rhs)?;
17419    let result = num_regs + 8;
17420    // `require_set` only accepts plain `Kind::Set` (Int elements) — `SetText` union/intersect is
17421    // refused above — so the result is always a scalar-element header.
17422    emit_empty_header(code, ctx, num_regs, result, AllocClass::ScalarHeader);
17423    emit_set_copy_loop(code, ctx, num_regs, result, lhs as u32, None);
17424    emit_set_copy_loop(code, ctx, num_regs, result, rhs as u32, None);
17425    local_get(code, result);
17426    local_set(code, dst as u32);
17427    Ok(())
17428}
17429
17430/// `a intersection b` — a fresh `Set` of `a`'s elements (in `a`'s order) that are also in `b`,
17431/// matching `semantics::collections::intersection`. Same build-into-`+8`-then-bind discipline as
17432/// [`lower_union`].
17433fn lower_intersect(
17434    code: &mut Vec<u8>,
17435    kinds: &KindTable,
17436    ctx: &Ctx,
17437    num_regs: u32,
17438    dst: u16,
17439    lhs: u16,
17440    rhs: u16,
17441) -> R<()> {
17442    require_set(kinds, lhs)?;
17443    require_set(kinds, rhs)?;
17444    let result = num_regs + 8;
17445    emit_empty_header(code, ctx, num_regs, result, AllocClass::ScalarHeader);
17446    emit_set_copy_loop(code, ctx, num_regs, result, lhs as u32, Some(rhs as u32));
17447    local_get(code, result);
17448    local_set(code, dst as u32);
17449    Ok(())
17450}
17451
17452/// Require a `Set` operand for union/intersection (our Sets only ever hold Int, so a `Set` kind is
17453/// enough to license the 8-byte-stride element copy).
17454fn require_set(kinds: &KindTable, r: u16) -> R<()> {
17455    if kinds.get(r as usize) == Some(Kind::Set) {
17456        Ok(())
17457    } else {
17458        Err(WasmLowerError::Unsupported(
17459            "union/intersect of a non-Set value",
17460        ))
17461    }
17462}
17463
17464/// `seq contains value` / `set contains value` — a linear membership scan (value equality,
17465/// matching the tree-walker's `List::position` / set membership): `dst = 1` if any element equals
17466/// `value`, else `0`. Int/Set-of-Int compare with `i64.eq`, Float with `f64.eq`.
17467fn lower_contains(
17468    code: &mut Vec<u8>,
17469    kinds: &KindTable,
17470    ctx: &Ctx,
17471    num_regs: u32,
17472    dst: u16,
17473    collection: u16,
17474    value: u16,
17475) -> R<()> {
17476    let set_text = matches!(
17477        kinds.get(collection as usize),
17478        Some(Kind::SetText) | Some(Kind::CrdtSetText)
17479    );
17480    let elem = match kinds.get(collection as usize) {
17481        Some(Kind::Set) => Kind::Int, // a Set of Int holds i64 values
17482        Some(Kind::SetText) | Some(Kind::CrdtSetText) => Kind::Text, // a Set of Text scans by byte equality
17483        _ => seq_elem_kind(kinds, collection)?,
17484    };
17485    // A `Set of Text` `contains` DOES value (byte) equality (below); a plain `seq of Text contains
17486    // text` is still deferred (the scalar membership scan would wrongly compare Text handle pointers).
17487    if elem == Kind::Text && !set_text {
17488        return Err(WasmLowerError::Unsupported(
17489            "contains over a sequence of Text (needs byte-equality)",
17490        ));
17491    }
17492    let (elem_load, elem_eq): (fn(&mut Vec<u8>, u32), u8) = if elem == Kind::Float {
17493        (f64_load, 0x61)
17494    } else {
17495        (i64_load, 0x51)
17496    };
17497    let idx = num_regs + 5; // i32 scratch
17498    let col = collection as u32;
17499    // dst = 0
17500    code.push(0x42);
17501    leb_i64(code, 0);
17502    local_set(code, dst as u32);
17503    // idx = 0
17504    i32_const(code, 0);
17505    local_set(code, idx);
17506    code.push(0x02);
17507    code.push(0x40); // block $exit
17508    code.push(0x03);
17509    code.push(0x40); // loop $loop
17510                     // if idx >= len: break
17511    local_get(code, idx);
17512    local_get(code, col);
17513    i32_load(code, 0); // len
17514    code.push(0x4E); // i32.ge_s
17515    code.push(0x0D);
17516    leb_u32(code, 1); // br_if $exit
17517                      // element == value ? — a Set of Text compares bytes, everything else `i64.eq`/`f64.eq`.
17518    if set_text {
17519        emit_set_elem_eq(code, ctx, num_regs, col, idx, value as u32, true);
17520    } else {
17521        local_get(code, col);
17522        i32_load(code, 8); // data_ptr
17523        local_get(code, idx);
17524        i32_const(code, 8);
17525        code.push(0x6C);
17526        code.push(0x6A);
17527        elem_load(code, 0);
17528        local_get(code, value as u32);
17529        code.push(elem_eq);
17530    }
17531    code.push(0x04);
17532    code.push(0x40); // if (void)
17533    code.push(0x42);
17534    leb_i64(code, 1);
17535    local_set(code, dst as u32); // dst = 1
17536    code.push(0x0C);
17537    leb_u32(code, 2); // br $exit (out of if → loop → block)
17538    code.push(0x0B); // end if
17539                     // idx++
17540    local_get(code, idx);
17541    i32_const(code, 1);
17542    code.push(0x6A);
17543    local_set(code, idx);
17544    code.push(0x0C);
17545    leb_u32(code, 0); // br $loop
17546    code.push(0x0B); // end loop
17547    code.push(0x0B); // end block
17548    Ok(())
17549}
17550
17551/// `lhs + rhs` (the tree-walker's `arith::concat`): stringify each operand and concatenate the
17552/// UTF-8 bytes into a fresh `Text`. A `Text` operand is its own bytes; an `Int` operand is
17553/// formatted by the host `fmt_i64_into` (string interpolation `"… {n} …"` lowers to this). Other
17554/// operand kinds (Float/Bool stringification) are not yet built.
17555fn lower_concat(code: &mut Vec<u8>, plan: &Plan, ctx: &Ctx, dst: u16, lhs: u16, rhs: u16) -> R<()> {
17556    // Render each operand into a Text handle held in a dedicated scratch local (the byte-copy below
17557    // reads their headers; rendering only borrows the +5/+6/+7 temps or calls a display function, so
17558    // the two handles in +8/+9 survive across both and the copy).
17559    let (a, b) = (plan.num_regs + 8, plan.num_regs + 9);
17560    display::emit_display_of(code, plan, ctx, lhs, a)?;
17561    display::emit_display_of(code, plan, ctx, rhs, b)?;
17562    emit_text_concat(code, ctx, plan.num_regs, a, b, dst as u32);
17563    Ok(())
17564}
17565
17566/// The alignment + width of a non-precision format spec: `>N` (right, code 0), `<N` (left, 1), `^N`
17567/// (center, 2), or a bare width `N` (right — matching `apply_format_spec`'s default). `None` for a spec
17568/// this backend doesn't lower (e.g. the `$` currency spec).
17569fn parse_align_spec(spec: &str) -> Option<(i32, u32)> {
17570    if let Some(first) = spec.as_bytes().first() {
17571        let align = match first {
17572            b'>' => Some(0),
17573            b'<' => Some(1),
17574            b'^' => Some(2),
17575            _ => None,
17576        };
17577        if let Some(a) = align {
17578            return spec[1..].parse::<u32>().ok().map(|w| (a, w));
17579        }
17580    }
17581    // A bare width is right-aligned (`format!("{:>w$}", s)`).
17582    spec.parse::<u32>().ok().map(|w| (0, w))
17583}
17584
17585/// `"{x:.9}"` / `"{x:>6}"` / `"{x=}"` — a formatted interpolation piece. The VM's `FormatValue`
17586/// renders `debug_prefix? + format(src, spec?)`: an optional `name=` prefix (the `{x=}` debug form),
17587/// then the value under its spec (or its default display when there is none). This lowers the value
17588/// piece into `dst` via [`lower_format_value_piece`], then — for a debug piece — prepends the constant
17589/// `name=` `Text` (concat `prefix ++ dst -> dst`), byte-identical to the VM's `String` assembly. The
17590/// prefix is a compile-time `Text` constant; the `$` currency spec is still refused (a documented deferral).
17591fn lower_format_value(
17592    code: &mut Vec<u8>,
17593    plan: &Plan,
17594    ctx: &Ctx,
17595    dst: u16,
17596    src: u16,
17597    spec: u32,
17598    debug_prefix: u32,
17599) -> R<()> {
17600    let num_regs = plan.num_regs;
17601    // The `{x=}` debug piece prepends `name=` to the value. Resolve the prefix `Text` constant now,
17602    // append the literal `=`, and materialize it — after the value is formatted into `dst`, concat it
17603    // in front, matching the VM's `out.push_str(prefix); out.push('='); out.push_str(value)`.
17604    let prefix_bytes = match debug_prefix {
17605        u32::MAX => None,
17606        idx => match ctx.constants.get(idx as usize) {
17607            Some(Constant::Text(s)) => Some(format!("{s}=")),
17608            _ => {
17609                return Err(WasmLowerError::Unsupported(
17610                    "debug prefix is not a text constant",
17611                ))
17612            }
17613        },
17614    };
17615    lower_format_value_piece(code, plan, ctx, dst, src, spec)?;
17616    if let Some(prefix) = prefix_bytes {
17617        // prefix in +8, formatted value in +9 (i32 handle scratch, disjoint from concat's +5/+6/+7);
17618        // out = prefix ++ value → dst.
17619        let (pfx, val) = (num_regs + 8, num_regs + 9);
17620        local_get(code, dst as u32);
17621        local_set(code, val);
17622        lower_text_literal(code, ctx, num_regs, prefix.as_bytes());
17623        local_set(code, pfx);
17624        emit_text_concat(code, ctx, num_regs, pfx, val, dst as u32);
17625    }
17626    Ok(())
17627}
17628
17629/// Render `src` under its format spec into a fresh `Text` handle stored in `dst` (the value piece of
17630/// [`lower_format_value`], no debug prefix). A `None` spec (`u32::MAX`) uses the value's default display
17631/// (`to_display_string` via [`emit_stringify`]); `.N` precision and `>N`/`<N`/`^N`/bare-`N` alignment/width
17632/// run the same host formatters the VM's `apply_format_spec` does.
17633fn lower_format_value_piece(
17634    code: &mut Vec<u8>,
17635    plan: &Plan,
17636    ctx: &Ctx,
17637    dst: u16,
17638    src: u16,
17639    spec: u32,
17640) -> R<()> {
17641    let (kinds, num_regs) = (&plan.kinds, plan.num_regs);
17642    let spec_s = match spec {
17643        // No spec: the value's default display, exactly the VM's `reg(src).to_display_string()`.
17644        u32::MAX => {
17645            display::emit_display_of(code, plan, ctx, src, dst as u32)?;
17646            return Ok(());
17647        }
17648        idx => match ctx.constants.get(idx as usize) {
17649            Some(Constant::Text(s)) => s.as_str(),
17650            _ => {
17651                return Err(WasmLowerError::Unsupported(
17652                    "format spec is not a text constant",
17653                ))
17654            }
17655        },
17656    };
17657    // Alignment / bare-width spec: stringify the value (any stringifiable kind), then pad to `width`
17658    // with spaces via `fmt_align_into` (the SAME Rust `format!` `apply_format_spec` runs).
17659    if !spec_s.starts_with('.') {
17660        let (align, width) = parse_align_spec(spec_s)
17661            .ok_or(WasmLowerError::Unsupported("unsupported format spec"))?;
17662        let fidx = (ctx.host_index)(HostFn::FmtAlignInto)
17663            .ok_or(WasmLowerError::Unsupported("align formatter not imported"))?;
17664        let (hdr, data, len, text) = (num_regs + 5, num_regs + 6, num_regs + 7, num_regs + 9);
17665        // text = stringify(src) — a Text handle (`fmt_align_into` reads its bytes)
17666        display::emit_display_of(code, plan, ctx, src, text)?;
17667        // data = alloc(text.len + width) — padding adds at most `width` single-byte spaces
17668        local_get(code, text);
17669        i32_load(code, 0);
17670        i32_const(code, width as i32);
17671        code.push(0x6A); // i32.add
17672        emit_alloc(code, ctx, data, AllocClass::Raw);
17673        // len = fmt_align_into(data, text, width, align)
17674        local_get(code, data);
17675        local_get(code, text);
17676        i32_const(code, width as i32);
17677        i32_const(code, align);
17678        code.push(0x10); // call
17679        leb_u32(code, fidx);
17680        local_set(code, len);
17681        // hdr = alloc(16); header = [len, cap = the buffer's size, data_ptr=data] — the capacity is
17682        // what a free returns, so it names the whole buffer, not the bytes written into it.
17683        i32_const(code, 16);
17684        emit_alloc(code, ctx, hdr, AllocClass::TextHeader);
17685        local_get(code, hdr);
17686        local_get(code, len);
17687        i32_store(code, 0);
17688        local_get(code, hdr);
17689        local_get(code, text);
17690        i32_load(code, 0);
17691        i32_const(code, width as i32);
17692        code.push(0x6A); // i32.add
17693        i32_store(code, 4);
17694        local_get(code, hdr);
17695        local_get(code, data);
17696        i32_store(code, 8);
17697        local_get(code, hdr);
17698        local_set(code, dst as u32);
17699        return Ok(());
17700    }
17701    let prec = spec_s
17702        .strip_prefix('.')
17703        .and_then(|r| r.parse::<u32>().ok())
17704        .ok_or(WasmLowerError::Unsupported(
17705            "unsupported format spec (only `.N` precision)",
17706        ))?;
17707    match kinds.get(src as usize) {
17708        Some(Kind::Float) | Some(Kind::Int) | Some(Kind::Bool) => {}
17709        _ => {
17710            return Err(WasmLowerError::Unsupported(
17711                "format `.N` on a non-numeric value",
17712            ))
17713        }
17714    }
17715    let (hdr, data, len) = (num_regs + 5, num_regs + 6, num_regs + 7);
17716    // hdr = alloc(16); data = alloc(340 + prec) bytes (worst-case f64 integer width + the decimals)
17717    i32_const(code, 16);
17718    emit_alloc(code, ctx, hdr, AllocClass::TextHeader);
17719    i32_const(code, (340 + prec) as i32);
17720    emit_alloc(code, ctx, data, AllocClass::Raw);
17721    // len = fmt_f64_prec_into(data, src as f64, prec)
17722    let fidx = (ctx.host_index)(HostFn::FmtF64PrecInto).ok_or(WasmLowerError::Unsupported(
17723        "precision formatter not imported",
17724    ))?;
17725    local_get(code, data);
17726    push_as_f64(code, src, kinds.get(src as usize))?;
17727    i32_const(code, prec as i32);
17728    code.push(0x10); // call
17729    leb_u32(code, fidx);
17730    local_set(code, len);
17731    // header: len; cap = the buffer's size (what a free returns); data_ptr = data
17732    local_get(code, hdr);
17733    local_get(code, len);
17734    i32_store(code, 0);
17735    local_get(code, hdr);
17736    i32_const(code, (340 + prec) as i32);
17737    i32_store(code, 4);
17738    local_get(code, hdr);
17739    local_get(code, data);
17740    i32_store(code, 8);
17741    local_get(code, hdr);
17742    local_set(code, dst as u32);
17743    Ok(())
17744}
17745
17746/// Concatenate the two `Text` handles in locals `a` and `b` into a fresh `Text` whose handle is
17747/// stored in local `out`. Uses the +5/+6/+7 scratch as temps (so `a`/`b`/`out` must be other
17748/// locals); `out` may alias `a` (all reads happen before the final store).
17749fn emit_text_concat(code: &mut Vec<u8>, ctx: &Ctx, num_regs: u32, a: u32, b: u32, out: u32) {
17750    if let Some(concat) = ctx.runtime.and_then(|r| r.index(RuntimeFn::TextConcat)) {
17751        local_get(code, a);
17752        local_get(code, b);
17753        code.push(0x10);
17754        leb_u32(code, concat);
17755        local_set(code, out);
17756        return;
17757    }
17758    // A linked module has no runtime of its own: the copy inline.
17759    let (hdr, data, idx) = (num_regs + 5, num_regs + 6, num_regs + 7);
17760    i32_const(code, 16);
17761    emit_alloc(code, ctx, hdr, AllocClass::TextHeader);
17762    // data = alloc(len_a + len_b) bytes (the allocator re-aligns the next pointer, so the byte
17763    // buffer need not be padded)
17764    local_get(code, a);
17765    i32_load(code, 0);
17766    local_get(code, b);
17767    i32_load(code, 0);
17768    code.push(0x6A); // len_a + len_b
17769    emit_alloc(code, ctx, data, AllocClass::Raw);
17770    emit_byte_copy(code, idx, data, a, a, false); // a bytes at [0, len_a)
17771    emit_byte_copy(code, idx, data, a, b, true); // b bytes at [len_a, len_a+len_b)
17772    for off in [0u32, 4] {
17773        local_get(code, hdr);
17774        local_get(code, a);
17775        i32_load(code, 0);
17776        local_get(code, b);
17777        i32_load(code, 0);
17778        code.push(0x6A);
17779        i32_store(code, off);
17780    }
17781    local_get(code, hdr);
17782    local_get(code, data);
17783    i32_store(code, 8);
17784    local_get(code, hdr);
17785    local_set(code, out);
17786}
17787
17788/// The bit of a Text header's capacity word (word 4) that marks a GROWABLE buffer: one whose 4 bytes
17789/// before `data_ptr` hold its high-water mark, the length of the longest Text written into it so far,
17790/// and the 4 before those its VIEW COUNT, how many Text headers read it (an append in place adds a
17791/// view; the free cascade frees the buffer with its last view). Only [`emit_text_append`] allocates
17792/// one; every other Text's capacity is its buffer's size.
17793const TEXT_GROWABLE: i32 = i32::MIN;
17794
17795/// `out = a ++ b` as an APPEND to `a`: a fresh 16-byte header over a buffer that grows by doubling.
17796///
17797/// A Text is an immutable view `[len][cap][data_ptr]`, and several views may share one buffer. `a`'s
17798/// bytes are extended IN PLACE when its buffer is growable, has room, and `a` is its frontier — no view
17799/// has written past `a`'s length (the buffer's high-water mark equals `len(a)`). Then nothing any view
17800/// can read is overwritten: every existing view ends at or before the mark. Otherwise the append copies
17801/// `a` and `b` into a fresh growable buffer of twice the new length. A loop appending to one Text is
17802/// therefore linear in what it writes, as the VM's in-place `+=` is, and correct however the Text is
17803/// aliased.
17804fn emit_text_append(code: &mut Vec<u8>, ctx: &Ctx, num_regs: u32, a: u32, b: u32, out: u32) {
17805    let (hdr, data, idx, cap, len) = (
17806        num_regs + 5,
17807        num_regs + 6,
17808        num_regs + 7,
17809        num_regs + 10,
17810        num_regs + 11,
17811    );
17812    local_get(code, a);
17813    i32_load(code, 0);
17814    local_get(code, b);
17815    i32_load(code, 0);
17816    code.push(0x6A); // len = len(a) + len(b)
17817    local_set(code, len);
17818    local_get(code, a);
17819    i32_load(code, 4);
17820    local_set(code, cap);
17821    code.push(0x02); // block $built
17822    code.push(0x40);
17823    code.push(0x02); // block $copy
17824    code.push(0x40);
17825    // In place only for a growable buffer ...
17826    local_get(code, cap);
17827    i32_const(code, TEXT_GROWABLE);
17828    code.push(0x71); // i32.and
17829    code.push(0x45); // i32.eqz
17830    code.push(0x0D); // br_if $copy
17831    leb_u32(code, 0);
17832    // ... with room for the new length ...
17833    local_get(code, cap);
17834    i32_const(code, i32::MAX);
17835    code.push(0x71); // capacity bytes
17836    local_get(code, len);
17837    code.push(0x49); // i32.lt_u
17838    code.push(0x0D); // br_if $copy
17839    leb_u32(code, 0);
17840    // ... whose high-water mark is `a`'s own end.
17841    local_get(code, a);
17842    i32_load(code, 8);
17843    local_set(code, data);
17844    local_get(code, data);
17845    i32_const(code, 4);
17846    code.push(0x6B); // data - 4
17847    i32_load(code, 0);
17848    local_get(code, a);
17849    i32_load(code, 0);
17850    code.push(0x47); // i32.ne
17851    code.push(0x0D); // br_if $copy
17852    leb_u32(code, 0);
17853    emit_byte_copy(code, idx, data, a, b, true); // b's bytes at [len(a), len)
17854                                                 // One more view reads the buffer (the header built below).
17855    local_get(code, data);
17856    i32_const(code, 8);
17857    code.push(0x6B);
17858    local_get(code, data);
17859    i32_const(code, 8);
17860    code.push(0x6B);
17861    i32_load(code, 0);
17862    i32_const(code, 1);
17863    code.push(0x6A);
17864    i32_store(code, 0);
17865    code.push(0x0C); // br $built
17866    leb_u32(code, 1);
17867    code.push(0x0B); // end $copy
17868                     // A fresh growable buffer: its view count, its mark word, then twice the new length (at least
17869                     // 16 bytes).
17870    local_get(code, len);
17871    i32_const(code, 1);
17872    code.push(0x74); // i32.shl — len * 2
17873    local_tee(code, cap);
17874    i32_const(code, 16);
17875    local_get(code, cap);
17876    i32_const(code, 16);
17877    code.push(0x4B); // i32.gt_u
17878    code.push(0x1B); // select — max(len * 2, 16)
17879    local_set(code, cap);
17880    local_get(code, cap);
17881    i32_const(code, 8);
17882    code.push(0x6A);
17883    emit_alloc(code, ctx, data, AllocClass::Raw);
17884    local_get(code, data);
17885    i32_const(code, 1);
17886    i32_store(code, 0); // one view: the header built below
17887    local_get(code, data);
17888    i32_const(code, 8);
17889    code.push(0x6A);
17890    local_set(code, data);
17891    emit_byte_copy(code, idx, data, a, a, false); // a's bytes at [0, len(a))
17892    emit_byte_copy(code, idx, data, a, b, true); // b's bytes at [len(a), len)
17893    local_get(code, cap);
17894    i32_const(code, TEXT_GROWABLE);
17895    code.push(0x72); // i32.or — mark the buffer growable
17896    local_set(code, cap);
17897    code.push(0x0B); // end $built
17898                     // The buffer's high-water mark is now this Text's end.
17899    local_get(code, data);
17900    i32_const(code, 4);
17901    code.push(0x6B);
17902    local_get(code, len);
17903    i32_store(code, 0);
17904    i32_const(code, 16);
17905    emit_alloc(code, ctx, hdr, AllocClass::TextHeader);
17906    local_get(code, hdr);
17907    local_get(code, len);
17908    i32_store(code, 0);
17909    local_get(code, hdr);
17910    local_get(code, cap);
17911    i32_store(code, 4);
17912    local_get(code, hdr);
17913    local_get(code, data);
17914    i32_store(code, 8);
17915    local_get(code, hdr);
17916    local_set(code, out);
17917}
17918
17919/// Store opcode for an 8-byte struct field slot, by the value's kind (`i64`/`f64`/`i32`-handle).
17920/// An unknown kind cannot be stored at a definite width, so it is refused.
17921fn emit_slot_store(code: &mut Vec<u8>, k: Option<Kind>, off: u32) -> R<()> {
17922    match k {
17923        Some(Kind::Float) => f64_store(code, off),
17924        Some(Kind::Nothing) | Some(Kind::Int) | Some(Kind::Bool) | Some(Kind::Char)
17925        | Some(Kind::Moment) | Some(Kind::Duration) | Some(Kind::Time) | Some(Kind::Span)
17926        | Some(Kind::Word64) => i64_store(code, off),
17927        Some(Kind::Date)
17928        | Some(Kind::SeqInt)
17929        | Some(Kind::SeqBool)
17930        | Some(Kind::SeqFloat)
17931        | Some(Kind::SeqText)
17932        | Some(Kind::SeqStruct)
17933        | Some(Kind::SeqEnum)
17934        | Some(Kind::SeqSeqInt)
17935        | Some(Kind::SeqHandle)
17936        | Some(Kind::SeqAny)
17937        | Some(Kind::Text)
17938        | Some(Kind::Struct)
17939        | Some(Kind::Map)
17940        | Some(Kind::Set)
17941        | Some(Kind::SetText)
17942        | Some(Kind::CrdtSetText)
17943        | Some(Kind::CrdtCounter)
17944        | Some(Kind::Enum)
17945        | Some(Kind::Closure)
17946        | Some(Kind::Tuple)
17947        | Some(Kind::Rational)
17948        | Some(Kind::Optional)
17949        | Some(Kind::Word32)
17950        | Some(Kind::SeqWord32)
17951        | Some(Kind::SeqWord64)
17952        | Some(Kind::BigInt)
17953        | Some(Kind::Complex)
17954        | Some(Kind::Modular)
17955        | Some(Kind::Decimal)
17956        | Some(Kind::Money)
17957        | Some(Kind::Quantity)
17958        | Some(Kind::Uuid)
17959        | Some(Kind::Lanes)
17960        | Some(Kind::LanesV)
17961        | Some(Kind::Dynamic)
17962        | Some(Kind::Tower) => i32_store(code, off),
17963        None => return Err(WasmLowerError::Unsupported("struct field of unknown kind")),
17964    }
17965    Ok(())
17966}
17967
17968/// Load opcode for an 8-byte struct field slot — the mirror of [`emit_slot_store`].
17969fn emit_slot_load(code: &mut Vec<u8>, k: Option<Kind>, off: u32) -> R<()> {
17970    match k {
17971        Some(Kind::Float) => f64_load(code, off),
17972        Some(Kind::Nothing) | Some(Kind::Int) | Some(Kind::Bool) | Some(Kind::Char)
17973        | Some(Kind::Moment) | Some(Kind::Duration) | Some(Kind::Time) | Some(Kind::Span)
17974        | Some(Kind::Word64) => i64_load(code, off),
17975        Some(Kind::Date)
17976        | Some(Kind::SeqInt)
17977        | Some(Kind::SeqBool)
17978        | Some(Kind::SeqFloat)
17979        | Some(Kind::SeqText)
17980        | Some(Kind::SeqStruct)
17981        | Some(Kind::SeqEnum)
17982        | Some(Kind::SeqSeqInt)
17983        | Some(Kind::SeqHandle)
17984        | Some(Kind::SeqAny)
17985        | Some(Kind::Text)
17986        | Some(Kind::Struct)
17987        | Some(Kind::Map)
17988        | Some(Kind::Set)
17989        | Some(Kind::SetText)
17990        | Some(Kind::CrdtSetText)
17991        | Some(Kind::CrdtCounter)
17992        | Some(Kind::Enum)
17993        | Some(Kind::Closure)
17994        | Some(Kind::Tuple)
17995        | Some(Kind::Rational)
17996        | Some(Kind::Optional)
17997        | Some(Kind::Word32)
17998        | Some(Kind::SeqWord32)
17999        | Some(Kind::SeqWord64)
18000        | Some(Kind::BigInt)
18001        | Some(Kind::Complex)
18002        | Some(Kind::Modular)
18003        | Some(Kind::Decimal)
18004        | Some(Kind::Money)
18005        | Some(Kind::Quantity)
18006        | Some(Kind::Uuid)
18007        | Some(Kind::Lanes)
18008        | Some(Kind::LanesV)
18009        | Some(Kind::Dynamic)
18010        | Some(Kind::Tower) => i32_load(code, off),
18011        None => return Err(WasmLowerError::Unsupported("struct field of unknown kind")),
18012    }
18013    Ok(())
18014}
18015
18016/// `a new T with …` (`NewStruct`) — bump-allocate the header + a `count`-slot (8 bytes each) field
18017/// buffer (`count` from the static layout). Slots are filled by the following `StructInsert`s
18018/// (every field is inserted, provided or default-filled), so they need no zero-init.
18019fn lower_new_struct(code: &mut Vec<u8>, ctx: &Ctx, num_regs: u32, count: u16, dst: u16) {
18020    let (hdr, data) = (num_regs + 5, num_regs + 6);
18021    i32_const(code, 16);
18022    emit_alloc(code, ctx, hdr, AllocClass::RecordHeader);
18023    i32_const(
18024        code,
18025        i32::from(count) * if ctx.heap_counting() { 9 } else { 8 },
18026    );
18027    emit_alloc(code, ctx, data, AllocClass::Raw);
18028    local_get(code, hdr);
18029    i32_const(code, i32::from(count));
18030    i32_store(code, 0); // num_fields
18031    local_get(code, hdr);
18032    i32_const(code, i32::from(count));
18033    i32_store(code, 4); // cap
18034    local_get(code, hdr);
18035    local_get(code, data);
18036    i32_store(code, 8); // data_ptr
18037                        // Every slot starts empty when writes count holders: a block the allocator hands back from its
18038                        // free list still carries whatever was there, and a field's first write releases what the slot
18039                        // held.
18040    if ctx.heap_counting() {
18041        for k in 0..u32::from(count) {
18042            local_get(code, data);
18043            code.push(0x42); // i64.const 0
18044            code.push(0x00);
18045            i64_store(code, k * 8);
18046            local_get(code, data);
18047            i32_const(code, 0);
18048            i32_store8(code, u32::from(count) * 8 + k);
18049        }
18050    }
18051    local_get(code, hdr);
18052    local_set(code, dst as u32);
18053}
18054
18055/// `Set obj's field to value` (`StructInsert`) — store the value into its static slot, at the
18056/// width of the value's kind.
18057/// Which `StructInsert`s need COPY-ON-WRITE — a flow-sensitive uniqueness pass that keeps Logos's
18058/// struct VALUE semantics without cloning on the read path. Structs are heap objects behind shared
18059/// handles here, but the tree-walker/VM copy a struct on field access and assignment, so mutating an
18060/// extracted or aliased struct must not write through to the original. Rather than clone on every
18061/// `GetField` (the hot read path), we clone lazily at the WRITE: a `StructInsert` whose target is not
18062/// provably a uniquely-owned fresh struct copies first, then mutates the copy.
18063///
18064/// `owned` holds registers currently bound to a unique, unaliased struct: set by `NewStruct`/
18065/// `DeepClone`; preserved across the construction `StructInsert`s that fill it and across `GetField`
18066/// reads of it (reading a field does not alias the struct); cleared the moment the struct is consumed
18067/// as a value anywhere else (stored into a field/collection, moved, returned, passed to a call — any
18068/// op's def/use footprint, via the exhaustive [`crate::vm::instruction::op_def_uses`], so no aliasing operand is
18069/// missed). State is reset at every basic-block leader, a conservative join (a struct owned on only
18070/// some incoming paths is treated as shared → it copies, never miscompiles). So construction and
18071/// reads cost nothing; only a write to a possibly-shared struct pays one copy.
18072fn cow_struct_inserts(
18073    ops: &[Op],
18074    kinds: &KindTable,
18075    num_regs: u32,
18076    functions: &[CompiledFunction],
18077) -> Vec<bool> {
18078    // `Set collection[index] to value` (`SetIndex`) is a STRUCT field write, same as `StructInsert`,
18079    // exactly when its collection is a struct handle and its index a Text — the compiler's own
18080    // place-mutation write-back for a nested field (`w's stock["k"]` reassembles `w`'s "stock" field
18081    // this way after mutating the extracted map), matching `machine.rs`'s identical `is_struct_text`
18082    // dispatch. Every other `SetIndex` (Map/Seq/Set) keeps its own COW gate ([`emit_cow`]).
18083    let is_struct_write = |op: &Op| match op {
18084        Op::SetIndex { collection, .. } | Op::SetIndexUnchecked { collection, .. } => {
18085            kinds.get(*collection as usize) == Some(Kind::Struct)
18086        }
18087        _ => false,
18088    };
18089    let mut cow = vec![false; ops.len()];
18090    let Some(blocks) = Blocks::new(ops) else {
18091        // Not self-contained (rejected downstream); be safe and copy every struct write.
18092        for (pc, op) in ops.iter().enumerate() {
18093            if matches!(op, Op::StructInsert { .. }) || is_struct_write(op) {
18094                cow[pc] = true;
18095            }
18096        }
18097        return cow;
18098    };
18099    let mut owned = vec![false; num_regs as usize];
18100    let is_owned = |owned: &[bool], r: u16| (r as usize) < owned.len() && owned[r as usize];
18101    let set_owned = |owned: &mut [bool], r: u16, v: bool| {
18102        if (r as usize) < owned.len() {
18103            owned[r as usize] = v;
18104        }
18105    };
18106    for (pc, op) in ops.iter().enumerate() {
18107        if blocks.is_leader(pc) {
18108            owned.iter_mut().for_each(|o| *o = false);
18109        }
18110        match op {
18111            Op::NewStruct { dst, .. }
18112            | Op::DeepClone { dst, .. }
18113            | Op::CallBuiltin {
18114                dst,
18115                builtin: BuiltinId::Copy,
18116                ..
18117            } => set_owned(&mut owned, *dst, true),
18118            Op::StructInsert { obj, value, .. } => {
18119                if !is_owned(&owned, *obj) {
18120                    cow[pc] = true; // mutating a possibly-shared struct → copy first
18121                }
18122                set_owned(&mut owned, *value, false); // the stored value is now aliased by obj.field
18123                set_owned(&mut owned, *obj, true); // obj is uniquely owned after (fresh copy, or already)
18124            }
18125            Op::SetIndex {
18126                collection,
18127                index,
18128                value,
18129            }
18130            | Op::SetIndexUnchecked {
18131                collection,
18132                index,
18133                value,
18134            } if is_struct_write(op) => {
18135                if !is_owned(&owned, *collection) {
18136                    cow[pc] = true;
18137                }
18138                set_owned(&mut owned, *index, false);
18139                set_owned(&mut owned, *value, false);
18140                set_owned(&mut owned, *collection, true);
18141            }
18142            // A push onto a record's list field may give the record a list of its own (the field's
18143            // copy-on-write), which is a write to the record.
18144            Op::ListPushField { obj, src, .. } => {
18145                if !is_owned(&owned, *obj) {
18146                    cow[pc] = true;
18147                }
18148                set_owned(&mut owned, *src, false);
18149                set_owned(&mut owned, *obj, true);
18150            }
18151            Op::GetField { dst, .. } => set_owned(&mut owned, *dst, false), // a borrowed field handle
18152            _ => {
18153                let (defs, uses) = crate::vm::instruction::op_def_uses(op, functions);
18154                for r in defs.into_iter().chain(uses) {
18155                    set_owned(&mut owned, r, false);
18156                }
18157            }
18158        }
18159    }
18160    cow
18161}
18162
18163/// `Set obj's field to value` / a construction field-fill (`StructInsert`). When `cow`, the target
18164/// struct may be shared (extracted by `GetField` or stored elsewhere), so — to honor value semantics
18165/// — flat-copy it into a fresh object bound back to `obj` and mutate THAT; otherwise mutate in place.
18166#[allow(clippy::too_many_arguments)]
18167/// The declared representation of a record slot, including records passed across functions.
18168fn declared_record_slot_kind(
18169    structs: &kind::StructLayout,
18170    types: &[StructTypeDef],
18171    constants: &[Constant],
18172    obj: u16,
18173    slot: usize,
18174) -> Option<Kind> {
18175    if let Some(ParamShape::Struct(layout)) = structs.reg_shape.get(&obj) {
18176        return layout.get(slot).map(|(_, k, _)| *k);
18177    }
18178    if let Some(layout) = structs
18179        .struct_name_of
18180        .get(&obj)
18181        .and_then(|name| kind::resolve_named_layout(name, types, constants))
18182    {
18183        if let Some((field, _)) = structs.reg_layout.get(&obj).and_then(|v| v.get(slot)) {
18184            return layout
18185                .iter()
18186                .find(|(f, _, _)| f == field)
18187                .map(|(_, k, _)| *k);
18188        }
18189        return layout.get(slot).map(|(_, k, _)| *k);
18190    }
18191    structs
18192        .call_result
18193        .get(&obj)
18194        .and_then(|v| v.get(slot))
18195        .map(|(_, k, _)| *k)
18196}
18197
18198/// Materialize an integer as a Rational before storing it in a Rational field.
18199/// Its source register keeps its own scalar representation.
18200fn promote_rational_field(
18201    code: &mut Vec<u8>,
18202    kinds: &KindTable,
18203    structs: &kind::StructLayout,
18204    ctx: &Ctx,
18205    num_regs: u32,
18206    obj: u16,
18207    slot: usize,
18208    value: u16,
18209) -> R<Option<u32>> {
18210    if declared_record_slot_kind(structs, ctx.struct_types, ctx.constants, obj, slot) != Some(Kind::Rational) {
18211        return Ok(None);
18212    }
18213    // The language holds nothing in a rational field a record is built without, which a compiled rational cannot
18214    // hold.
18215    if kinds.get(value as usize) == Some(Kind::Nothing) {
18216        return Err(WasmLowerError::Unsupported(
18217            "a record's rational field holding nothing: a compiled rational holds no nothing",
18218        ));
18219    }
18220    let widened = if ctx.linked { matches!(kinds.get(value as usize), Some(Kind::Int | Kind::BigInt)) } else { kinds.get(value as usize) == Some(Kind::Int) };
18221    if !widened {
18222        return Ok(None);
18223    }
18224    let handle = num_regs + 8;
18225    if ctx.linked {
18226        push_rational_operand(code, kinds, ctx, value)?;
18227        local_set(code, handle);
18228    } else {
18229        let data = num_regs + 9;
18230        i32_const(code, 16);
18231        emit_alloc(code, ctx, handle, AllocClass::ScalarHeader);
18232        i32_const(code, 16);
18233        emit_alloc(code, ctx, data, AllocClass::Raw);
18234        for off in [0u32, 4] {
18235            local_get(code, handle);
18236            i32_const(code, 2);
18237            i32_store(code, off);
18238        }
18239        local_get(code, handle);
18240        local_get(code, data);
18241        i32_store(code, 8);
18242        local_get(code, data);
18243        local_get(code, value as u32);
18244        i64_store(code, 0);
18245        local_get(code, data);
18246        i64c(code, 1);
18247        i64_store(code, 8);
18248    }
18249    // The new field owns the promoted value beyond the allocating turn.
18250    emit_true_retain_of(code, ctx, |c| local_get(c, handle));
18251    Ok(Some(handle))
18252}
18253
18254/// Store `value` into `obj`'s field at `slot`; `held` is the local holding the field's own handle where the field or
18255/// the value is one of the exact extension ([`tower::field_value`]).
18256fn lower_struct_insert(
18257    code: &mut Vec<u8>,
18258    kinds: &KindTable,
18259    structs: &kind::StructLayout,
18260    ctx: &Ctx,
18261    num_regs: u32,
18262    slot: u16,
18263    obj: u16,
18264    value: u16,
18265    cow: bool,
18266    held: Option<u32>,
18267) -> R<()> {
18268    // The target must be a known Struct handle (an i32). A struct param has no static layout, so it
18269    // is typed as a scalar here — reject rather than treat the scalar as a heap pointer (which the
18270    // copy-on-write below would, emitting invalid wasm).
18271    if kinds.get(obj as usize) != Some(Kind::Struct) {
18272        return Err(WasmLowerError::Unsupported(
18273            "struct field set on a value with no known struct layout",
18274        ));
18275    }
18276    if cow {
18277        emit_record_copy(
18278            code,
18279            ctx,
18280            kinds,
18281            structs,
18282            num_regs,
18283            obj,
18284            Some(usize::from(slot)),
18285        )?;
18286    }
18287    let promoted = match held {
18288        Some(h) => Some(h),
18289        None => promote_rational_field(
18290            code,
18291            kinds,
18292            structs,
18293            ctx,
18294            num_regs,
18295            obj,
18296            usize::from(slot),
18297            value,
18298        )?,
18299    };
18300    let stored_kind = if held.is_some() {
18301        Some(Kind::Tower)
18302    } else if promoted.is_some() {
18303        Some(Kind::Rational)
18304    } else {
18305        kinds.get(value as usize)
18306    };
18307    let off = u32::from(slot) * 8;
18308    // S8's true count: the field stops holding the value it is about to overwrite (a fresh record's
18309    // slots start empty — `lower_new_struct`).
18310    if ctx.heap_counting() && counted_kind(stored_kind) {
18311        emit_true_release(code, ctx, |c| {
18312            local_get(c, obj as u32);
18313            i32_load(c, 8); // data_ptr
18314            i32_load(c, off);
18315        });
18316    }
18317    local_get(code, obj as u32);
18318    i32_load(code, 8); // data_ptr
18319    local_get(code, promoted.unwrap_or(value as u32));
18320    emit_slot_store(code, stored_kind, off)?;
18321    emit_record_field_kind(code, ctx, obj, u32::from(slot), stored_kind);
18322    Ok(())
18323}
18324
18325/// Write the field's ownership byte in the trailer, separate from its full-width scalar value.
18326fn emit_record_field_kind(code: &mut Vec<u8>, ctx: &Ctx, obj: u16, slot: u32, kind: Option<Kind>) {
18327    emit_record_field_is_handle(code, ctx, obj, slot, kind.is_some_and(kind_is_handle));
18328}
18329
18330fn emit_record_field_is_handle(
18331    code: &mut Vec<u8>,
18332    ctx: &Ctx,
18333    obj: u16,
18334    slot: u32,
18335    is_handle: bool,
18336) {
18337    if !ctx.heap_counting() {
18338        return;
18339    }
18340    local_get(code, obj as u32);
18341    i32_load(code, 8);
18342    local_get(code, obj as u32);
18343    i32_load(code, 0);
18344    i32_const(code, 8);
18345    code.push(0x6C);
18346    code.push(0x6A);
18347    i32_const(code, i32::from(is_handle));
18348    i32_store8(code, slot);
18349}
18350
18351/// `obj's field` (`GetField`) — load the value from its static slot, at the width of the field's
18352/// kind (the inferred kind of `dst`).
18353fn lower_get_field(code: &mut Vec<u8>, kinds: &KindTable, slot: u16, dst: u16, obj: u16) -> R<()> {
18354    if kinds.get(obj as usize) != Some(Kind::Struct) {
18355        return Err(WasmLowerError::Unsupported(
18356            "field access on a value with no known struct layout",
18357        ));
18358    }
18359    let off = u32::from(slot) * 8;
18360    local_get(code, obj as u32);
18361    i32_load(code, 8); // data_ptr
18362    emit_slot_load(code, kinds.get(dst as usize), off)?;
18363    local_set(code, dst as u32);
18364    Ok(())
18365}
18366
18367/// `Set collection[index] to value` where `collection` is a RECORD — `machine.rs`'s `is_struct_text`
18368/// overload of `SetIndex` (`st.fields.insert(field, new_val)`), value semantics like `StructInsert`.
18369/// The VM's place lowering writes a field back this way after mutating what it took out
18370/// (`w's stock["k"] = v` reassembles `w`'s `stock`), naming the field by a register that holds the
18371/// field's name as a constant loaded beside the write ([`PlaceSites::field_at`]) — so the slot is as
18372/// static as a `StructInsert`'s. The `nothing` the VM writes to clear the field before the mutation
18373/// stores nothing here ([`PlaceSites`]); its copy-on-write still runs, so the put-back that follows
18374/// lands in this record's own slots, never in a record it shares them with.
18375fn lower_record_field_set(
18376    code: &mut Vec<u8>,
18377    plan: &Plan,
18378    kinds: &KindTable,
18379    ctx: &Ctx,
18380    pc: usize,
18381    cow: bool,
18382    collection: u16,
18383    value: u16,
18384) -> R<()> {
18385    let field =
18386        plan.place
18387            .field_at
18388            .get(pc)
18389            .copied()
18390            .flatten()
18391            .ok_or(WasmLowerError::Unsupported(
18392                "record field written by a name computed at run time",
18393            ))?;
18394    let slot = record_field_slot(plan, collection, field).ok_or(WasmLowerError::Unsupported(
18395        "record field write on a value with no known record layout",
18396    ))?;
18397    if cow {
18398        // A write replaces the field in the copy, so the copy does not share what the field held. A
18399        // clear does not: the value it empties the field of goes on in the take's register, and the
18400        // original record — which another holder still has — still points at it.
18401        let clear = plan.place.clear.get(pc).copied().unwrap_or(false);
18402        let overwritten = (!clear).then_some(slot);
18403        emit_record_copy(
18404            code,
18405            ctx,
18406            kinds,
18407            &plan.structs,
18408            plan.num_regs,
18409            collection,
18410            overwritten,
18411        )?;
18412    }
18413    let clear = plan.place.clear.get(pc).copied().unwrap_or(false);
18414    // S8's true count: the field stops holding the value it held — a clear's value goes on in the
18415    // take's register (the put-back holds it again), a write's is replaced.
18416    let declared = declared_record_slot_kind(
18417        &plan.structs,
18418        ctx.struct_types,
18419        ctx.constants,
18420        collection,
18421        slot,
18422    );
18423    let field_kind = if declared == Some(Kind::Rational) {
18424        declared
18425    } else if clear {
18426        record_slot_kinds(kinds, &plan.structs, collection)
18427            .and_then(|ks| ks.get(slot).copied().flatten())
18428    } else {
18429        kinds.get(value as usize)
18430    };
18431    if ctx.heap_counting() && counted_kind(field_kind) {
18432        emit_true_release(code, ctx, |c| {
18433            local_get(c, collection as u32);
18434            i32_load(c, 8); // data_ptr
18435            i32_load(c, (slot as u32) * 8);
18436        });
18437    }
18438    if clear {
18439        // The field's value is out in the take's register until the put-back: the slot holds
18440        // nothing meanwhile, so a copy of the record made in between does not share the value
18441        // being mutated (and so does not make its next write copy it).
18442        local_get(code, collection as u32);
18443        i32_load(code, 8); // data_ptr
18444        code.push(0x42); // i64.const 0
18445        code.push(0x00);
18446        i64_store(code, (slot as u32) * 8);
18447        emit_record_field_kind(code, ctx, collection, slot as u32, None);
18448        return Ok(());
18449    }
18450    // A field of the exact extension is set by name only by a put-back, which returns the handle its take moved
18451    // out (a copy of the field's own); a value of another kind there has no lowering here.
18452    if declared == Some(Kind::Tower) && kinds.get(value as usize) != Some(Kind::Tower) {
18453        return Err(WasmLowerError::Unsupported(
18454            "a field of an exact type set by name to a value of another kind",
18455        ));
18456    }
18457    let promoted = promote_rational_field(
18458        code,
18459        kinds,
18460        &plan.structs,
18461        ctx,
18462        plan.num_regs,
18463        collection,
18464        slot,
18465        value,
18466    )?;
18467    let stored_kind = if promoted.is_some() {
18468        Some(Kind::Rational)
18469    } else {
18470        kinds.get(value as usize)
18471    };
18472    local_get(code, collection as u32);
18473    i32_load(code, 8); // data_ptr
18474    local_get(code, promoted.unwrap_or(value as u32));
18475    emit_slot_store(code, stored_kind, (slot as u32) * 8)?;
18476    emit_record_field_kind(code, ctx, collection, slot as u32, stored_kind);
18477    Ok(())
18478}
18479
18480/// Whether a value of `kind` is its own deep clone — a scalar with no sub-structure to copy
18481/// recursively (`Int`/`Bool`/`Char`/`Float`/`Date`/`Moment`). A handle kind (Text/Seq/Struct/…) is not.
18482fn is_clone_trivial(kind: Option<Kind>) -> bool {
18483    matches!(
18484        kind,
18485        Some(
18486            Kind::Int
18487                | Kind::Bool
18488                | Kind::Char
18489                | Kind::Word32
18490                | Kind::Word64
18491                | Kind::Float
18492                | Kind::Date
18493                | Kind::Moment
18494                | Kind::Duration
18495                | Kind::Time
18496                | Kind::Span
18497        )
18498    )
18499}
18500
18501/// A struct field this backend can deep-clone: a scalar (copied flat with the field buffer), a
18502/// `Text`/`Set`/scalar-sequence handle (clonable into an independent buffer one level down), or a
18503/// `Map` of scalar or Text entries (its entry buffer copied, a `SharedMap`'s mark with it). A field
18504/// that is itself a struct / enum / nested-handle sequence needs deeper recursion and is not cloned
18505/// here (the struct clone is then refused, soundly).
18506fn field_clone_ok(kind: Option<Kind>) -> bool {
18507    is_clone_trivial(kind)
18508        || matches!(
18509            kind,
18510            Some(
18511                Kind::Rational
18512                    | Kind::Text
18513                    | Kind::SeqInt
18514                    | Kind::SeqBool
18515                    | Kind::SeqFloat
18516                    | Kind::SeqWord32
18517                    | Kind::SeqWord64
18518                    | Kind::SeqAny
18519                    | Kind::Set
18520                    | Kind::Map
18521                    | Kind::Struct
18522            )
18523        )
18524}
18525
18526/// Clone a `Text` (byte buffer) or sequence/`Set` (8-byte-slot buffer) whose handle is in `src_local`
18527/// into a fresh, independent object, leaving the new handle in `hdr`. `is_text` selects the copy
18528/// stride; `hdr`/`data`/`idx` are three scratch locals, and `data` does not survive the call (a slot
18529/// copy is `__logos_seq_clone`'s). The fresh buffer is why a later in-place mutation of the clone (or
18530/// the original) cannot be seen through the other. `class` is the CLONE's own class — always the
18531/// same as the source's, since a clone never changes kind; the caller already knows it, so this
18532/// function does not have to re-derive it from `is_text` alone.
18533fn emit_buffer_clone(
18534    code: &mut Vec<u8>,
18535    ctx: &Ctx,
18536    hdr: u32,
18537    data: u32,
18538    idx: u32,
18539    src_local: u32,
18540    is_text: bool,
18541    class: AllocClass,
18542) {
18543    if !is_text {
18544        if let Some(clone) = ctx.runtime.and_then(|r| r.index(RuntimeFn::SeqClone)) {
18545            local_get(code, src_local);
18546            i32_const(code, class.code() as i32);
18547            code.push(0x10);
18548            leb_u32(code, clone);
18549            local_set(code, hdr);
18550            return;
18551        }
18552    }
18553    i32_const(code, 16);
18554    emit_alloc(code, ctx, hdr, class);
18555    local_get(code, src_local);
18556    i32_load(code, 0); // len (bytes for Text, element count otherwise)
18557    if !is_text {
18558        i32_const(code, 8);
18559        code.push(0x6C); // i32.mul — 8-byte slots
18560    }
18561    emit_alloc(code, ctx, data, AllocClass::Raw);
18562    if is_text {
18563        emit_byte_copy(code, idx, data, src_local, src_local, false);
18564    } else {
18565        emit_seq_copy(code, idx, data, src_local, src_local, false);
18566    }
18567    for off in [0u32, 4] {
18568        local_get(code, hdr);
18569        local_get(code, src_local);
18570        i32_load(code, 0); // len → both len and cap
18571        i32_store(code, off);
18572    }
18573    local_get(code, hdr);
18574    local_get(code, data);
18575    i32_store(code, 8); // data_ptr
18576}
18577
18578/// Clone a `Map` — a `num_entries × 16`-byte buffer of `[key@0][value@8]` pairs — whose handle is in
18579/// `src_local`, into a fresh independent map left in `hdr`. Flat entry copy (`num_entries × 2` `i64`
18580/// slots): the corpus maps have Text/scalar keys and scalar values, so the pairs copy by value; a
18581/// handle value would stay shared (a deep value clone is a later refinement). `hdr`/`data`/`idx` are
18582/// three scratch locals. The fresh buffer is why a later `Set item k of map` on the clone (or the
18583/// original) is invisible through the other holder.
18584fn emit_map_clone(code: &mut Vec<u8>, ctx: &Ctx, hdr: u32, data: u32, idx: u32, src_local: u32) {
18585    if let Some(clone) = ctx.runtime.and_then(|r| r.index(RuntimeFn::MapClone)) {
18586        local_get(code, src_local);
18587        code.push(0x10);
18588        leb_u32(code, clone);
18589        local_set(code, hdr);
18590        return;
18591    }
18592    // A linked module has no runtime of its own: the copy inline.
18593    i32_const(code, 16);
18594    // The class stamped here is irrelevant — word 12 is fully overwritten below from `src_local`'s
18595    // own word 12, which already carries the map's real class (stamped at its first insert).
18596    emit_alloc(code, ctx, hdr, AllocClass::Raw);
18597    // data = alloc(num_entries * 16)
18598    local_get(code, src_local);
18599    i32_load(code, 0); // num_entries
18600    i32_const(code, 16);
18601    code.push(0x6C);
18602    emit_alloc(code, ctx, data, AllocClass::Raw);
18603    // copy num_entries*2 i64 slots (each entry = key slot + value slot)
18604    i32_const(code, 0);
18605    local_set(code, idx);
18606    code.push(0x02);
18607    code.push(0x40); // block
18608    code.push(0x03);
18609    code.push(0x40); // loop
18610    local_get(code, idx);
18611    local_get(code, src_local);
18612    i32_load(code, 0);
18613    i32_const(code, 2);
18614    code.push(0x6C); // num_entries * 2
18615    code.push(0x4E); // idx >= num*2
18616    code.push(0x0D);
18617    leb_u32(code, 1); // br_if block
18618    local_get(code, data);
18619    local_get(code, idx);
18620    i32_const(code, 8);
18621    code.push(0x6C);
18622    code.push(0x6A); // data + idx*8
18623    local_get(code, src_local);
18624    i32_load(code, 8);
18625    local_get(code, idx);
18626    i32_const(code, 8);
18627    code.push(0x6C);
18628    code.push(0x6A); // src_data + idx*8
18629    i64_load(code, 0);
18630    i64_store(code, 0);
18631    local_get(code, idx);
18632    i32_const(code, 1);
18633    code.push(0x6A);
18634    local_set(code, idx);
18635    code.push(0x0C);
18636    leb_u32(code, 0); // br loop
18637    code.push(0x0B); // end loop
18638    code.push(0x0B); // end block
18639    for off in [0u32, 4] {
18640        local_get(code, hdr);
18641        local_get(code, src_local);
18642        i32_load(code, 0);
18643        i32_store(code, off);
18644    }
18645    local_get(code, hdr);
18646    local_get(code, data);
18647    i32_store(code, 8);
18648    // word 12 = (sign mark, if this is a program with SharedMaps and `src` is one) | src's class byte
18649    // — a plain map's clone keeps its class; a `SharedMap`'s clone stays another replica of the same
18650    // map (the sign mark), classified exactly like its source.
18651    local_get(code, hdr);
18652    if ctx.shared_maps {
18653        i32_const(code, SHARED_MAP_MARK);
18654        i32_const(code, 0);
18655        local_get(code, src_local);
18656        i32_load(code, 12);
18657        i32_const(code, 0);
18658        code.push(0x48); // i32.lt_s
18659        code.push(0x1B); // select
18660    } else {
18661        i32_const(code, 0);
18662    }
18663    local_get(code, src_local);
18664    i32_load(code, 12);
18665    i32_const(code, 0xFF);
18666    code.push(0x71); // i32.and — src's class byte
18667    code.push(0x72); // i32.or
18668    i32_store(code, 12);
18669    // S8's true count: the copy shares every entry — each handle key and value gains it as a holder.
18670    emit_retain_children(code, ctx, hdr);
18671}
18672
18673/// After a nested sequence's OUTER handle buffer has been flat-cloned into `data` (its element count
18674/// in `outer_hdr`'s word 0), replace each element handle with a deep clone of the value it points to,
18675/// so the clone owns independent inner sequences (a flat copy would share them). `is_text` selects
18676/// the inner copy stride. A runtime loop over the (statically-unknown) element count; scratch
18677/// `counter` plus `isrc`/`ihdr`/`idata`/`iidx` (the inner buffer clone) are all disjoint from
18678/// `outer_hdr`/`data`.
18679#[allow(clippy::too_many_arguments)]
18680fn emit_clone_each_element(
18681    code: &mut Vec<u8>,
18682    ctx: &Ctx,
18683    outer_hdr: u32,
18684    data: u32,
18685    counter: u32,
18686    isrc: u32,
18687    ihdr: u32,
18688    idata: u32,
18689    iidx: u32,
18690    is_text: bool,
18691    inner_class: AllocClass,
18692) {
18693    i32_const(code, 0);
18694    local_set(code, counter);
18695    code.push(0x02);
18696    code.push(0x40); // block
18697    code.push(0x03);
18698    code.push(0x40); // loop
18699    local_get(code, counter);
18700    local_get(code, outer_hdr);
18701    i32_load(code, 0); // element count
18702    code.push(0x4E); // i32.ge_s
18703    code.push(0x0D);
18704    leb_u32(code, 1); // br_if exit
18705                      // isrc = data[counter*8] — the inner handle the flat copy duplicated
18706    local_get(code, data);
18707    local_get(code, counter);
18708    i32_const(code, 8);
18709    code.push(0x6C); // i32.mul
18710    code.push(0x6A); // i32.add
18711    i32_load(code, 0);
18712    local_set(code, isrc);
18713    emit_buffer_clone(code, ctx, ihdr, idata, iidx, isrc, is_text, inner_class);
18714    // data[counter*8] = ihdr (the fresh, independent inner handle)
18715    local_get(code, data);
18716    local_get(code, counter);
18717    i32_const(code, 8);
18718    code.push(0x6C); // i32.mul
18719    code.push(0x6A); // i32.add
18720    local_get(code, ihdr);
18721    i32_store(code, 0);
18722    // S8's true count: the slot is the fresh element's holder beyond the turn that made it.
18723    if ctx.heap_counting() {
18724        emit_true_retain_of(code, ctx, |c| local_get(c, ihdr));
18725    }
18726    // counter++
18727    local_get(code, counter);
18728    i32_const(code, 1);
18729    code.push(0x6A); // i32.add
18730    local_set(code, counter);
18731    code.push(0x0C);
18732    leb_u32(code, 0); // br loop
18733    code.push(0x0B); // end loop
18734    code.push(0x0B); // end block
18735}
18736
18737/// Each slot's kind of the record in `src`, in slot order: its DECLARED layout wherever the record's
18738/// type is known (built here, a parameter, a call's result), else the kinds of the registers that
18739/// filled a record built here with no declaration. An unfilled or unknown slot is `None`.
18740fn record_slot_kinds(
18741    kinds: &KindTable,
18742    structs: &kind::StructLayout,
18743    src: u16,
18744) -> Option<Vec<Option<Kind>>> {
18745    if let Some(ParamShape::Struct(layout)) = structs.reg_shape.get(&src) {
18746        return Some(layout.iter().map(|(_, k, _)| Some(*k)).collect());
18747    }
18748    let layout = structs.reg_layout.get(&src)?;
18749    Some(
18750        layout
18751            .iter()
18752            .map(|&(_, vr)| vr.and_then(|vr| kinds.get(vr as usize)))
18753            .collect(),
18754    )
18755}
18756
18757/// `a copy of x` (`DeepClone`) — an independent deep copy. A scalar is its own value (copied); a
18758/// `Text` gets a fresh byte buffer; a sequence/struct of trivially-cloneable (scalar) elements gets
18759/// a fresh element buffer. The new buffer means a later mutation of the clone (or the original)
18760/// cannot be seen through the other — value semantics, matching the tree-walker's `deep_clone`. A
18761/// composite holding HANDLE sub-values (a struct with a Text/Seq field, a Seq of handles) needs a
18762/// recursive clone (a generated per-type helper); deferred — soundly rejected, never miscopied.
18763fn lower_deep_clone(
18764    code: &mut Vec<u8>,
18765    kinds: &KindTable,
18766    structs: &kind::StructLayout,
18767    ctx: &Ctx,
18768    num_regs: u32,
18769    dst: u16,
18770    src: u16,
18771) -> R<()> {
18772    let (hdr, data, idx) = (num_regs + 5, num_regs + 6, num_regs + 7);
18773    let s = src as u32;
18774    match kinds.get(src as usize) {
18775        // Scalars and Rational values are immutable; copying preserves the same value.
18776        Some(Kind::Rational) | Some(Kind::Int) | Some(Kind::Bool) | Some(Kind::Word32)
18777        | Some(Kind::Word64) | Some(Kind::Float) | Some(Kind::Date) | Some(Kind::Moment)
18778        | Some(Kind::Duration) | Some(Kind::Time) | Some(Kind::Span) => {
18779            local_get(code, s);
18780            local_set(code, dst as u32);
18781            return Ok(());
18782        }
18783        // A struct whose fields are scalars and/or clonable handles (`Text`/`Set`/scalar-sequence):
18784        // clone the header + the field buffer (8-byte slots, count = `num_fields`), then RECURSIVELY
18785        // clone each handle field one level so the clone owns independent sub-buffers — a flat copy
18786        // would SHARE a mutable inner sequence, defeating value semantics. Scalar fields are already
18787        // independent after the flat copy. The field layout flows to `dst` (see `struct_layout`), so
18788        // `clone's field` still resolves.
18789        Some(Kind::Struct)
18790            if record_slot_kinds(kinds, structs, src)
18791                .is_some_and(|ks| ks.iter().all(|&k| field_clone_ok(k))) =>
18792        {
18793            // A record's header and field slots have a sequence's shape: `num_fields` 8-byte slots.
18794            emit_buffer_clone(
18795                code,
18796                ctx,
18797                hdr,
18798                data,
18799                idx,
18800                s,
18801                false,
18802                AllocClass::RecordHeader,
18803            );
18804            local_get(code, hdr);
18805            i32_load(code, 8);
18806            local_set(code, data);
18807            // Recursively clone each handle field IN PLACE in the cloned buffer (`data`), overwriting
18808            // its flat-copied shared handle with a fresh one. Scratch `+8..+11` is disjoint from the
18809            // struct's `+5..+7`. The layout is compile-time, so this unrolls per handle field.
18810            let (fsrc, fhdr, fdata, fidx) =
18811                (num_regs + 8, num_regs + 9, num_regs + 10, num_regs + 11);
18812            let slot_kinds =
18813                record_slot_kinds(kinds, structs, src).expect("guarded by is_some_and above");
18814            for (slot, &fk) in slot_kinds.iter().enumerate() {
18815                if is_clone_trivial(fk) {
18816                    if fk == Some(Kind::Int) && ctx.exact.record_ints() {
18817                        exact::retain_record_integer(code, ctx, hdr, slot as u16);
18818                    }
18819                    continue; // immutable cells and scalars preserve their value in the flat copy
18820                }
18821                let off = slot as u32 * 8;
18822                if matches!(fk, Some(Kind::Rational | Kind::Struct)) {
18823                    // Nested records share their value until a field write copies it.
18824                    if fk == Some(Kind::Struct) {
18825                        emit_share_inline(code, |code| {
18826                            local_get(code, data);
18827                            i32_load(code, off);
18828                        });
18829                    }
18830                    emit_true_retain_of(code, ctx, |code| {
18831                        local_get(code, data);
18832                        i32_load(code, off);
18833                    });
18834                    continue;
18835                }
18836                local_get(code, data);
18837                i32_load(code, off); // the shared handle the flat copy duplicated
18838                local_set(code, fsrc);
18839                if fk == Some(Kind::Map) {
18840                    emit_map_clone(code, ctx, fhdr, fdata, fidx, fsrc);
18841                } else {
18842                    let is_text = fk == Some(Kind::Text);
18843                    // `field_clone_ok` (guarding this whole branch) only ever admits Text/SeqInt/
18844                    // SeqBool/SeqFloat/SeqAny/Set/Map here; of those, `SeqAny` is the one handle-
18845                    // element case.
18846                    let class = if is_text {
18847                        AllocClass::TextHeader
18848                    } else {
18849                        AllocClass::of_elements(fk == Some(Kind::SeqAny))
18850                    };
18851                    emit_buffer_clone(code, ctx, fhdr, fdata, fidx, fsrc, is_text, class);
18852                    if class == AllocClass::HandleHeader {
18853                        emit_retain_children(code, ctx, fhdr);
18854                    }
18855                }
18856                local_get(code, data);
18857                local_get(code, fhdr); // the fresh, independent handle
18858                i32_store(code, off);
18859                // S8's true count: the clone's field is the fresh copy's holder beyond its turn.
18860                if ctx.heap_counting() {
18861                    emit_true_retain_of(code, ctx, |c| local_get(c, fhdr));
18862                }
18863            }
18864            local_get(code, hdr);
18865            local_set(code, dst as u32);
18866            return Ok(());
18867        }
18868        Some(k) if is_collection_clonable(k) => {
18869            emit_collection_clone(code, ctx, num_regs, k, s);
18870            local_get(code, hdr);
18871            local_set(code, dst as u32);
18872            Ok(())
18873        }
18874        _ => Err(WasmLowerError::Unsupported(
18875            "deep clone of an unsupported value kind",
18876        )),
18877    }
18878}
18879
18880/// The kinds [`emit_collection_clone`] copies.
18881fn is_collection_clonable(k: Kind) -> bool {
18882    matches!(
18883        k,
18884        Kind::Text
18885            | Kind::SeqInt
18886            | Kind::SeqBool
18887            | Kind::SeqFloat
18888            | Kind::SeqWord32
18889            | Kind::SeqWord64
18890            | Kind::SeqAny
18891            | Kind::Set
18892            | Kind::SetText
18893            | Kind::Map
18894            | Kind::SeqSeqInt
18895            | Kind::SeqText
18896            | Kind::SeqStruct
18897            | Kind::SeqEnum
18898            | Kind::SeqHandle
18899    )
18900}
18901
18902/// A fresh, independent copy of the `k`-kinded value whose handle is in local `src`, left in local
18903/// `num_regs + 5`. Scratch: `+5..+7`, and `+8..+11` for a `Seq of Seq`; `src` must be none of them
18904/// but `+8`, which the copy only reuses once it has finished reading `src`.
18905fn emit_collection_clone(code: &mut Vec<u8>, ctx: &Ctx, num_regs: u32, k: Kind, src: u32) {
18906    let (hdr, data, idx) = (num_regs + 5, num_regs + 6, num_regs + 7);
18907    if let Some(mode) = seq_clone_mode(k) {
18908        if let Some(clone) = ctx.runtime.and_then(|r| r.index(RuntimeFn::SeqClone)) {
18909            local_get(code, src);
18910            i32_const(code, mode);
18911            code.push(0x10);
18912            leb_u32(code, clone);
18913            local_set(code, hdr);
18914            return;
18915        }
18916    }
18917    match k {
18918        // Text → fresh byte buffer; a sequence or `Set of Int` → fresh 8-byte-element buffer (a Set
18919        // is a flat scalar buffer like `SeqInt`, so the same copy is an independent deep clone).
18920        // A `SetText` clones like a `Set` (flat 8-byte-slot copy) — the shared `Text` element handles
18921        // are immutable in Logos, so the clone sharing them is sound (no deeper recursion needed).
18922        Kind::Text
18923        | Kind::SeqInt
18924        | Kind::SeqBool
18925        | Kind::SeqFloat
18926        | Kind::SeqWord32
18927        | Kind::SeqWord64
18928        | Kind::SeqAny
18929        | Kind::Set
18930        | Kind::SetText => {
18931            let is_text = k == Kind::Text;
18932            let class = if is_text {
18933                AllocClass::TextHeader
18934            } else {
18935                AllocClass::of_elements(matches!(k, Kind::SeqAny | Kind::SetText))
18936            };
18937            emit_buffer_clone(code, ctx, hdr, data, idx, src, is_text, class);
18938            if class == AllocClass::HandleHeader {
18939                emit_retain_children(code, ctx, hdr);
18940            }
18941        }
18942        // A Map — its `[key][value]` entry buffer flat-copied into a fresh, independent map.
18943        Kind::Map => emit_map_clone(code, ctx, hdr, data, idx, src),
18944        // A Seq of Seq (an Int matrix): clone the outer handle buffer, then clone EACH inner sequence
18945        // so the rows are independent (a flat copy would share the row handles). `idx` is free again
18946        // after the outer copy, so it doubles as the per-row loop counter; `+8..+11` clone each row.
18947        Kind::SeqSeqInt => {
18948            // The outer buffer holds one `Seq of Int` HANDLE per row; each row itself holds scalars.
18949            emit_buffer_clone(
18950                code,
18951                ctx,
18952                hdr,
18953                data,
18954                idx,
18955                src,
18956                false,
18957                AllocClass::HandleHeader,
18958            );
18959            local_get(code, hdr);
18960            i32_load(code, 8);
18961            local_set(code, data); // the copy's row handles, each replaced by a copy of its row
18962            let (isrc, ihdr, idata, iidx) =
18963                (num_regs + 8, num_regs + 9, num_regs + 10, num_regs + 11);
18964            emit_clone_each_element(
18965                code,
18966                ctx,
18967                hdr,
18968                data,
18969                idx,
18970                isrc,
18971                ihdr,
18972                idata,
18973                iidx,
18974                false,
18975                AllocClass::ScalarHeader,
18976            );
18977        }
18978        // A list of Texts, records, variants or collections: a flat copy of the element handles, each
18979        // element now held by both lists. A record or a collection gains a copy-on-write hold, so a
18980        // write to it through either list copies it first; a Text is immutable and a variant is
18981        // rebuilt, never written in place, so theirs are shared as they are.
18982        Kind::SeqText | Kind::SeqStruct | Kind::SeqEnum | Kind::SeqHandle => {
18983            emit_buffer_clone(
18984                code,
18985                ctx,
18986                hdr,
18987                data,
18988                idx,
18989                src,
18990                false,
18991                AllocClass::HandleHeader,
18992            );
18993            emit_retain_children(code, ctx, hdr);
18994            if matches!(k, Kind::SeqStruct | Kind::SeqHandle) {
18995                emit_cow_retain_each_element(code, hdr, idx);
18996            }
18997        }
18998        _ => unreachable!("emit_collection_clone of {k:?}: callers check is_collection_clonable"),
18999    }
19000}
19001
19002/// `lhs equals rhs` / `lhs is not rhs` on two `Text` values — byte equality (unequal length ⇒ not
19003/// equal, else compare bytes). Result is a `Bool` i64 0/1 in `dst` (`negate` flips it for `!=`).
19004fn lower_text_eq(
19005    code: &mut Vec<u8>,
19006    ctx: &Ctx,
19007    num_regs: u32,
19008    dst: u16,
19009    lhs: u16,
19010    rhs: u16,
19011    negate: bool,
19012) {
19013    emit_text_eq(code, ctx, num_regs, lhs as u32, rhs as u32);
19014    if negate {
19015        code.push(0x45); // i32.eqz
19016    }
19017    code.push(0xAD); // i64.extend_i32_u
19018    local_set(code, dst as u32);
19019}
19020
19021/// Materialize the value in local `src` (of kind `kind`) as a `Text` handle stored in local `out`.
19022/// A `Text` is itself (just copied); an `Int`/`Float`/`Bool` is formatted into a fresh buffer by
19023/// the matching host formatter (which returns the byte length) and wrapped in a header. Uses the
19024/// +5/+6/+7 scratch as temps. Value-based (a local + kind, not a register) so it serves both
19025/// `Concat`'s operands and `Show`'s slot-loaded struct fields.
19026fn emit_stringify(
19027    code: &mut Vec<u8>,
19028    ctx: &Ctx,
19029    num_regs: u32,
19030    src: u32,
19031    kind: Option<Kind>,
19032    out: u32,
19033) -> R<()> {
19034    if kind == Some(Kind::SeqInt) && ctx.exact.sequence_ints() {
19035        return exact::sequence_text(code, ctx, num_regs, src, out);
19036    }
19037    match kind {
19038        Some(Kind::Text) => {
19039            local_get(code, src);
19040            local_set(code, out);
19041        }
19042        // A value of the exact extension joins text as it prints.
19043        Some(Kind::Tower) => tower::text_of(code, ctx, src, out)?,
19044        // A `BigInt` operand of a concat (`"x = " + (2^200)`): render it to a decimal `Text` via the
19045        // runtime, then stringify AS that Text — matching the VM, which appends the decimal to the text.
19046        Some(Kind::BigInt) => {
19047            let to_text = (ctx.host_index)(HostFn::BigintToText)
19048                .ok_or(WasmLowerError::Unsupported("bigint_to_text not imported"))?;
19049            local_get(code, src);
19050            code.push(0x10); // call
19051            leb_u32(code, to_text);
19052            local_set(code, out);
19053        }
19054        Some(k @ (Kind::Int | Kind::Float | Kind::Bool)) => {
19055            // Stringify a scalar via the matching host formatter writing into a fresh buffer.
19056            let (host, bufsize) = match k {
19057                Kind::Int => (HostFn::FmtI64Into, 24), // ≤ 20 decimal digits + sign
19058                Kind::Float => (HostFn::FmtF64Into, 340), // worst-case shortest-round-trip f64 width (~326)
19059                _ => (HostFn::FmtBoolInto, 8),            // "true"/"false"
19060            };
19061            let (h, data, tmp) = (num_regs + 5, num_regs + 6, num_regs + 7);
19062            i32_const(code, 16);
19063            emit_alloc(code, ctx, h, AllocClass::TextHeader);
19064            i32_const(code, bufsize);
19065            emit_alloc(code, ctx, data, AllocClass::Raw);
19066            // len = fmt_*_into(data, src)
19067            let fidx = (ctx.host_index)(host)
19068                .ok_or(WasmLowerError::Unsupported("text formatter not imported"))?;
19069            local_get(code, data);
19070            local_get(code, src);
19071            code.push(0x10); // call
19072            leb_u32(code, fidx);
19073            local_set(code, tmp); // tmp = len
19074                                  // header: len = tmp; cap = the buffer's size (what a free returns); data_ptr = data
19075            local_get(code, h);
19076            local_get(code, tmp);
19077            i32_store(code, 0);
19078            local_get(code, h);
19079            i32_const(code, bufsize);
19080            i32_store(code, 4);
19081            local_get(code, h);
19082            local_get(code, data);
19083            i32_store(code, 8);
19084            local_get(code, h);
19085            local_set(code, out);
19086        }
19087        // A whole `Seq of Int` / `Set of Int` operand — the host formats `[e0, …]` / `{e0, …}` out of
19088        // linear memory into a buffer sized from the collection's length (`len*24 + 8`, worst-case i64
19089        // decimal + `", "` + brackets), which is then wrapped in a Text header. Matches
19090        // `RuntimeValue::List`/`Set::to_display_string` (insertion order = the AOT's storage order).
19091        Some(k @ (Kind::SeqInt | Kind::SeqBool | Kind::SeqAny | Kind::Set)) => {
19092            let host = match k {
19093                Kind::Set => HostFn::FmtSetI64Into,
19094                Kind::SeqBool => HostFn::FmtSeqBoolInto, // renders `[true, false, …]` (`len*24+8` is ample)
19095                _ => HostFn::FmtSeqI64Into,
19096            };
19097            let (h, data, tmp) = (num_regs + 5, num_regs + 6, num_regs + 7);
19098            i32_const(code, 16);
19099            emit_alloc(code, ctx, h, AllocClass::TextHeader);
19100            // data = alloc(len*24 + 8)
19101            local_get(code, src);
19102            i32_load(code, 0); // len
19103            i32_const(code, 24);
19104            code.push(0x6C); // i32.mul
19105            i32_const(code, 8);
19106            code.push(0x6A); // + 8
19107            emit_alloc(code, ctx, data, AllocClass::Raw);
19108            // len = fmt_{seq,set}_i64_into(data, src)
19109            let fidx = (ctx.host_index)(host).ok_or(WasmLowerError::Unsupported(
19110                "collection formatter not imported",
19111            ))?;
19112            local_get(code, data);
19113            local_get(code, src);
19114            code.push(0x10); // call
19115            leb_u32(code, fidx);
19116            local_set(code, tmp);
19117            local_get(code, h);
19118            local_get(code, tmp);
19119            i32_store(code, 0);
19120            local_get(code, h);
19121            local_get(code, src);
19122            i32_load(code, 0);
19123            i32_const(code, 24);
19124            code.push(0x6C);
19125            i32_const(code, 8);
19126            code.push(0x6A); // cap = the buffer's size, len*24 + 8
19127            i32_store(code, 4);
19128            local_get(code, h);
19129            local_get(code, data);
19130            i32_store(code, 8);
19131            local_get(code, h);
19132            local_set(code, out);
19133        }
19134        _ => {
19135            return Err(WasmLowerError::Unsupported(
19136                "concat operand kind cannot be stringified yet",
19137            ))
19138        }
19139    }
19140    Ok(())
19141}
19142
19143/// Build the display `Text` of the struct in `handle` (type `def`) into `out` — `TypeName { f: v, … }`
19144/// (`RuntimeValue::Struct::to_display_string`) with the fields in DETERMINISTIC alphabetical order (the
19145/// VM sorts its `HashMap` fields by name; this sorts the DECLARED fields the same way). Each field's
19146/// value is loaded from its declared slot (`data_ptr + slot*8`) at the field type's width and
19147/// stringified. An empty struct is just its name. `part`/`field_i32` are caller-supplied scratch kept
19148/// distinct from `out`. The reusable core of [`lower_show_struct`] and [`lower_show_seqstruct`].
19149fn emit_struct_display(
19150    code: &mut Vec<u8>,
19151    ctx: &Ctx,
19152    num_regs: u32,
19153    def: &StructTypeDef,
19154    handle: u32,
19155    out: u32,
19156    part: u32,
19157    field_i32: u32,
19158) -> R<()> {
19159    let mut order: Vec<usize> = (0..def.fields.len()).collect();
19160    order.sort_by(|&a, &b| def.fields[a].0.cmp(&def.fields[b].0));
19161    if def.fields.is_empty() {
19162        lower_text_literal(code, ctx, num_regs, def.name.as_bytes());
19163        local_set(code, out);
19164        return Ok(());
19165    }
19166    lower_text_literal(code, ctx, num_regs, format!("{} {{ ", def.name).as_bytes());
19167    local_set(code, out);
19168    let n = order.len();
19169    for (j, &i) in order.iter().enumerate() {
19170        let (fname, bt) = &def.fields[i];
19171        let ek = kind::boundary_to_kind(bt);
19172        lower_text_literal(code, ctx, num_regs, format!("{fname}: ").as_bytes());
19173        local_set(code, part);
19174        emit_text_concat(code, ctx, num_regs, out, part, out);
19175        if ctx.exact.record_ints() && ek == Some(Kind::Int) {
19176            exact::record_integer_text(code, ctx, num_regs, handle, i as u16, part)?;
19177        } else if let Some(shown) =
19178            display::Shown::of_type(bt).filter(|s| s.inline_kind().is_none())
19179        {
19180            local_get(code, handle);
19181            i32_load(code, 8);
19182            i32_load(code, (i as u32) * 8);
19183            local_set(code, field_i32);
19184            display::emit_shown(code, ctx, num_regs, field_i32, &shown, part)?;
19185        } else {
19186            // load field `i`'s slot value (declared slot = `i`, at `data_ptr + i*8`)
19187            let elem_tmp = match ek.map(Kind::wasm_valtype) {
19188                Some(F64) => num_regs + 12,
19189                Some(I64) => num_regs + 1,
19190                _ => field_i32,
19191            };
19192            local_get(code, handle);
19193            i32_load(code, 8); // data_ptr
19194            emit_slot_load(code, ek, (i as u32) * 8)?;
19195            local_set(code, elem_tmp);
19196            emit_stringify(code, ctx, num_regs, elem_tmp, ek, part)?;
19197        }
19198        emit_text_concat(code, ctx, num_regs, out, part, out);
19199        if j + 1 < n {
19200            lower_text_literal(code, ctx, num_regs, b", ");
19201            local_set(code, part);
19202            emit_text_concat(code, ctx, num_regs, out, part, out);
19203        }
19204    }
19205    lower_text_literal(code, ctx, num_regs, b" }");
19206    local_set(code, part);
19207    emit_text_concat(code, ctx, num_regs, out, part, out);
19208    Ok(())
19209}
19210
19211fn lower_show_struct(code: &mut Vec<u8>, plan: &Plan, ctx: &Ctx, src: u16) -> R<()> {
19212    let type_name = plan
19213        .structs
19214        .struct_name_of
19215        .get(&src)
19216        .or_else(|| match plan.structs.reg_declared.get(&src) {
19217            Some(BoundaryType::Struct(name)) => Some(name),
19218            _ => None,
19219        })
19220        .ok_or(WasmLowerError::Unsupported(
19221            "Show of a struct whose type is not statically known",
19222        ))?;
19223    let def = ctx
19224        .struct_types
19225        .iter()
19226        .find(|s| &s.name == type_name)
19227        .ok_or(WasmLowerError::Unsupported(
19228            "Show of an unknown struct type",
19229        ))?;
19230    let print_idx = (ctx.host_index)(HostFn::PrintText).ok_or(WasmLowerError::Unsupported(
19231        "Show struct: print_text not imported",
19232    ))?;
19233    let num_regs = plan.num_regs;
19234    let out = num_regs + 8;
19235    emit_struct_display(
19236        code,
19237        ctx,
19238        num_regs,
19239        def,
19240        src as u32,
19241        out,
19242        num_regs + 9,
19243        num_regs + 10,
19244    )?;
19245    local_get(code, out);
19246    code.push(0x10); // call print_text
19247    leb_u32(code, print_idx);
19248    Ok(())
19249}
19250
19251/// `Show <Seq of Struct>` — `[TypeName { … }, …]` over the sequence in insertion order, each element
19252/// rendered by [`emit_struct_display`]. A RUNTIME loop: element `i` is an i32 struct handle at
19253/// `data_ptr+i*8`; its display is built into `out` and concatenated onto the outer `[…]` accumulator.
19254/// The element struct type comes from `seq_elem_struct_name` (the homogeneous list's element).
19255fn lower_show_seqstruct(code: &mut Vec<u8>, plan: &Plan, ctx: &Ctx, src: u16) -> R<()> {
19256    let type_name =
19257        plan.structs
19258            .seq_elem_struct_name
19259            .get(&src)
19260            .ok_or(WasmLowerError::Unsupported(
19261                "Show of a Seq of Struct whose element type is not statically known",
19262            ))?;
19263    let def = ctx
19264        .struct_types
19265        .iter()
19266        .find(|s| &s.name == type_name)
19267        .ok_or(WasmLowerError::Unsupported(
19268            "Show seq-struct: unknown element struct type",
19269        ))?;
19270    let print_idx = (ctx.host_index)(HostFn::PrintText).ok_or(WasmLowerError::Unsupported(
19271        "Show seq-struct: print_text not imported",
19272    ))?;
19273    let num_regs = plan.num_regs;
19274    let m = src as u32;
19275    let (outer_acc, out, i, elem) = (num_regs + 8, num_regs + 9, num_regs + 10, num_regs + 11);
19276    let (part, field_i32) = (num_regs + 13, num_regs + 14);
19277    lower_text_literal(code, ctx, num_regs, b"[");
19278    local_set(code, outer_acc);
19279    i32_const(code, 0);
19280    local_set(code, i);
19281    code.push(0x02);
19282    code.push(0x40); // block
19283    code.push(0x03);
19284    code.push(0x40); // loop
19285    local_get(code, i);
19286    local_get(code, m);
19287    i32_load(code, 0);
19288    code.push(0x4E); // i32.ge_s
19289    code.push(0x0D);
19290    leb_u32(code, 1);
19291    // separator ", " before every element after the first
19292    local_get(code, i);
19293    code.push(0x45);
19294    code.push(0x04);
19295    code.push(0x40);
19296    code.push(0x05);
19297    lower_text_literal(code, ctx, num_regs, b", ");
19298    local_set(code, part);
19299    emit_text_concat(code, ctx, num_regs, outer_acc, part, outer_acc);
19300    code.push(0x0B); // end if
19301                     // elem = seq element i (i32 struct handle at data_ptr + i*8)
19302    local_get(code, m);
19303    i32_load(code, 8);
19304    local_get(code, i);
19305    i32_const(code, 8);
19306    code.push(0x6C);
19307    code.push(0x6A);
19308    i32_load(code, 0);
19309    local_set(code, elem);
19310    emit_struct_display(code, ctx, num_regs, def, elem, out, part, field_i32)?;
19311    emit_text_concat(code, ctx, num_regs, outer_acc, out, outer_acc);
19312    local_get(code, i);
19313    i32_const(code, 1);
19314    code.push(0x6A);
19315    local_set(code, i);
19316    code.push(0x0C);
19317    leb_u32(code, 0);
19318    code.push(0x0B); // end loop
19319    code.push(0x0B); // end block
19320    lower_text_literal(code, ctx, num_regs, b"]");
19321    local_set(code, part);
19322    emit_text_concat(code, ctx, num_regs, outer_acc, part, outer_acc);
19323    local_get(code, outer_acc);
19324    code.push(0x10); // call print_text
19325    leb_u32(code, print_idx);
19326    Ok(())
19327}
19328
19329/// `Show <Seq of Seq of Int>` — `[[…], […]]` over the outer sequence in stored (insertion) order,
19330/// matching the VM's `RuntimeValue::List` of `List`s. A RUNTIME loop (outer length is dynamic): each
19331/// outer element is an `i32` handle (low word of its 8-byte slot) to an inner `Seq of Int`, which the
19332/// scalar seq formatter (`emit_stringify` of `Kind::SeqInt` → `fmt_seq_i64_into`) renders as `[e0, …]`;
19333/// the outer wraps them in `[…]` with `", "` separators. Byte-identical to the VM's nested display.
19334fn lower_show_seqseq(code: &mut Vec<u8>, ctx: &Ctx, num_regs: u32, src: u16) -> R<()> {
19335    let print_idx = (ctx.host_index)(HostFn::PrintText).ok_or(WasmLowerError::Unsupported(
19336        "Show seq-of-seq: print_text not imported",
19337    ))?;
19338    let m = src as u32;
19339    // acc = accumulator Text; part = each inner render; i = outer loop counter; inner = the inner
19340    // `Seq of Int` handle (all outside the +5/+6/+7 scratch `emit_stringify`/concat clobber).
19341    let (acc, part, i, inner) = (num_regs + 8, num_regs + 9, num_regs + 10, num_regs + 11);
19342    // acc = "["
19343    lower_text_literal(code, ctx, num_regs, b"[");
19344    local_set(code, acc);
19345    i32_const(code, 0);
19346    local_set(code, i);
19347    code.push(0x02);
19348    code.push(0x40); // block
19349    code.push(0x03);
19350    code.push(0x40); // loop
19351                     // if i >= outer_len: br block
19352    local_get(code, i);
19353    local_get(code, m);
19354    i32_load(code, 0); // outer len
19355    code.push(0x4E); // i32.ge_s
19356    code.push(0x0D);
19357    leb_u32(code, 1); // br_if block
19358                      // separator: entries after the first get ", "
19359    local_get(code, i);
19360    code.push(0x45); // i32.eqz
19361    code.push(0x04);
19362    code.push(0x40); // if (i == 0): nothing
19363    code.push(0x05); // else
19364    lower_text_literal(code, ctx, num_regs, b", ");
19365    local_set(code, part);
19366    emit_text_concat(code, ctx, num_regs, acc, part, acc);
19367    code.push(0x0B); // end if
19368                     // inner = outer element i (i32 handle at data_ptr + i*8)
19369    local_get(code, m);
19370    i32_load(code, 8); // data_ptr
19371    local_get(code, i);
19372    i32_const(code, 8);
19373    code.push(0x6C); // i32.mul
19374    code.push(0x6A); // i32.add
19375    i32_load(code, 0); // the inner Seq handle
19376    local_set(code, inner);
19377    // part = stringify(inner as Seq of Int); acc += part
19378    emit_stringify(code, ctx, num_regs, inner, Some(Kind::SeqInt), part)?;
19379    emit_text_concat(code, ctx, num_regs, acc, part, acc);
19380    // i += 1; br loop
19381    local_get(code, i);
19382    i32_const(code, 1);
19383    code.push(0x6A);
19384    local_set(code, i);
19385    code.push(0x0C);
19386    leb_u32(code, 0); // br loop
19387    code.push(0x0B); // end loop
19388    code.push(0x0B); // end block
19389                     // acc += "]"; print_text(acc)
19390    lower_text_literal(code, ctx, num_regs, b"]");
19391    local_set(code, part);
19392    emit_text_concat(code, ctx, num_regs, acc, part, acc);
19393    local_get(code, acc);
19394    code.push(0x10); // call print_text
19395    leb_u32(code, print_idx);
19396    Ok(())
19397}
19398
19399/// `Show <map>` — `RuntimeValue::Map::to_display_string` = `{k0: v0, k1: v1, …}` over the map's
19400/// entries in STORED order: INSERTION order for a `Map` (the VM's `MapStorage` is an `IndexMap`, the
19401/// order the linear map appends in) and key order for a `SharedMap` (kept sorted on insert), so the
19402/// rendering is byte-identical to the reference tier's. A RUNTIME loop over `0..num_entries`, each
19403/// 16-byte entry `[key@0][value@8]` stringified by its kinds and joined as `k: v`. The kinds come
19404/// from the last `SetIndex`'s registers in this region, or from the map's declared type.
19405///
19406/// A map with neither is a locally-declared map nothing ever wrote — every entry is created by a
19407/// `SetIndex` — so it holds zero entries and displays as `{}`, the VM's empty `IndexMap`. A declared
19408/// map type whose key kind this backend cannot represent is refused.
19409/// What a whole-map `Show` of `src` renders from — one answer for the import scan and the lowering.
19410enum MapShowKinds {
19411    /// Entries of these key and value kinds.
19412    Entries(Option<Kind>, Option<Kind>),
19413    /// A locally-declared map nothing ever wrote: `{}`.
19414    Empty,
19415    /// A declared map whose key or value kind this backend cannot represent.
19416    Unknown,
19417}
19418
19419/// The key and value kinds of the map in `src`: the registers of a `SetIndex` on it in this region,
19420/// or else its DECLARED type (a parameter, a global, a record's field, a call result).
19421fn map_show_kinds(plan: &Plan, src: u16) -> MapShowKinds {
19422    match plan.structs.map_set_key.get(&src) {
19423        Some(&key_reg) => match plan.structs.map_set_value.get(&src) {
19424            Some(&val_reg) => MapShowKinds::Entries(
19425                plan.kinds.get(key_reg as usize),
19426                plan.kinds.get(val_reg as usize),
19427            ),
19428            None => MapShowKinds::Unknown,
19429        },
19430        None => match plan.structs.reg_shape.get(&src) {
19431            Some(ParamShape::Map {
19432                key: Some(k),
19433                value,
19434                ..
19435            }) => MapShowKinds::Entries(Some(*k), Some(*value)),
19436            Some(ParamShape::Map { key: None, .. }) => MapShowKinds::Unknown,
19437            _ => MapShowKinds::Empty,
19438        },
19439    }
19440}
19441
19442fn lower_show_map(
19443    code: &mut Vec<u8>,
19444    plan: &Plan,
19445    _kinds: &KindTable,
19446    ctx: &Ctx,
19447    src: u16,
19448) -> R<()> {
19449    let (key_kind, val_kind) = match map_show_kinds(plan, src) {
19450        MapShowKinds::Entries(k, v) => (k, v),
19451        MapShowKinds::Empty => return lower_show_empty_map(code, plan, ctx),
19452        MapShowKinds::Unknown => {
19453            return Err(WasmLowerError::Unsupported(
19454                "Show of a map whose key or value kind is not statically known",
19455            ))
19456        }
19457    };
19458    let key_text = match key_kind {
19459        Some(Kind::Text) => true,
19460        Some(Kind::Int) => false,
19461        _ => {
19462            return Err(WasmLowerError::Unsupported(
19463                "Show of a map with a non-Int/Text key",
19464            ))
19465        }
19466    };
19467    let val_load = map_value_load(val_kind)?; // the value's slot load at its kind's width
19468    let print_idx = (ctx.host_index)(HostFn::PrintText).ok_or(WasmLowerError::Unsupported(
19469        "Show map: print_text not imported",
19470    ))?;
19471    let num_regs = plan.num_regs;
19472    let m = src as u32;
19473    // acc = accumulator Text; part = each stringified piece; i = the entry loop counter. Key/value
19474    // temps borrow width-matched scratch (idle during a Show): the key is fully stringified before the
19475    // value is loaded, so they may share a slot.
19476    let (acc, part, i) = (num_regs + 8, num_regs + 9, num_regs + 10);
19477    let key_tmp = if key_text {
19478        num_regs + 11
19479    } else {
19480        num_regs + 1
19481    };
19482    let val_tmp = match val_kind.map(Kind::wasm_valtype) {
19483        Some(F64) => num_regs + 12,
19484        Some(I64) => num_regs + 1,
19485        _ => num_regs + 11,
19486    };
19487    // acc = "{"
19488    lower_text_literal(code, ctx, num_regs, b"{");
19489    local_set(code, acc);
19490    // i = 0
19491    i32_const(code, 0);
19492    local_set(code, i);
19493    code.push(0x02);
19494    code.push(0x40); // block
19495    code.push(0x03);
19496    code.push(0x40); // loop
19497                     // if i >= num_entries: br block
19498    local_get(code, i);
19499    local_get(code, m);
19500    i32_load(code, 0); // num_entries
19501    code.push(0x4E); // i32.ge_s
19502    code.push(0x0D);
19503    leb_u32(code, 1); // br_if block
19504                      // separator: entries after the first are prefixed with ", "
19505    local_get(code, i);
19506    code.push(0x45); // i32.eqz → i == 0 ?
19507    code.push(0x04);
19508    code.push(0x40); // if (i == 0): nothing
19509    code.push(0x05); // else (i != 0)
19510    lower_text_literal(code, ctx, num_regs, b", ");
19511    local_set(code, part);
19512    emit_text_concat(code, ctx, num_regs, acc, part, acc);
19513    code.push(0x0B); // end if
19514                     // key = entry[i].key (offset 0), stringified, appended
19515    emit_map_entry_addr(code, m, i);
19516    if !key_text && ctx.exact.map_ints {
19517        exact::map_integer_text(code, ctx, num_regs, m, 0, part)?;
19518    } else {
19519        if key_text {
19520            i32_load(code, 0);
19521        } else {
19522            i64_load(code, 0);
19523        }
19524        local_set(code, key_tmp);
19525        emit_stringify(code, ctx, num_regs, key_tmp, key_kind, part)?;
19526    }
19527    emit_text_concat(code, ctx, num_regs, acc, part, acc);
19528    // ": "
19529    lower_text_literal(code, ctx, num_regs, b": ");
19530    local_set(code, part);
19531    emit_text_concat(code, ctx, num_regs, acc, part, acc);
19532    // value = entry[i].value (offset 8), stringified, appended
19533    emit_map_entry_addr(code, m, i);
19534    if val_kind == Some(Kind::Int) && ctx.exact.map_ints {
19535        exact::map_integer_text(code, ctx, num_regs, m, 8, part)?;
19536    } else {
19537        val_load(code, 8);
19538        local_set(code, val_tmp);
19539        emit_stringify(code, ctx, num_regs, val_tmp, val_kind, part)?;
19540    }
19541    emit_text_concat(code, ctx, num_regs, acc, part, acc);
19542    // i += 1
19543    local_get(code, i);
19544    i32_const(code, 1);
19545    code.push(0x6A);
19546    local_set(code, i);
19547    code.push(0x0C);
19548    leb_u32(code, 0); // br loop
19549    code.push(0x0B); // end loop
19550    code.push(0x0B); // end block
19551                     // acc += "}"; print_text(acc)
19552    lower_text_literal(code, ctx, num_regs, b"}");
19553    local_set(code, part);
19554    emit_text_concat(code, ctx, num_regs, acc, part, acc);
19555    local_get(code, acc);
19556    code.push(0x10); // call print_text
19557    leb_u32(code, print_idx);
19558    Ok(())
19559}
19560
19561/// `Show <empty map>` — a locally-declared map that never received a `SetIndex` holds zero entries,
19562/// so its display is the fixed `{}` (the VM's rendering of an empty `IndexMap`), emitted directly as a
19563/// `Text` literal without an entry loop (no key/value kind is needed because none is ever stringified).
19564fn lower_show_empty_map(code: &mut Vec<u8>, plan: &Plan, ctx: &Ctx) -> R<()> {
19565    let print_idx = (ctx.host_index)(HostFn::PrintText).ok_or(WasmLowerError::Unsupported(
19566        "Show map: print_text not imported",
19567    ))?;
19568    lower_text_literal(code, ctx, plan.num_regs, b"{}");
19569    code.push(0x10); // call print_text
19570    leb_u32(code, print_idx);
19571    Ok(())
19572}
19573
19574/// `Show tuple` — the tree-walker displays a heterogeneous tuple as `(e0, e1, …)`, each element by
19575/// its own scalar display. The tuple layout (element registers → kinds, via `structs.tuple_layouts`)
19576/// is known at compile time, so this UNROLLS: build the `Text` `"("`, then for each element load its
19577/// 8-byte slot, stringify it, and concat it onto the accumulator (with a `", "` separator between
19578/// elements), close with `")"`, and `print_text` the assembled string — byte-identical to
19579/// `RuntimeValue::Tuple::to_display_string`. Deterministic (tuple element order is fixed), unlike a
19580/// struct/map whose display order the tree-walker randomizes (hence those stay deferred). The
19581/// accumulator/separator live in the `+8`/`+9` handle scratch (which `emit_text_concat` preserves);
19582/// the element value is loaded into the `+1` (i64), `+12` (f64), or `+10` (i32-handle) temp by width.
19583fn lower_show_tuple(code: &mut Vec<u8>, plan: &Plan, ctx: &Ctx, src: u16) -> R<()> {
19584    let elems = plan
19585        .structs
19586        .tuple_layouts
19587        .get(&src)
19588        .ok_or(WasmLowerError::Unsupported(
19589            "Show of a tuple with no static layout",
19590        ))?;
19591    let num_regs = plan.num_regs;
19592    let (acc, part) = (num_regs + 8, num_regs + 9);
19593    // acc = "("
19594    lower_text_literal(code, ctx, num_regs, b"(");
19595    local_set(code, acc);
19596    let n = elems.len();
19597    for (i, &elem_reg) in elems.iter().enumerate() {
19598        let ek = plan.kinds.get(elem_reg as usize);
19599        // Load slot i (the element value at its width) into a matching-typed temp local.
19600        let elem_tmp = match ek.map(Kind::wasm_valtype) {
19601            Some(F64) => num_regs + 12, // f64 temp
19602            Some(I64) => num_regs + 1,  // i64 temp (borrows a pow scratch — idle during Show)
19603            _ => num_regs + 10,         // i32 handle temp (Text/…)
19604        };
19605        local_get(code, src as u32);
19606        i32_load(code, 8); // data_ptr
19607        emit_slot_load(code, ek, (i as u32) * 8)?;
19608        local_set(code, elem_tmp);
19609        // part = stringify(element); acc = acc + part
19610        if ctx.exact.sequence_ints() && plan.kinds.get(src as usize) == Some(Kind::SeqInt) {
19611            local_get(code, elem_tmp);
19612            code.push(0x10);
19613            leb_u32(
19614                code,
19615                (ctx.host_index)(HostFn::ExactText)
19616                    .ok_or(WasmLowerError::Unsupported("exact text import"))?,
19617            );
19618            local_set(code, part);
19619        } else {
19620            emit_stringify(code, ctx, num_regs, elem_tmp, ek, part)?;
19621        }
19622        emit_text_concat(code, ctx, num_regs, acc, part, acc);
19623        // ", " between elements
19624        if i + 1 < n {
19625            lower_text_literal(code, ctx, num_regs, b", ");
19626            local_set(code, part);
19627            emit_text_concat(code, ctx, num_regs, acc, part, acc);
19628        }
19629    }
19630    // acc = acc + ")"
19631    lower_text_literal(code, ctx, num_regs, b")");
19632    local_set(code, part);
19633    emit_text_concat(code, ctx, num_regs, acc, part, acc);
19634    // print_text(acc)
19635    let idx = (ctx.host_index)(HostFn::PrintText).ok_or(WasmLowerError::Unsupported(
19636        "Show tuple: print_text not imported",
19637    ))?;
19638    local_get(code, acc);
19639    code.push(0x10); // call print_text
19640    leb_u32(code, idx);
19641    Ok(())
19642}
19643
19644/// `Show <enum>` — a nullary variant displays as just its constructor name (`RuntimeValue::Inductive`
19645/// with empty args → `ind.constructor.clone()`). The enum handle's first word is the TAG (the
19646/// constructor name's constant index; `NewInductive`'s `ctor = add_const(Text(name))`), so this emits
19647/// a tag→name dispatch: for each variant of `src`'s enum type (resolved via `ind_type_of` →
19648/// `enum_types`), `if stored_tag == const_idx(name) { print_text name }`. Exactly one branch matches
19649/// (the live variant), so exactly one name prints — byte-identical to the tree-walker. Restricted to
19650/// ALL-NULLARY enum types; a payload variant (`Ctor(args)`) display is a later increment (soundly
19651/// refused, so such a Show stays deferred rather than miscompiling).
19652/// Build the display `Text` of the enum value in `handle` (its type `def`) into `out` — a nullary
19653/// variant renders as its constructor name, a payload variant as `Ctor(f0, f1, …)`
19654/// (`format!("{}({})", ctor, join(", "))`), matching `RuntimeValue::Inductive::to_display_string`. A
19655/// tag→name dispatch (`stored_tag == const_idx(name)`) selects the live variant; exactly one matches,
19656/// so `out` is always written. `part`/`field_i32` are scratch the CALLER must keep distinct from `out`
19657/// and (for the sequence case) from its outer accumulator/counter/handle. The reusable core of
19658/// [`lower_show_enum`] (a scalar `Show`) and [`lower_show_seqenum`] (per element of a `Seq of Enum`).
19659fn emit_enum_display(
19660    code: &mut Vec<u8>,
19661    ctx: &Ctx,
19662    num_regs: u32,
19663    def: &EnumTypeDef,
19664    handle: u32,
19665    out: u32,
19666    part: u32,
19667    field_i32: u32,
19668) -> R<()> {
19669    for v in &def.variants {
19670        // The variant's tag = the constant-pool index of its name `Text` (constant dedup makes this the
19671        // exact value `NewInductive` stored). A variant NEVER constructed anywhere is absent from the
19672        // pool — it can't be the runtime value, so it needs no branch.
19673        let Some(tag) = ctx
19674            .constants
19675            .iter()
19676            .position(|c| matches!(c, Constant::Text(n) if *n == v.name))
19677        else {
19678            continue;
19679        };
19680        let tag = tag as i32;
19681        local_get(code, handle);
19682        i32_load(code, 0); // the enum handle's stored tag
19683        i32_const(code, tag);
19684        code.push(0x46); // i32.eq → stored_tag == variant_tag
19685        code.push(0x04);
19686        code.push(0x40); // if (void)
19687                         // out = the constructor name (the whole display for a nullary variant)
19688        lower_text_literal(code, ctx, num_regs, v.name.as_bytes());
19689        local_set(code, out);
19690        if !v.field_types.is_empty() {
19691            // Append each payload value using this module's enum layout.
19692            lower_text_literal(code, ctx, num_regs, b"(");
19693            local_set(code, part);
19694            emit_text_concat(code, ctx, num_regs, out, part, out);
19695            let n = v.field_types.len();
19696            for (i, ft) in v.field_types.iter().enumerate() {
19697                let ek = kind::boundary_to_kind(ft);
19698                let elem_tmp = match ek.map(Kind::wasm_valtype) {
19699                    Some(F64) => num_regs + 12,
19700                    Some(I64) => num_regs + 1,
19701                    _ => field_i32,
19702                };
19703                local_get(code, handle);
19704                emit_enum_payload_base(code, ctx);
19705                emit_slot_load(code, ek, enum_payload_offset(ctx, i as u32))?;
19706                local_set(code, elem_tmp);
19707                emit_stringify(code, ctx, num_regs, elem_tmp, ek, part)?;
19708                emit_text_concat(code, ctx, num_regs, out, part, out);
19709                if i + 1 < n {
19710                    lower_text_literal(code, ctx, num_regs, b", ");
19711                    local_set(code, part);
19712                    emit_text_concat(code, ctx, num_regs, out, part, out);
19713                }
19714            }
19715            lower_text_literal(code, ctx, num_regs, b")");
19716            local_set(code, part);
19717            emit_text_concat(code, ctx, num_regs, out, part, out);
19718        }
19719        code.push(0x0B); // end if
19720    }
19721    Ok(())
19722}
19723
19724fn lower_show_enum(code: &mut Vec<u8>, plan: &Plan, ctx: &Ctx, src: u16) -> R<()> {
19725    let type_name = plan
19726        .structs
19727        .ind_type_of
19728        .get(&src)
19729        .ok_or(WasmLowerError::Unsupported(
19730            "Show of an enum whose type is not statically known",
19731        ))?;
19732    let def = ctx
19733        .enum_types
19734        .iter()
19735        .find(|e| &e.name == type_name)
19736        .ok_or(WasmLowerError::Unsupported("Show of an unknown enum type"))?;
19737    let print_idx = (ctx.host_index)(HostFn::PrintText).ok_or(WasmLowerError::Unsupported(
19738        "Show enum: print_text not imported",
19739    ))?;
19740    let num_regs = plan.num_regs;
19741    // out = the assembled display; +9/+10 are the piece + field-i32 scratch (the classic `Show` pool).
19742    let out = num_regs + 8;
19743    emit_enum_display(
19744        code,
19745        ctx,
19746        num_regs,
19747        def,
19748        src as u32,
19749        out,
19750        num_regs + 9,
19751        num_regs + 10,
19752    )?;
19753    local_get(code, out);
19754    code.push(0x10); // call print_text
19755    leb_u32(code, print_idx);
19756    Ok(())
19757}
19758
19759/// `Show <Seq of Enum>` — `[e0, e1, …]` over the sequence in insertion order, each element rendered by
19760/// [`emit_enum_display`] (nullary name or `Ctor(fields)`). A RUNTIME loop: element `i` is an i32 enum
19761/// handle at `data_ptr+i*8`; its display is built into `out` and concatenated onto the outer `[…]`
19762/// accumulator. The element enum type comes from `seq_elem_ind_type` (the homogeneous list's element).
19763fn lower_show_seqenum(code: &mut Vec<u8>, plan: &Plan, ctx: &Ctx, src: u16) -> R<()> {
19764    let type_name = plan
19765        .structs
19766        .seq_elem_ind_type
19767        .get(&src)
19768        .ok_or(WasmLowerError::Unsupported(
19769            "Show of a Seq of Enum whose element type is not statically known",
19770        ))?;
19771    let def =
19772        ctx.enum_types
19773            .iter()
19774            .find(|e| &e.name == type_name)
19775            .ok_or(WasmLowerError::Unsupported(
19776                "Show seq-enum: unknown element enum type",
19777            ))?;
19778    let print_idx = (ctx.host_index)(HostFn::PrintText).ok_or(WasmLowerError::Unsupported(
19779        "Show seq-enum: print_text not imported",
19780    ))?;
19781    let num_regs = plan.num_regs;
19782    let m = src as u32;
19783    // Outer loop: `outer_acc` = `[…]`, `i` = counter, `elem` = the current enum handle. The per-element
19784    // display goes to `out`, using `part`/`field_i32` (+13/+14) kept distinct from all of the above.
19785    let (outer_acc, out, i, elem) = (num_regs + 8, num_regs + 9, num_regs + 10, num_regs + 11);
19786    let (part, field_i32) = (num_regs + 13, num_regs + 14);
19787    lower_text_literal(code, ctx, num_regs, b"[");
19788    local_set(code, outer_acc);
19789    i32_const(code, 0);
19790    local_set(code, i);
19791    code.push(0x02);
19792    code.push(0x40); // block
19793    code.push(0x03);
19794    code.push(0x40); // loop
19795                     // if i >= len: br block
19796    local_get(code, i);
19797    local_get(code, m);
19798    i32_load(code, 0);
19799    code.push(0x4E); // i32.ge_s
19800    code.push(0x0D);
19801    leb_u32(code, 1);
19802    // separator ", " before every element after the first
19803    local_get(code, i);
19804    code.push(0x45); // i32.eqz
19805    code.push(0x04);
19806    code.push(0x40);
19807    code.push(0x05); // if (i==0) {} else
19808    lower_text_literal(code, ctx, num_regs, b", ");
19809    local_set(code, part);
19810    emit_text_concat(code, ctx, num_regs, outer_acc, part, outer_acc);
19811    code.push(0x0B); // end if
19812                     // elem = seq element i (i32 enum handle at data_ptr + i*8)
19813    local_get(code, m);
19814    i32_load(code, 8);
19815    local_get(code, i);
19816    i32_const(code, 8);
19817    code.push(0x6C); // i32.mul
19818    code.push(0x6A); // i32.add
19819    i32_load(code, 0);
19820    local_set(code, elem);
19821    // out = display(elem); outer_acc += out
19822    emit_enum_display(code, ctx, num_regs, def, elem, out, part, field_i32)?;
19823    emit_text_concat(code, ctx, num_regs, outer_acc, out, outer_acc);
19824    // i += 1; br loop
19825    local_get(code, i);
19826    i32_const(code, 1);
19827    code.push(0x6A);
19828    local_set(code, i);
19829    code.push(0x0C);
19830    leb_u32(code, 0);
19831    code.push(0x0B); // end loop
19832    code.push(0x0B); // end block
19833    lower_text_literal(code, ctx, num_regs, b"]");
19834    local_set(code, part);
19835    emit_text_concat(code, ctx, num_regs, outer_acc, part, outer_acc);
19836    local_get(code, outer_acc);
19837    code.push(0x10); // call print_text
19838    leb_u32(code, print_idx);
19839    Ok(())
19840}
19841
19842/// The (slot index, boundary type) of `field_name` in struct type `type_name`, from the DECLARED
19843/// field order (= the AOT's 8-byte-slot storage order). `None` if the type or field is unknown.
19844fn policy_field_slot<'a>(
19845    ctx: &'a Ctx,
19846    type_name: &str,
19847    field_name: &str,
19848) -> Option<(u16, &'a BoundaryType)> {
19849    let def = ctx.struct_types.iter().find(|s| s.name == type_name)?;
19850    def.fields
19851        .iter()
19852        .position(|(n, _)| n == field_name)
19853        .map(|i| (i as u16, &def.fields[i].1))
19854}
19855
19856/// Load struct `reg`'s Text field (an `i32` handle in the low word of slot `slot`) into `dst_local`.
19857fn emit_load_text_field(code: &mut Vec<u8>, reg: u16, slot: u16, dst_local: u32) {
19858    local_get(code, reg as u32);
19859    i32_load(code, 8); // data_ptr
19860    i32_load(code, u32::from(slot) * 8); // the Text handle at slot*8
19861    local_set(code, dst_local);
19862}
19863
19864/// Compile a policy `condition` against `subject` (and optional `object`, `u16::MAX` = none) into an
19865/// i32 (1 = holds, 0 = fails) left on the wasm stack — mirroring `evaluate_policy_condition`. Only the
19866/// Text-field / predicate / and-or / cross-field forms are lowered (they cover the shipping policies);
19867/// a numeric / boolean field compare is soundly refused (the `CheckPolicy` then stays deferred).
19868fn emit_policy_condition(
19869    code: &mut Vec<u8>,
19870    plan: &Plan,
19871    ctx: &Ctx,
19872    cond: &PolicyCondition,
19873    subject: u16,
19874    object: u16,
19875) -> R<()> {
19876    let (f8, f11) = (plan.num_regs + 8, plan.num_regs + 11);
19877    match cond {
19878        PolicyCondition::FieldEquals {
19879            field,
19880            value,
19881            is_string_literal,
19882        } => {
19883            if !is_string_literal {
19884                return Err(WasmLowerError::Unsupported(
19885                    "policy: non-Text field comparison",
19886                ));
19887            }
19888            let subj_type =
19889                plan.structs
19890                    .struct_name_of
19891                    .get(&subject)
19892                    .ok_or(WasmLowerError::Unsupported(
19893                        "policy: subject has no struct type",
19894                    ))?;
19895            let field_name = ctx.interner.resolve(*field);
19896            let (slot, bt) = policy_field_slot(ctx, subj_type, field_name).ok_or(
19897                WasmLowerError::Unsupported("policy: field not in subject type"),
19898            )?;
19899            if !matches!(bt, BoundaryType::Text) {
19900                return Err(WasmLowerError::Unsupported("policy: field is not Text"));
19901            }
19902            let value_str = ctx.interner.resolve(*value).to_string();
19903            emit_load_text_field(code, subject, slot, f8);
19904            lower_text_literal(code, ctx, plan.num_regs, value_str.as_bytes());
19905            local_set(code, f11);
19906            emit_text_eq(code, ctx, plan.num_regs, f8, f11);
19907        }
19908        PolicyCondition::Predicate { predicate, .. } => {
19909            let subj_type =
19910                plan.structs
19911                    .struct_name_of
19912                    .get(&subject)
19913                    .ok_or(WasmLowerError::Unsupported(
19914                        "policy: subject has no struct type",
19915                    ))?;
19916            let subj_sym = ctx
19917                .interner
19918                .lookup(subj_type)
19919                .ok_or(WasmLowerError::Unsupported(
19920                    "policy: subject type not interned",
19921                ))?;
19922            let preds =
19923                ctx.policies
19924                    .get_predicates(subj_sym)
19925                    .ok_or(WasmLowerError::Unsupported(
19926                        "policy: no predicates for subject type",
19927                    ))?;
19928            let pred = preds
19929                .iter()
19930                .find(|p| p.predicate_name == *predicate)
19931                .ok_or(WasmLowerError::Unsupported(
19932                    "policy: referenced predicate not found",
19933                ))?;
19934            emit_policy_condition(code, plan, ctx, &pred.condition, subject, object)?;
19935        }
19936        PolicyCondition::SubjectFieldEqualsObjectField {
19937            subject_field,
19938            object_field,
19939            ..
19940        }
19941        | PolicyCondition::ObjectFieldEquals {
19942            subject: subject_field,
19943            field: object_field,
19944            ..
19945        } => {
19946            if object == u16::MAX {
19947                return Err(WasmLowerError::Unsupported(
19948                    "policy: cross-field compare needs an object",
19949                ));
19950            }
19951            let subj_type =
19952                plan.structs
19953                    .struct_name_of
19954                    .get(&subject)
19955                    .ok_or(WasmLowerError::Unsupported(
19956                        "policy: subject has no struct type",
19957                    ))?;
19958            let obj_type =
19959                plan.structs
19960                    .struct_name_of
19961                    .get(&object)
19962                    .ok_or(WasmLowerError::Unsupported(
19963                        "policy: object has no struct type",
19964                    ))?;
19965            let sf = ctx.interner.resolve(*subject_field);
19966            let of = ctx.interner.resolve(*object_field);
19967            let (s_slot, s_bt) = policy_field_slot(ctx, subj_type, sf).ok_or(
19968                WasmLowerError::Unsupported("policy: subject field not found"),
19969            )?;
19970            let (o_slot, o_bt) = policy_field_slot(ctx, obj_type, of).ok_or(
19971                WasmLowerError::Unsupported("policy: object field not found"),
19972            )?;
19973            if !matches!(s_bt, BoundaryType::Text) || !matches!(o_bt, BoundaryType::Text) {
19974                return Err(WasmLowerError::Unsupported(
19975                    "policy: cross-field compare of non-Text fields",
19976                ));
19977            }
19978            emit_load_text_field(code, subject, s_slot, f8);
19979            emit_load_text_field(code, object, o_slot, f11);
19980            emit_text_eq(code, ctx, plan.num_regs, f8, f11);
19981        }
19982        PolicyCondition::Or(l, r) => {
19983            emit_policy_condition(code, plan, ctx, l, subject, object)?;
19984            emit_policy_condition(code, plan, ctx, r, subject, object)?;
19985            code.push(0x72); // i32.or
19986        }
19987        PolicyCondition::And(l, r) => {
19988            emit_policy_condition(code, plan, ctx, l, subject, object)?;
19989            emit_policy_condition(code, plan, ctx, r, subject, object)?;
19990            code.push(0x71); // i32.and
19991        }
19992        PolicyCondition::FieldBool { .. } => {
19993            return Err(WasmLowerError::Unsupported(
19994                "policy: boolean field condition",
19995            ));
19996        }
19997    }
19998    Ok(())
19999}
20000
20001/// `Check that <subject> is <predicate>` / `… can <action> <object>` (`CheckPolicy`) — resolve the
20002/// predicate/capability's condition from the `## Policy` registry, compile it inline, and TRAP
20003/// (`unreachable`) when it is false (the standalone module's analog of the VM's `check_policy` error);
20004/// when it holds, execution falls through to the following statements. Mirrors the VM semantics.
20005fn lower_check_policy(
20006    code: &mut Vec<u8>,
20007    plan: &Plan,
20008    ctx: &Ctx,
20009    subject: u16,
20010    predicate: crate::Symbol,
20011    is_capability: bool,
20012    object: u16,
20013) -> R<()> {
20014    let subj_type =
20015        plan.structs
20016            .struct_name_of
20017            .get(&subject)
20018            .ok_or(WasmLowerError::Unsupported(
20019                "CheckPolicy on a non-struct subject",
20020            ))?;
20021    let subj_sym = ctx
20022        .interner
20023        .lookup(subj_type)
20024        .ok_or(WasmLowerError::Unsupported(
20025            "CheckPolicy subject type not interned",
20026        ))?;
20027    let cond = if is_capability {
20028        let caps = ctx
20029            .policies
20030            .get_capabilities(subj_sym)
20031            .ok_or(WasmLowerError::Unsupported(
20032                "CheckPolicy: no capabilities for subject type",
20033            ))?;
20034        caps.iter()
20035            .find(|c| c.action == predicate)
20036            .map(|c| &c.condition)
20037            .ok_or(WasmLowerError::Unsupported(
20038                "CheckPolicy: capability not found",
20039            ))?
20040    } else {
20041        let preds = ctx
20042            .policies
20043            .get_predicates(subj_sym)
20044            .ok_or(WasmLowerError::Unsupported(
20045                "CheckPolicy: no predicates for subject type",
20046            ))?;
20047        preds
20048            .iter()
20049            .find(|p| p.predicate_name == predicate)
20050            .map(|p| &p.condition)
20051            .ok_or(WasmLowerError::Unsupported(
20052                "CheckPolicy: predicate not found",
20053            ))?
20054    };
20055    emit_policy_condition(code, plan, ctx, cond, subject, object)?;
20056    code.push(0x45); // i32.eqz → condition is FALSE
20057    code.push(0x04);
20058    code.push(0x40); // if (failed)
20059    code.push(0x00); // unreachable — the check failed (the VM errors here)
20060    code.push(0x0B); // end if
20061    Ok(())
20062}
20063
20064/// The byte stride of one per-replica counter record: `[replica_id:i64 @0][inc:i64 @8][dec:i64 @16]`.
20065/// A `ConvergentCount` (G-Counter) never touches `dec`; a `Tally` (PN-counter) uses both.
20066const CRDT_RECORD_BYTES: i32 = 24;
20067
20068/// Allocate a counted counter header over a scalar replica buffer.
20069/// A monotonic identity stays distinct after the allocator reuses a dead counter's storage,
20070/// including while another counter still retains the old replica's merged contribution.
20071fn emit_new_counter(code: &mut Vec<u8>, ctx: &Ctx, num_regs: u32, dst: u32) {
20072    let (hdr, data) = (num_regs + 5, num_regs + 6); // i32 heap scratch
20073                                                    // hdr = alloc(16); data = alloc(24)
20074    i32_const(code, 16);
20075    emit_alloc(code, ctx, hdr, AllocClass::CounterHeader);
20076    i32_const(code, CRDT_RECORD_BYTES);
20077    emit_alloc(code, ctx, data, AllocClass::Raw);
20078    // header: len = 1, cap = 1, data_ptr = data
20079    local_get(code, hdr);
20080    i32_const(code, 1);
20081    i32_store(code, 0);
20082    local_get(code, hdr);
20083    i32_const(code, 1);
20084    i32_store(code, 4);
20085    local_get(code, hdr);
20086    local_get(code, data);
20087    i32_store(code, 8);
20088    // An address may be reused after collection; an identity retained in a merged replica may not.
20089    let replica = ctx.replica_global.expect("counter identity global");
20090    global_get(code, replica);
20091    i64c(code, 1);
20092    code.push(0x7C);
20093    global_set(code, replica);
20094    global_get(code, replica);
20095    code.push(0x50); // i64.eqz: do not wrap the identity space
20096    code.push(0x04);
20097    code.push(0x40);
20098    code.push(0x00);
20099    code.push(0x0B);
20100    local_get(code, data);
20101    global_get(code, replica);
20102    i64_store(code, 0);
20103    local_get(code, data);
20104    code.push(0x42); // i64.const 0
20105    leb_i64(code, 0);
20106    i64_store(code, 8); // inc
20107    local_get(code, data);
20108    code.push(0x42);
20109    leb_i64(code, 0);
20110    i64_store(code, 16); // dec
20111    local_get(code, hdr);
20112    local_set(code, dst);
20113}
20114
20115/// `obj's <counter-field>` — project the per-replica counter OBJECT stored in the field slot to its
20116/// Int total `Σinc − Σdec`, into `dst` (an `i64` local). Loads the counter handle from the field's
20117/// slot, then a loop accumulates each record's `inc` and subtracts its `dec`. The single-replica case
20118/// runs the body once (`inc − dec`), matching the tree-walker's counter value byte-for-byte.
20119fn lower_get_counter_total(
20120    code: &mut Vec<u8>,
20121    plan: &Plan,
20122    slot: u16,
20123    dst: u16,
20124    obj: u16,
20125) -> R<()> {
20126    if plan.kinds.get(obj as usize) != Some(Kind::Struct) {
20127        return Err(WasmLowerError::Unsupported(
20128            "counter field access on a value with no known struct layout",
20129        ));
20130    }
20131    let (cnt, acc, i) = (plan.num_regs + 17, plan.num_regs + 15, plan.num_regs + 18); // cnt/i i32, acc i64
20132    let off = u32::from(slot) * 8;
20133    // cnt = obj.data_ptr[slot]  (the counter object handle)
20134    local_get(code, obj as u32);
20135    i32_load(code, 8);
20136    i32_load(code, off);
20137    local_set(code, cnt);
20138    // acc = 0; i = 0
20139    code.push(0x42);
20140    leb_i64(code, 0);
20141    local_set(code, acc);
20142    i32_const(code, 0);
20143    local_set(code, i);
20144    code.push(0x02);
20145    code.push(0x40); // block $exit
20146    code.push(0x03);
20147    code.push(0x40); // loop $loop
20148                     // if i >= len break
20149    local_get(code, i);
20150    local_get(code, cnt);
20151    i32_load(code, 0); // len
20152    code.push(0x4E); // i32.ge_s
20153    code.push(0x0D);
20154    leb_u32(code, 1); // br_if $exit
20155                      // rec = data_ptr + i * 24
20156                      // acc += rec.inc - rec.dec
20157    local_get(code, acc);
20158    // rec base address on the stack twice (for inc and dec loads)
20159    local_get(code, cnt);
20160    i32_load(code, 8); // data_ptr
20161    local_get(code, i);
20162    i32_const(code, CRDT_RECORD_BYTES);
20163    code.push(0x6C); // i32.mul
20164    code.push(0x6A); // data_ptr + i*24 = rec
20165    local_tee(code, plan.num_regs + 19); // rec cursor (i32 scratch)
20166    i64_load(code, 8); // inc
20167    code.push(0x7C); // acc + inc
20168    local_get(code, plan.num_regs + 19);
20169    i64_load(code, 16); // dec
20170    code.push(0x7D); // (acc+inc) - dec
20171    local_set(code, acc);
20172    // i += 1
20173    local_get(code, i);
20174    i32_const(code, 1);
20175    code.push(0x6A);
20176    local_set(code, i);
20177    code.push(0x0C);
20178    leb_u32(code, 0); // br $loop
20179    code.push(0x0B); // end loop
20180    code.push(0x0B); // end block
20181    local_get(code, acc);
20182    local_set(code, dst as u32);
20183    Ok(())
20184}
20185
20186/// `Increase/Decrease <obj>'s <field> by <amount>` (`CrdtBump`) on a `Shared` struct's
20187/// `ConvergentCount`/`Tally` field. The field holds a per-replica counter OBJECT; this bumps THIS
20188/// replica's own slot (record 0, allocated by `emit_new_counter`) — `Increase` adds to its `inc`,
20189/// `Decrease` adds to its `dec` (a `Tally`; a G-Counter never emits a decrement, rejected upstream).
20190/// The per-replica accounting is what makes a later `Merge` idempotent — the same remote state
20191/// re-merged MAXes equal values and never double-counts.
20192fn lower_crdt_bump(
20193    code: &mut Vec<u8>,
20194    plan: &Plan,
20195    ctx: &Ctx,
20196    obj: u16,
20197    field_const: u32,
20198    amount: u16,
20199    negate: bool,
20200) -> R<()> {
20201    let _ = ctx;
20202    // The counter's slot = its position in the struct's field layout (matched by the field-name const
20203    // index the op carries). `reg_layout` is populated from the actual `NewStruct`/`StructInsert` ops,
20204    // so it covers a `Shared` struct too (whose type may not be in the plain `struct_types`).
20205    let layout = plan
20206        .structs
20207        .reg_layout
20208        .get(&obj)
20209        .ok_or(WasmLowerError::Unsupported(
20210            "CrdtBump on a value with no struct layout",
20211        ))?;
20212    let slot =
20213        layout
20214            .iter()
20215            .position(|(fc, _)| *fc == field_const)
20216            .ok_or(WasmLowerError::Unsupported(
20217                "CrdtBump: field not in struct layout",
20218            ))? as u32;
20219    let off = slot * 8;
20220    // `Increase` accumulates into record 0's `inc`, `Decrease` into its `dec` (offset 8 vs 16).
20221    let rec_off = if negate { 16 } else { 8 };
20222    let rec = plan.num_regs + 17; // i32 scratch: the counter object's record-0 base (== data_ptr)
20223                                  // rec = obj.data_ptr[slot].data_ptr   (record 0 is at data_ptr + 0)
20224    local_get(code, obj as u32);
20225    i32_load(code, 8);
20226    i32_load(code, off); // the counter object handle
20227    i32_load(code, 8); // its data_ptr
20228    local_set(code, rec);
20229    // rec[rec_off] += amount
20230    local_get(code, rec);
20231    local_get(code, rec);
20232    i64_load(code, rec_off);
20233    local_get(code, amount as u32);
20234    code.push(0x7C); // i64.add (amount is a non-negative magnitude for both Increase and Decrease)
20235    i64_store(code, rec_off);
20236    Ok(())
20237}
20238
20239/// `Merge <source> into <target>` (`CrdtMerge`) of two same-typed `Shared` structs whose fields are
20240/// `ConvergentCount`/`Tally` counters. Each counter field is a per-replica counter OBJECT; the merge is
20241/// the state-based LATTICE JOIN — per-replica MAX on both `inc` and `dec`. IDEMPOTENT: a redelivered
20242/// source replica finds its record already present in the target and MAXes equal values, so it never
20243/// double-counts. Mirrors `logicaffeine_data::crdt::{GCounter, PNCounter}::merge` (the interpreter /
20244/// register VM / native AOT hold those exact types). A field that is NOT a counter CRDT needs a
20245/// different merge object and is soundly refused.
20246fn lower_crdt_merge(code: &mut Vec<u8>, plan: &Plan, ctx: &Ctx, target: u16, source: u16) -> R<()> {
20247    let layout = plan
20248        .structs
20249        .reg_layout
20250        .get(&target)
20251        .ok_or(WasmLowerError::Unsupported(
20252            "CrdtMerge on a value with no struct layout",
20253        ))?;
20254    let fields = layout.clone();
20255    for (slot, &(_fc, value_reg)) in fields.iter().enumerate() {
20256        let field_kind = value_reg.and_then(|r| plan.kinds.get(r as usize));
20257        if field_kind != Some(Kind::CrdtCounter) {
20258            // Name the author's own construct, not this backend's internal op — the same
20259            // convention every other backend's CRDT refusal already uses
20260            // (`crate::semantics::crdt::CrdtKind::refusal`), just for MERGING specifically: wasm
20261            // does lower a single-replica `SharedMap`/`SharedSet`/`SharedSequence` (this field's
20262            // OWN read/write ops), it merges none of them.
20263            let kind_name = match field_kind {
20264                Some(Kind::Map) => "SharedMap",
20265                Some(Kind::SetText) | Some(Kind::CrdtSetText) => "SharedSet",
20266                Some(Kind::SeqSeqInt) | Some(Kind::SeqInt) => "SharedSequence",
20267                _ => "a CRDT",
20268            };
20269            return Err(WasmLowerError::UnsupportedOwned(format!(
20270                "`{kind_name}` is a CRDT the wasm backend does not implement merging for — run \
20271                 the program on the interpreter or the VM, or build it with the Rust tier \
20272                 (`largo build`)"
20273            )));
20274        }
20275        emit_counter_field_merge(code, plan, ctx, target, source, (slot as u32) * 8);
20276    }
20277    Ok(())
20278}
20279
20280/// Per-replica MAX merge of ONE counter field: for each SOURCE record, find the matching replica in
20281/// the TARGET (by replica id) and MAX its `inc`/`dec`; if the replica is new, append the record. This
20282/// is the join that makes the counter idempotent. Scratch: `+17` target counter handle, `+18` source
20283/// counter handle, `+19` outer (source) index, `+20` source record base, `+15` source replica id,
20284/// `+21` matched target record base (0 = not found), `+22` inner (target) index.
20285fn emit_counter_field_merge(
20286    code: &mut Vec<u8>,
20287    plan: &Plan,
20288    ctx: &Ctx,
20289    target: u16,
20290    source: u16,
20291    off: u32,
20292) {
20293    let nr = plan.num_regs;
20294    let (t_cnt, s_cnt) = (nr + 17, nr + 18); // target / source counter object handles (i32)
20295    let (j, s_rec) = (nr + 19, nr + 20); // source index (i32), source record base (i32)
20296    let s_id = nr + 15; // source replica id (i64)
20297    let (found, k) = (nr + 21, nr + 22); // matched target record base (i32, 0=none), target index (i32)
20298                                         // t_cnt = target.data_ptr[slot]; s_cnt = source.data_ptr[slot]
20299    local_get(code, target as u32);
20300    i32_load(code, 8);
20301    i32_load(code, off);
20302    local_set(code, t_cnt);
20303    local_get(code, source as u32);
20304    i32_load(code, 8);
20305    i32_load(code, off);
20306    local_set(code, s_cnt);
20307    // for j in 0..s_cnt.len
20308    i32_const(code, 0);
20309    local_set(code, j);
20310    code.push(0x02);
20311    code.push(0x40); // block $outer_exit
20312    code.push(0x03);
20313    code.push(0x40); // loop $outer
20314    local_get(code, j);
20315    local_get(code, s_cnt);
20316    i32_load(code, 0); // s len
20317    code.push(0x4E); // i32.ge_s
20318    code.push(0x0D);
20319    leb_u32(code, 1); // br_if $outer_exit
20320                      // s_rec = s_cnt.data_ptr + j*24; s_id = s_rec.id
20321    local_get(code, s_cnt);
20322    i32_load(code, 8);
20323    local_get(code, j);
20324    i32_const(code, CRDT_RECORD_BYTES);
20325    code.push(0x6C);
20326    code.push(0x6A);
20327    local_tee(code, s_rec);
20328    i64_load(code, 0);
20329    local_set(code, s_id);
20330    // found = 0; for k in 0..t_cnt.len: if t_rec.id == s_id { found = t_rec; break }
20331    i32_const(code, 0);
20332    local_set(code, found);
20333    i32_const(code, 0);
20334    local_set(code, k);
20335    code.push(0x02);
20336    code.push(0x40); // block $inner_exit
20337    code.push(0x03);
20338    code.push(0x40); // loop $inner
20339    local_get(code, k);
20340    local_get(code, t_cnt);
20341    i32_load(code, 0); // t len
20342    code.push(0x4E); // i32.ge_s
20343    code.push(0x0D);
20344    leb_u32(code, 1); // br_if $inner_exit
20345                      // t_rec = t_cnt.data_ptr + k*24  (reuse `found` as the running candidate)
20346    local_get(code, t_cnt);
20347    i32_load(code, 8);
20348    local_get(code, k);
20349    i32_const(code, CRDT_RECORD_BYTES);
20350    code.push(0x6C);
20351    code.push(0x6A);
20352    local_tee(code, found);
20353    // if t_rec.id == s_id break (found holds the match)
20354    i64_load(code, 0);
20355    local_get(code, s_id);
20356    code.push(0x51); // i64.eq
20357    code.push(0x04);
20358    code.push(0x40); // if
20359    code.push(0x0C);
20360    leb_u32(code, 2); // br $inner_exit (out of the if, then the inner loop block)
20361    code.push(0x0B); // end if
20362                     // not a match this iteration → clear `found` so a fall-through past the last record means "none"
20363    i32_const(code, 0);
20364    local_set(code, found);
20365    local_get(code, k);
20366    i32_const(code, 1);
20367    code.push(0x6A);
20368    local_set(code, k);
20369    code.push(0x0C);
20370    leb_u32(code, 0); // br $inner
20371    code.push(0x0B); // end $inner loop
20372    code.push(0x0B); // end $inner_exit block
20373                     // if found != 0 { MAX inc + MAX dec } else { append (s_id, s_inc, s_dec) to target }
20374    local_get(code, found);
20375    code.push(0x45); // i32.eqz → found == 0
20376    code.push(0x04);
20377    code.push(0x40); // if (append path)
20378    emit_counter_append(code, plan, ctx, t_cnt, s_rec, s_id);
20379    code.push(0x05); // else (MAX path)
20380    emit_counter_record_max(code, found, s_rec, 8); // inc
20381    emit_counter_record_max(code, found, s_rec, 16); // dec
20382    code.push(0x0B); // end if
20383                     // j += 1
20384    local_get(code, j);
20385    i32_const(code, 1);
20386    code.push(0x6A);
20387    local_set(code, j);
20388    code.push(0x0C);
20389    leb_u32(code, 0); // br $outer
20390    code.push(0x0B); // end $outer loop
20391    code.push(0x0B); // end $outer_exit block
20392}
20393
20394/// `target[off] = max(target[off], source[off])` on an i64 record field (signed). No wasm i64.max, so
20395/// `select` on `i64.gt_s`.
20396fn emit_counter_record_max(code: &mut Vec<u8>, t_rec: u32, s_rec: u32, off: u32) {
20397    local_get(code, t_rec);
20398    // max(t, s) = t > s ? t : s
20399    local_get(code, t_rec);
20400    i64_load(code, off);
20401    local_get(code, s_rec);
20402    i64_load(code, off);
20403    local_get(code, t_rec);
20404    i64_load(code, off);
20405    local_get(code, s_rec);
20406    i64_load(code, off);
20407    code.push(0x55); // i64.gt_s
20408    code.push(0x1B); // select → (t>s) ? t : s
20409    i64_store(code, off);
20410}
20411
20412/// Append a fresh replica record `[s_id, s_rec.inc, s_rec.dec]` to the target counter object `t_cnt`,
20413/// growing its buffer geometrically and freeing the one growth abandons (mirrors `lower_list_push`,
20414/// but a 24-byte record stride). Reached only when a source replica is NOT already present in the
20415/// target — so the new state is genuinely new, and a later redelivery finds it present (idempotent).
20416fn emit_counter_append(
20417    code: &mut Vec<u8>,
20418    plan: &Plan,
20419    ctx: &Ctx,
20420    t_cnt: u32,
20421    s_rec: u32,
20422    s_id: u32,
20423) {
20424    let nr = plan.num_regs;
20425    // `dst_rec` = nr+22 (the merge's `k`, free in the append branch); MUST avoid `s_rec` (nr+20) and
20426    // `s_id` (nr+15), which are read to fill the new record after the buffer may have grown.
20427    let (hs_new, hs_i, hs_cap, dst_rec) = (nr + 5, nr + 6, nr + 7, nr + 22);
20428    // if len < cap { in place } else { grow }
20429    local_get(code, t_cnt);
20430    i32_load(code, 0); // len
20431    local_get(code, t_cnt);
20432    i32_load(code, 4); // cap
20433    code.push(0x48); // i32.lt_s
20434    code.push(0x04);
20435    code.push(0x40); // if (in place)
20436    {
20437        // dst_rec = data_ptr + len*24
20438        local_get(code, t_cnt);
20439        i32_load(code, 8);
20440        local_get(code, t_cnt);
20441        i32_load(code, 0);
20442        i32_const(code, CRDT_RECORD_BYTES);
20443        code.push(0x6C);
20444        code.push(0x6A);
20445        local_set(code, dst_rec);
20446    }
20447    code.push(0x05); // else (grow)
20448    {
20449        // new_cap = cap == 0 ? 1 : cap*2
20450        i32_const(code, 1);
20451        local_get(code, t_cnt);
20452        i32_load(code, 4);
20453        i32_const(code, 2);
20454        code.push(0x6C);
20455        local_get(code, t_cnt);
20456        i32_load(code, 4);
20457        code.push(0x45); // i32.eqz → cap == 0
20458        code.push(0x1B); // select
20459        local_set(code, hs_cap);
20460        // new = alloc(new_cap * 24)
20461        local_get(code, hs_cap);
20462        i32_const(code, CRDT_RECORD_BYTES);
20463        code.push(0x6C);
20464        emit_alloc(code, ctx, hs_new, AllocClass::Raw);
20465        // copy old records: for i in 0..len*24 step 8 (word copy) — copy len*3 i64 words
20466        i32_const(code, 0);
20467        local_set(code, hs_i);
20468        code.push(0x02);
20469        code.push(0x40); // block $copy_exit
20470        code.push(0x03);
20471        code.push(0x40); // loop $copy
20472        local_get(code, hs_i);
20473        local_get(code, t_cnt);
20474        i32_load(code, 0);
20475        i32_const(code, CRDT_RECORD_BYTES);
20476        code.push(0x6C); // len*24 (byte count)
20477        code.push(0x4E); // i32.ge_s → i >= len*24
20478        code.push(0x0D);
20479        leb_u32(code, 1); // br_if $copy_exit
20480                          // new[i] = old[i]  (i64 word copy at byte offset hs_i)
20481        local_get(code, hs_new);
20482        local_get(code, hs_i);
20483        code.push(0x6A);
20484        local_get(code, t_cnt);
20485        i32_load(code, 8); // old data_ptr
20486        local_get(code, hs_i);
20487        code.push(0x6A);
20488        i64_load(code, 0);
20489        i64_store(code, 0);
20490        local_get(code, hs_i);
20491        i32_const(code, 8);
20492        code.push(0x6A);
20493        local_set(code, hs_i);
20494        code.push(0x0C);
20495        leb_u32(code, 0); // br $copy
20496        code.push(0x0B); // end $copy loop
20497        code.push(0x0B); // end $copy_exit block
20498                         // dst_rec = new + len*24
20499        local_get(code, hs_new);
20500        local_get(code, t_cnt);
20501        i32_load(code, 0);
20502        i32_const(code, CRDT_RECORD_BYTES);
20503        code.push(0x6C);
20504        code.push(0x6A);
20505        local_set(code, dst_rec);
20506        // The old record buffer is dead by construction: this counter object is the only holder
20507        // and is about to stop pointing at it — read before the header is repointed, exactly as
20508        // `lower_list_push_at` frees the buffer a sequence's growth abandons.
20509        emit_free(
20510            code,
20511            ctx,
20512            |c| {
20513                local_get(c, t_cnt);
20514                i32_load(c, 8); // the OLD data_ptr
20515            },
20516            |c| {
20517                local_get(c, t_cnt);
20518                i32_load(c, 4); // the OLD cap
20519                i32_const(c, CRDT_RECORD_BYTES);
20520                c.push(0x6C);
20521            },
20522        );
20523        // header: data_ptr = new, cap = new_cap
20524        local_get(code, t_cnt);
20525        local_get(code, hs_new);
20526        i32_store(code, 8);
20527        local_get(code, t_cnt);
20528        local_get(code, hs_cap);
20529        i32_store(code, 4);
20530    }
20531    code.push(0x0B); // end if
20532                     // write the new record: [s_id, s_rec.inc, s_rec.dec]
20533    local_get(code, dst_rec);
20534    local_get(code, s_id);
20535    i64_store(code, 0);
20536    local_get(code, dst_rec);
20537    local_get(code, s_rec);
20538    i64_load(code, 8);
20539    i64_store(code, 8);
20540    local_get(code, dst_rec);
20541    local_get(code, s_rec);
20542    i64_load(code, 16);
20543    i64_store(code, 16);
20544    // header: len += 1
20545    local_get(code, t_cnt);
20546    local_get(code, t_cnt);
20547    i32_load(code, 0);
20548    i32_const(code, 1);
20549    code.push(0x6A);
20550    i32_store(code, 0);
20551}
20552
20553/// `Resolve <obj>'s <field> to <value>` (`CrdtResolve`) — a single-replica Divergent register just
20554/// takes the new value (the VM overwrites the field: `s.fields.insert(field, v)`). So this stores the
20555/// value handle into the field's slot (resolved from `reg_layout` by the field-name const), matching
20556/// a plain field write — byte-identical for one replica. (A merged multi-value register is deferred.)
20557fn lower_crdt_resolve(
20558    code: &mut Vec<u8>,
20559    plan: &Plan,
20560    kinds: &KindTable,
20561    obj: u16,
20562    field_const: u32,
20563    value: u16,
20564) -> R<()> {
20565    let layout = plan
20566        .structs
20567        .reg_layout
20568        .get(&obj)
20569        .ok_or(WasmLowerError::Unsupported(
20570            "CrdtResolve on a value with no struct layout",
20571        ))?;
20572    let slot =
20573        layout
20574            .iter()
20575            .position(|(fc, _)| *fc == field_const)
20576            .ok_or(WasmLowerError::Unsupported(
20577                "CrdtResolve: field not in struct layout",
20578            ))? as u32;
20579    let off = slot * 8;
20580    local_get(code, obj as u32);
20581    i32_load(code, 8); // data_ptr (store base)
20582    local_get(code, value as u32);
20583    emit_slot_store(code, kinds.get(value as usize), off)?;
20584    Ok(())
20585}
20586
20587/// `Append <value> to <seq>` (`CrdtAppend`) — a single-replica RGA/sequence is just a growable list,
20588/// so this appends in place (the VM: a `List` → `list_push`). The CRDT collection is intentionally
20589/// MUTABLE-SHARED (the VM keeps it behind an `Rc` and says "appending in place propagates — no
20590/// write-back"), so this must NOT copy-on-write: it drives `lower_list_push` directly (whose in-place
20591/// header update the aliasing field sees). An OR-Set append routes to the dedup set add, which keeps a
20592/// CRDT set sorted.
20593fn lower_crdt_append(
20594    code: &mut Vec<u8>,
20595    plan: &Plan,
20596    kinds: &KindTable,
20597    ctx: &Ctx,
20598    seq: u16,
20599    value: u16,
20600) -> R<()> {
20601    match kinds.get(seq as usize) {
20602        Some(Kind::SeqText) | Some(Kind::SeqInt) | Some(Kind::SeqBool) | Some(Kind::SeqFloat)
20603        | Some(Kind::SeqAny) => lower_list_push(code, kinds, ctx, plan.num_regs, seq, value),
20604        Some(Kind::SetText) | Some(Kind::CrdtSetText) => {
20605            emit_set_add_elem(
20606                code,
20607                ctx,
20608                plan.num_regs,
20609                seq as u32,
20610                value as u32,
20611                true,
20612                SetOrder::Sorted,
20613            );
20614            Ok(())
20615        }
20616        Some(Kind::Set) => {
20617            emit_set_add_elem(
20618                code,
20619                ctx,
20620                plan.num_regs,
20621                seq as u32,
20622                value as u32,
20623                false,
20624                SetOrder::Sorted,
20625            );
20626            Ok(())
20627        }
20628        _ => Err(WasmLowerError::Unsupported(
20629            "CrdtAppend to a non-collection CRDT",
20630        )),
20631    }
20632}
20633
20634/// `Push src to obj's field` (`ListPushField`) — the direct field-seq push (`Push x to p's items`).
20635/// Resolve the field's slot (`reg_layout`, matched by the field-name const) and its element kind (from
20636/// the register that defined the field's value), load the field's seq handle, and push through the
20637/// shared amortized [`lower_list_push_at`]. The seq's header address is stable across the push, so the
20638/// struct's field slot keeps pointing at it (no write-back). COW `obj` first (value-semantic struct
20639/// mutation); the exercised programs own `obj` uniquely (a nested aliased field-seq is a COW frontier).
20640/// `Push src to obj's field` — onto the list in the field of the record `obj` holds, value
20641/// semantics on both levels: a record another value may share (`cow`, [`cow_struct_inserts`]) is
20642/// copied first, and a list another holder shares is copied into this record's field before the push.
20643#[allow(clippy::too_many_arguments)]
20644fn lower_list_push_field(
20645    code: &mut Vec<u8>,
20646    plan: &Plan,
20647    kinds: &KindTable,
20648    ctx: &Ctx,
20649    cow: bool,
20650    obj: u16,
20651    field_const: u32,
20652    src: u16,
20653) -> R<()> {
20654    let slot = record_field_slot(plan, obj, field_const).ok_or(WasmLowerError::Unsupported(
20655        "push to a field of a value with no known record layout",
20656    ))?;
20657    if cow {
20658        emit_record_copy(code, ctx, kinds, &plan.structs, plan.num_regs, obj, None)?;
20659    }
20660    // The element width comes from the PUSHED value's kind (the field seq may have been default-filled
20661    // empty, leaving its declared element kind unrefined) — an Int rides an i64 slot, a Text/handle an
20662    // i32 in the low word, all 8-byte slots.
20663    let elem = kinds.get(src as usize).ok_or(WasmLowerError::Unsupported(
20664        "ListPushField: unknown pushed-value kind",
20665    ))?;
20666    let off = (slot as u32) * 8;
20667    let handle = plan.num_regs + 8; // i32 scratch, distinct from lower_list_push_at's +5/+6/+7
20668                                    // handle = obj.data_ptr[slot] (the field seq's i32 handle)
20669    local_get(code, obj as u32);
20670    i32_load(code, 8);
20671    i32_load(code, off);
20672    local_set(code, handle);
20673    let field_kind =
20674        record_slot_kinds(kinds, &plan.structs, obj).and_then(|ks| ks.get(slot).copied().flatten());
20675    if let Some(fk) = field_kind.filter(|&k| cow_clonable(Some(k)) && is_collection_clonable(k)) {
20676        emit_should_clone(code, handle);
20677        code.push(0x04);
20678        code.push(0x40); // if the list is shared: this record's field takes a copy of its own
20679        {
20680            emit_collection_clone(code, ctx, plan.num_regs, fk, handle);
20681            local_get(code, obj as u32);
20682            i32_load(code, 8);
20683            local_get(code, plan.num_regs + 5);
20684            i32_store(code, off);
20685            local_get(code, plan.num_regs + 5);
20686            local_set(code, handle);
20687            // S8's true count: the field holds the fresh copy beyond the turn that made it.
20688            if ctx.heap_counting() && counted_kind(Some(fk)) {
20689                emit_true_retain_of(code, ctx, |c| local_get(c, handle));
20690            }
20691        }
20692        code.push(0x0B);
20693    }
20694    if elem == Kind::Int && ctx.exact.sequence_ints() {
20695        exact::promote_sequence(code, ctx, plan.num_regs, handle)?;
20696        exact::push_sequence_word(code, plan, ctx, handle, src)
20697    } else {
20698        lower_list_push_at(code, elem, ctx, plan.num_regs, handle, src)
20699    }
20700}
20701
20702/// Whether argument `a` of a call of `func`, register `arg`, is a heap value the callee's parameter becomes a second
20703/// holder of: one the parameter takes as it is, not one converted into the runtime's value.
20704fn shares_argument(plan: &Plan, ctx: &Ctx, func: u16, a: u16, arg: u16) -> bool {
20705    let param = ctx
20706        .fn_param_kinds
20707        .get(func as usize)
20708        .and_then(|ks| ks.get(a as usize))
20709        .copied()
20710        .flatten();
20711    counts_aliases(plan.kinds.get(arg as usize)) && param != Some(Kind::Tower)
20712}
20713
20714/// Push argument `a` of a call of `func`, register `arg`, as the callee's parameter takes it: the runtime's value
20715/// for a parameter holding a value of the exact extension ([`tower::push_argument`]), the rational an integer
20716/// equals for a rational parameter, the `f64` of an `Int` for a `Float` parameter (`half(9)` → `half(9.0)`), and
20717/// anything else at its own value type, which must be the parameter's.
20718fn push_call_argument(code: &mut Vec<u8>, plan: &Plan, ctx: &Ctx, func: u16, a: u16, arg: u16) -> R<()> {
20719    let kinds = &plan.kinds;
20720    let param = ctx
20721        .fn_param_kinds
20722        .get(func as usize)
20723        .and_then(|ks| ks.get(a as usize))
20724        .copied()
20725        .flatten();
20726    if tower::push_argument(code, plan, ctx, arg, param)?.is_some() {
20727        return Ok(());
20728    }
20729    let arg_vt = kinds.valtype(arg as usize);
20730    let param_vt = ctx
20731        .fn_param_valtypes
20732        .get(func as usize)
20733        .ok_or(WasmLowerError::Unsupported("call of unknown function"))?
20734        .get(a as usize)
20735        .copied()
20736        .unwrap_or(I64);
20737    if param == Some(Kind::Rational) && matches!(kinds.get(arg as usize), Some(Kind::Int | Kind::BigInt)) {
20738        push_rational_operand(code, kinds, ctx, arg)
20739    } else if arg_vt == param_vt {
20740        local_get(code, arg as u32);
20741        Ok(())
20742    } else if arg_vt == I64 && param_vt == F64 {
20743        push_as_f64(code, arg, kinds.get(arg as usize))
20744    } else {
20745        Err(WasmLowerError::Unsupported(
20746            "call argument type does not match the parameter",
20747        ))
20748    }
20749}
20750
20751/// Emit a task's argument marshaling + `call` (the shared core of `Spawn` and `SpawnHandle`) — retain clonable
20752/// heap args (value semantics), pass each as the callee's parameter takes it ([`push_call_argument`]). Returns
20753/// whether the callee leaves a RESULT on the stack (dropped for a fire-and-forget spawn).
20754fn emit_sync_call(
20755    code: &mut Vec<u8>,
20756    plan: &Plan,
20757    ctx: &Ctx,
20758    func: u16,
20759    args_start: u16,
20760    arg_count: u16,
20761) -> R<bool> {
20762    if ctx.fn_stubbed.get(func as usize).copied().unwrap_or(false) {
20763        code.push(0x00); // unreachable — the reach analysis proved this call never runs
20764        return Ok(false);
20765    }
20766    if ctx
20767        .fn_inout
20768        .get(func as usize)
20769        .is_some_and(|ps| !ps.is_empty())
20770    {
20771        return Err(WasmLowerError::Unsupported(
20772            "a task that lends a variable to a `mutable` parameter",
20773        ));
20774    }
20775    for a in 0..arg_count {
20776        let arg = args_start + a;
20777        if shares_argument(plan, ctx, func, a, arg) {
20778            emit_retain(code, ctx, arg);
20779        }
20780    }
20781    for a in 0..arg_count {
20782        push_call_argument(code, plan, ctx, func, a, args_start + a)?;
20783    }
20784    code.push(0x10); // call
20785    leb_u32(code, ctx.fn_base + func as u32);
20786    Ok(ctx
20787        .fn_results
20788        .get(func as usize)
20789        .copied()
20790        .flatten()
20791        .is_some())
20792}
20793
20794/// `Receive <dst> from <chan>` (`ChanRecv`) on a single-threaded FIFO channel — pop the FRONT element:
20795/// Non-blocking `Try to receive` (`ChanTryRecv`) → an `Optional`: a non-empty queue pops its front
20796/// element and boxes it (`Some` — a fresh 8-byte heap box holding the inner scalar; handle != 0); an
20797/// empty queue yields `Nothing` (handle `0`). There is no blocking/trap path — the deterministic
20798/// single-task scheduler resumes a try-recv immediately either way (`scheduler::do_try_recv`). The
20799/// present inner kind (for a later `Show`) is carried out-of-band in `opt_inner` from this channel.
20800fn lower_chan_try_recv(
20801    code: &mut Vec<u8>,
20802    kinds: &KindTable,
20803    ctx: &Ctx,
20804    num_regs: u32,
20805    dst: u16,
20806    chan: u16,
20807) -> R<()> {
20808    let elem =
20809        kinds
20810            .get(chan as usize)
20811            .and_then(Kind::seq_elem)
20812            .ok_or(WasmLowerError::Unsupported(
20813                "try-receive from a channel of unknown element kind",
20814            ))?;
20815    let ch = chan as u32;
20816    let idx = num_regs + 5; // i32 pop-front shift-loop scratch
20817    let boxp = num_regs + 6; // i32 Optional box pointer
20818                             // A width-matched scratch holds the popped value before it is stored into the box.
20819    let val = match elem {
20820        Kind::Float => num_regs + 12, // f64 scratch
20821        Kind::Int
20822        | Kind::Bool
20823        | Kind::Char
20824        | Kind::Moment
20825        | Kind::Duration
20826        | Kind::Time
20827        | Kind::Span => num_regs + 1, // i64 scratch
20828        _ => num_regs + 7,            // i32-handle scratch
20829    };
20830    // if len == 0 { dst = Nothing (0) } else { pop front into `val`; box it; dst = box handle }
20831    local_get(code, ch);
20832    i32_load(code, 0);
20833    code.push(0x45); // i32.eqz → queue empty?
20834    code.push(0x04);
20835    code.push(0x40); // if (void block type)
20836    i32_const(code, 0);
20837    local_set(code, dst as u32); // Nothing
20838    code.push(0x05); // else
20839    emit_pop_front(code, elem, ch, idx, val)?;
20840    i32_const(code, 8);
20841    emit_alloc(code, ctx, boxp, AllocClass::Raw);
20842    local_get(code, boxp);
20843    local_get(code, val);
20844    emit_slot_store(code, Some(elem), 0)?;
20845    local_get(code, boxp);
20846    local_set(code, dst as u32);
20847    code.push(0x0B); // end if
20848    Ok(())
20849}
20850
20851/// load `data_ptr[0]`, shift every later 8-byte slot down one, decrement `len`. A receive on an EMPTY
20852/// channel would BLOCK on the scheduler; a standalone module has none, so it traps (`unreachable`) —
20853/// the non-blocking send-then-receive shape never hits it.
20854fn lower_chan_recv(
20855    code: &mut Vec<u8>,
20856    kinds: &KindTable,
20857    num_regs: u32,
20858    dst: u16,
20859    chan: u16,
20860) -> R<()> {
20861    let elem =
20862        kinds
20863            .get(chan as usize)
20864            .and_then(Kind::seq_elem)
20865            .ok_or(WasmLowerError::Unsupported(
20866                "receive from a channel of unknown element kind",
20867            ))?;
20868    let ch = chan as u32;
20869    let idx = num_regs + 5;
20870    // if len == 0 → trap (blocking receive, no scheduler to resume it)
20871    local_get(code, ch);
20872    i32_load(code, 0);
20873    code.push(0x45); // i32.eqz
20874    code.push(0x04);
20875    code.push(0x40);
20876    code.push(0x00); // unreachable
20877    code.push(0x0B);
20878    emit_pop_front(code, elem, ch, idx, dst as u32)
20879}
20880
20881/// Pop the FRONT element of channel/queue `ch` into `dst`: `dst = data[0]`, shift `data[1..len]`
20882/// down one 8-byte slot, then `len -= 1`. Assumes `len > 0` (the caller guards or traps). Shared by
20883/// [`lower_chan_recv`] and the winning recv arm of a `select` ([`lower_select_wait`]).
20884fn emit_pop_front(code: &mut Vec<u8>, elem: Kind, ch: u32, idx: u32, dst: u32) -> R<()> {
20885    let elem_load = seq_elem_load(elem)?;
20886    // dst = data_ptr[0]
20887    local_get(code, ch);
20888    i32_load(code, 8);
20889    elem_load(code, 0);
20890    local_set(code, dst);
20891    // for i in 0..len-1: data[i] = data[i+1] (8-byte slot copy)
20892    i32_const(code, 0);
20893    local_set(code, idx);
20894    code.push(0x02);
20895    code.push(0x40);
20896    code.push(0x03);
20897    code.push(0x40);
20898    local_get(code, idx);
20899    local_get(code, ch);
20900    i32_load(code, 0);
20901    i32_const(code, 1);
20902    code.push(0x6B);
20903    code.push(0x4E); // i32.ge_s → idx >= len-1
20904    code.push(0x0D);
20905    leb_u32(code, 1);
20906    local_get(code, ch);
20907    i32_load(code, 8);
20908    local_get(code, idx);
20909    i32_const(code, 8);
20910    code.push(0x6C);
20911    code.push(0x6A);
20912    local_get(code, ch);
20913    i32_load(code, 8);
20914    local_get(code, idx);
20915    i32_const(code, 1);
20916    code.push(0x6A);
20917    i32_const(code, 8);
20918    code.push(0x6C);
20919    code.push(0x6A);
20920    i64_load(code, 0);
20921    i64_store(code, 0);
20922    local_get(code, idx);
20923    i32_const(code, 1);
20924    code.push(0x6A);
20925    local_set(code, idx);
20926    code.push(0x0C);
20927    leb_u32(code, 0);
20928    code.push(0x0B);
20929    code.push(0x0B);
20930    // len -= 1
20931    local_get(code, ch);
20932    local_get(code, ch);
20933    i32_load(code, 0);
20934    i32_const(code, 1);
20935    code.push(0x6B);
20936    i32_store(code, 0);
20937    Ok(())
20938}
20939
20940/// Resolve a `select` (`Await the first of …`) deterministically, writing the winning arm's index
20941/// into `dst_arm` (the following compiler-emitted per-arm `Eq`/jump dispatch then runs that branch).
20942///
20943/// The arms were registered by the `SelectArm*` ops preceding this `SelectWait` in the same block
20944/// (each emits no code); we read them back by scanning the block, resetting at any earlier
20945/// `SelectWait` so a second `select` in one block sees only its own arms.
20946///
20947/// The resolution mirrors the seeded cooperative scheduler for the shapes the AOT models (no true
20948/// racing): the FIRST recv arm whose FIFO queue is non-empty wins (pop-front into its bound var);
20949/// if no recv arm is ready, the timeout arm fires. When no recv arm is ready and there is no
20950/// timeout arm the scheduler would block forever — a deterministic deadlock, emitted as a trap.
20951fn lower_select_wait(
20952    code: &mut Vec<u8>,
20953    plan: &Plan,
20954    kinds: &KindTable,
20955    blocks: &Blocks,
20956    k: usize,
20957    pc: usize,
20958    dst_arm: u16,
20959) -> R<()> {
20960    #[derive(Clone, Copy)]
20961    enum Arm {
20962        Recv { chan: u16, var: u16 },
20963        Timeout,
20964    }
20965    let mut arms: Vec<Arm> = Vec::new();
20966    for j in blocks.start(k)..pc {
20967        match plan.ops[j] {
20968            Op::SelectArmRecv { chan, var } => arms.push(Arm::Recv { chan, var }),
20969            Op::SelectArmTimeout { .. } => arms.push(Arm::Timeout),
20970            Op::SelectWait { .. } => arms.clear(),
20971            _ => {}
20972        }
20973    }
20974    let da = dst_arm as u32;
20975    let timeout_idx = arms.iter().position(|a| matches!(a, Arm::Timeout));
20976
20977    // dst_arm = -1 (no winner yet).
20978    code.push(0x42); // i64.const
20979    leb_i64(code, -1);
20980    local_set(code, da);
20981
20982    // First ready recv arm wins: `if dst_arm == -1 && len(chan) > 0 { var = pop_front(chan); dst_arm = i }`.
20983    for (i, arm) in arms.iter().enumerate() {
20984        if let Arm::Recv { chan, var } = *arm {
20985            let elem = kinds.get(chan as usize).and_then(Kind::seq_elem).ok_or(
20986                WasmLowerError::Unsupported("select recv arm on a channel of unknown element kind"),
20987            )?;
20988            local_get(code, da);
20989            code.push(0x42); // i64.const -1
20990            leb_i64(code, -1);
20991            code.push(0x51); // i64.eq → (dst_arm == -1)
20992            local_get(code, chan as u32);
20993            i32_load(code, 0); // len(chan)
20994            i32_const(code, 0);
20995            code.push(0x4A); // i32.gt_s → (len > 0)
20996            code.push(0x71); // i32.and
20997            code.push(0x04);
20998            code.push(0x40); // if (void)
20999            emit_pop_front(code, elem, chan as u32, plan.num_regs + 5, var as u32)?;
21000            code.push(0x42); // i64.const i
21001            leb_i64(code, i as i64);
21002            local_set(code, da);
21003            code.push(0x0B); // end if
21004        }
21005    }
21006
21007    // No recv arm ready → the timeout arm fires (or a deadlock trap if there is none).
21008    local_get(code, da);
21009    code.push(0x42); // i64.const -1
21010    leb_i64(code, -1);
21011    code.push(0x51); // i64.eq
21012    code.push(0x04);
21013    code.push(0x40); // if (void)
21014    match timeout_idx {
21015        Some(ti) => {
21016            code.push(0x42); // i64.const ti
21017            leb_i64(code, ti as i64);
21018            local_set(code, da);
21019        }
21020        None => code.push(0x00), // unreachable — no ready arm, no timeout: deadlock
21021    }
21022    code.push(0x0B); // end if
21023    Ok(())
21024}
21025
21026/// `i64.const v`.
21027fn i64c(code: &mut Vec<u8>, v: i64) {
21028    code.push(0x42);
21029    leb_i64(code, v);
21030}
21031
21032/// Lower `Op::MagicDivU` — `lhs / c` (`mul_back == 0`) or `lhs % c` (`mul_back == c`) via the
21033/// Granlund–Montgomery magic reciprocal, mirroring `vm::compiler::magic_eval` bit-for-bit. `magic`,
21034/// `more`, and `mul_back` are compile-time constants, so the flag paths are chosen HERE (in Rust) and
21035/// only the taken sequence is emitted. The 64×64→128 high word (`(magic * n) >> 64`) is computed from
21036/// 32-bit limbs (wasm has no mul-high). `lhs` is an Oracle-proven non-negative `Int` (i64).
21037fn lower_magic_div(
21038    code: &mut Vec<u8>,
21039    num_regs: u32,
21040    dst: u16,
21041    lhs: u16,
21042    magic: u64,
21043    more: u8,
21044    mul_back: i64,
21045) {
21046    const SHIFT_MASK: u8 = 0x3F;
21047    const ADD_MARKER: u8 = 0x40;
21048    const SHIFT_PATH: u8 = 0x80;
21049    let shift = (more & SHIFT_MASK) as i64;
21050    let q = num_regs + 1; // i64 scratch (reuses the integer-pow result slot)
21051    let n_lo = num_regs + 2;
21052    let n_hi = num_regs + 3;
21053    let hi = num_regs + 4;
21054    let mask: i64 = 0xFFFF_FFFF;
21055
21056    if more & SHIFT_PATH != 0 {
21057        // q = n >>u shift
21058        local_get(code, lhs as u32);
21059        i64c(code, shift);
21060        code.push(0x88); // i64.shr_u
21061        local_set(code, q);
21062    } else {
21063        // n limbs
21064        local_get(code, lhs as u32);
21065        i64c(code, mask);
21066        code.push(0x83); // i64.and
21067        local_set(code, n_lo);
21068        local_get(code, lhs as u32);
21069        i64c(code, 32);
21070        code.push(0x88); // shr_u
21071        local_set(code, n_hi);
21072        let m_lo = (magic & 0xFFFF_FFFF) as i64;
21073        let m_hi = (magic >> 32) as i64;
21074        // cross = (m_lo*n_lo >>u 32) + (m_hi*n_lo & mask) + (m_lo*n_hi & mask)  → into `q`
21075        i64c(code, m_lo);
21076        local_get(code, n_lo);
21077        code.push(0x7E); // mul
21078        i64c(code, 32);
21079        code.push(0x88); // >>u 32
21080        i64c(code, m_hi);
21081        local_get(code, n_lo);
21082        code.push(0x7E);
21083        i64c(code, mask);
21084        code.push(0x83); // & mask
21085        code.push(0x7C); // add
21086        i64c(code, m_lo);
21087        local_get(code, n_hi);
21088        code.push(0x7E);
21089        i64c(code, mask);
21090        code.push(0x83);
21091        code.push(0x7C); // add
21092        local_set(code, q); // q := cross
21093                            // hi = m_hi*n_hi + (m_hi*n_lo >>u 32) + (m_lo*n_hi >>u 32) + (cross >>u 32)
21094        i64c(code, m_hi);
21095        local_get(code, n_hi);
21096        code.push(0x7E); // hi_hi
21097        i64c(code, m_hi);
21098        local_get(code, n_lo);
21099        code.push(0x7E);
21100        i64c(code, 32);
21101        code.push(0x88);
21102        code.push(0x7C); // + (hi_lo>>32)
21103        i64c(code, m_lo);
21104        local_get(code, n_hi);
21105        code.push(0x7E);
21106        i64c(code, 32);
21107        code.push(0x88);
21108        code.push(0x7C); // + (lo_hi>>32)
21109        local_get(code, q);
21110        i64c(code, 32);
21111        code.push(0x88);
21112        code.push(0x7C); // + (cross>>32)
21113        local_set(code, hi);
21114        if more & ADD_MARKER != 0 {
21115            // q = (((n - hi) >>u 1) + hi) >>u shift
21116            local_get(code, lhs as u32);
21117            local_get(code, hi);
21118            code.push(0x7D); // sub
21119            i64c(code, 1);
21120            code.push(0x88); // >>u 1
21121            local_get(code, hi);
21122            code.push(0x7C); // + hi
21123            i64c(code, shift);
21124            code.push(0x88); // >>u shift
21125            local_set(code, q);
21126        } else {
21127            // q = hi >>u shift
21128            local_get(code, hi);
21129            i64c(code, shift);
21130            code.push(0x88);
21131            local_set(code, q);
21132        }
21133    }
21134
21135    if mul_back == 0 {
21136        local_get(code, q);
21137        local_set(code, dst as u32);
21138    } else {
21139        // result = lhs - q * mul_back
21140        local_get(code, lhs as u32);
21141        local_get(code, q);
21142        i64c(code, mul_back);
21143        code.push(0x7E); // mul
21144        code.push(0x7D); // sub
21145        local_set(code, dst as u32);
21146    }
21147}
21148
21149/// Lower `Op::ExactDiv` — `dst = lhs / rhs` as an exact `Rational` (`7 / 2 → 7/2`). Normalizes the
21150/// sign (den > 0), reduces by `gcd(|num|, den)`, allocates a counted scalar pair, and
21151/// leaves its handle in `dst`. A whole quotient reduces to `den == 1` (so `Show` renders just the
21152/// integer, matching the VM's downsize). Traps on a zero divisor (the VM errors "Division by zero").
21153fn lower_exact_div(code: &mut Vec<u8>, ctx: &Ctx, num_regs: u32, dst: u16, lhs: u16, rhs: u16) {
21154    let (num, den, a, b) = (num_regs + 1, num_regs + 2, num_regs + 3, num_regs + 4);
21155    let (handle, data) = (num_regs + 5, num_regs + 6);
21156    // rhs == 0 → trap
21157    local_get(code, rhs as u32);
21158    code.push(0x50); // i64.eqz
21159    code.push(0x04);
21160    code.push(0x40);
21161    code.push(0x00); // unreachable
21162    code.push(0x0B);
21163    // num = lhs; den = rhs
21164    local_get(code, lhs as u32);
21165    local_set(code, num);
21166    local_get(code, rhs as u32);
21167    local_set(code, den);
21168    // if den < 0 { num = -num; den = -den }
21169    local_get(code, den);
21170    i64c(code, 0);
21171    code.push(0x53); // i64.lt_s
21172    code.push(0x04);
21173    code.push(0x40);
21174    i64c(code, 0);
21175    local_get(code, num);
21176    code.push(0x7D); // sub → -num
21177    local_set(code, num);
21178    i64c(code, 0);
21179    local_get(code, den);
21180    code.push(0x7D);
21181    local_set(code, den);
21182    code.push(0x0B); // end if
21183                     // a = |num|
21184    local_get(code, num);
21185    local_set(code, a);
21186    local_get(code, a);
21187    i64c(code, 0);
21188    code.push(0x53); // a < 0
21189    code.push(0x04);
21190    code.push(0x40);
21191    i64c(code, 0);
21192    local_get(code, a);
21193    code.push(0x7D);
21194    local_set(code, a);
21195    code.push(0x0B);
21196    // b = den; gcd(a, b): while b != 0 { let r = a % b; a = b; b = r }
21197    local_get(code, den);
21198    local_set(code, b);
21199    code.push(0x02);
21200    code.push(0x40); // block
21201    code.push(0x03);
21202    code.push(0x40); // loop
21203    local_get(code, b);
21204    code.push(0x50); // i64.eqz
21205    code.push(0x0D);
21206    leb_u32(code, 1); // br_if exit (b == 0)
21207    local_get(code, a);
21208    local_get(code, b);
21209    code.push(0x81); // i64.rem_s → a % b (on stack)
21210    local_get(code, b);
21211    local_set(code, a); // a = old b
21212    local_set(code, b); // b = a % b
21213    code.push(0x0C);
21214    leb_u32(code, 0); // br loop
21215    code.push(0x0B); // end loop
21216    code.push(0x0B); // end block
21217                     // num /= a (gcd) ; den /= a
21218    local_get(code, num);
21219    local_get(code, a);
21220    code.push(0x7F); // i64.div_s
21221    local_set(code, num);
21222    local_get(code, den);
21223    local_get(code, a);
21224    code.push(0x7F);
21225    local_set(code, den);
21226    // An immutable pair owns two scalar slots through the ordinary counted header.
21227    i32_const(code, 16);
21228    emit_alloc(code, ctx, handle, AllocClass::ScalarHeader);
21229    i32_const(code, 16);
21230    emit_alloc(code, ctx, data, AllocClass::Raw);
21231    for off in [0u32, 4] {
21232        local_get(code, handle);
21233        i32_const(code, 2);
21234        i32_store(code, off);
21235    }
21236    local_get(code, handle);
21237    local_get(code, data);
21238    i32_store(code, 8);
21239    local_get(code, data);
21240    local_get(code, num);
21241    i64_store(code, 0);
21242    local_get(code, data);
21243    local_get(code, den);
21244    i64_store(code, 8);
21245    local_get(code, handle);
21246    local_set(code, dst as u32);
21247}
21248
21249/// Emit `for i in 0..len(src): dest[(base_off + i)] = src_bytes[i]`, a single-byte copy loop (for
21250/// `Text`). `offset_by_a` shifts the destination by `len(a_for_offset)` (to append after the first
21251/// operand of a concat); otherwise the copy is index-aligned.
21252fn emit_byte_copy(
21253    code: &mut Vec<u8>,
21254    idx: u32,
21255    dest_data: u32,
21256    a_for_offset: u32,
21257    src: u32,
21258    offset_by_a: bool,
21259) {
21260    i32_const(code, 0);
21261    local_set(code, idx);
21262    code.push(0x02);
21263    code.push(0x40); // block
21264    code.push(0x03);
21265    code.push(0x40); // loop
21266    local_get(code, idx);
21267    local_get(code, src);
21268    i32_load(code, 0); // len(src)
21269    code.push(0x4E); // i32.ge_s
21270    code.push(0x0D);
21271    leb_u32(code, 1); // br_if exit
21272                      // dest addr = dest_data + (offset + i)
21273    local_get(code, dest_data);
21274    if offset_by_a {
21275        local_get(code, a_for_offset);
21276        i32_load(code, 0); // len(a)
21277        local_get(code, idx);
21278        code.push(0x6A);
21279    } else {
21280        local_get(code, idx);
21281    }
21282    code.push(0x6A);
21283    // src byte = src_data[i]
21284    local_get(code, src);
21285    i32_load(code, 8); // src data_ptr
21286    local_get(code, idx);
21287    code.push(0x6A);
21288    i32_load8_u(code, 0);
21289    i32_store8(code, 0);
21290    // i++
21291    local_get(code, idx);
21292    i32_const(code, 1);
21293    code.push(0x6A);
21294    local_set(code, idx);
21295    code.push(0x0C);
21296    leb_u32(code, 0); // br loop
21297    code.push(0x0B); // end loop
21298    code.push(0x0B); // end block
21299}
21300
21301/// A string literal → a fresh `Text` object in linear memory, leaving its `i32` handle on the
21302/// stack. Bump-allocates a 16-byte header + an 8-aligned byte buffer, writes the UTF-8 bytes as
21303/// little-endian 8-byte `i64.store` chunks (the trailing chunk zero-padded past `len`, which is
21304/// never read), and fills the header `[len][cap][data_ptr]` (byte counts). Each execution makes a
21305/// fresh object, matching the tree-walker's value semantics (immutable, so the waste is benign).
21306fn lower_text_literal(code: &mut Vec<u8>, ctx: &Ctx, num_regs: u32, bytes: &[u8]) {
21307    // Interned: the literal already exists in the data section, so its handle is a constant and
21308    // nothing is built at run time. See [`TextPool`].
21309    if let Some(pool) = ctx.text_pool {
21310        let addr = pool.borrow_mut().intern(bytes);
21311        i32_const(code, addr);
21312        return;
21313    }
21314    let len = bytes.len();
21315    let cap8 = (len + 7) & !7; // 8-aligned buffer so the last i64.store stays in bounds
21316    let (hdr, data) = (num_regs + 5, num_regs + 6);
21317    i32_const(code, 16);
21318    emit_alloc(code, ctx, hdr, AllocClass::TextHeader);
21319    i32_const(code, cap8 as i32);
21320    emit_alloc(code, ctx, data, AllocClass::Raw);
21321    for c in 0..(cap8 / 8) {
21322        let mut v: u64 = 0;
21323        for j in 0..8 {
21324            if let Some(&b) = bytes.get(c * 8 + j) {
21325                v |= (b as u64) << (j * 8);
21326            }
21327        }
21328        local_get(code, data);
21329        code.push(0x42); // i64.const
21330        leb_i64(code, v as i64);
21331        i64_store(code, (c * 8) as u32);
21332    }
21333    local_get(code, hdr);
21334    i32_const(code, len as i32);
21335    i32_store(code, 0); // len (bytes)
21336    local_get(code, hdr);
21337    i32_const(code, len as i32);
21338    i32_store(code, 4); // cap
21339    local_get(code, hdr);
21340    local_get(code, data);
21341    i32_store(code, 8); // data_ptr
21342    local_get(code, hdr); // leave the handle on the stack
21343}
21344
21345/// `chr(code) -> Text` — a single-character `Text` from a Unicode scalar value. The UTF-8 encoding is
21346/// computed INLINE (1–4 bytes selected by the code point's range) and packed little-endian into an
21347/// `i64`, then written into a fresh Text object (`[len][cap][data_ptr]` header + an 8-byte data
21348/// buffer). An invalid scalar (a surrogate `U+D800..=U+DFFF` or `> U+10FFFF`) traps, matching the
21349/// VM's `char::from_u32(..)` returning `None`.
21350fn lower_chr(code: &mut Vec<u8>, ctx: &Ctx, num_regs: u32, dst: u16, arg: u16) {
21351    let c = num_regs + 1; // i64 code point
21352    let packed = num_regs + 2; // i64 UTF-8 bytes, little-endian in the low bytes
21353    let len = num_regs + 7; // i32 byte count
21354    let (hdr, data) = (num_regs + 5, num_regs + 6);
21355    // Continuation byte `0x80 | ((c >> shift) & 0x3F)`, shifted into byte position `pos`, left on stack.
21356    let cont = |code: &mut Vec<u8>, shift: i64, pos: i64| {
21357        local_get(code, c);
21358        i64c(code, shift);
21359        code.push(0x88); // i64.shr_u
21360        i64c(code, 0x3F);
21361        code.push(0x83); // i64.and
21362        i64c(code, 0x80);
21363        code.push(0x84); // i64.or
21364        i64c(code, pos);
21365        code.push(0x86); // i64.shl
21366    };
21367    // Lead byte `mask | (c >> shift)`, left on stack.
21368    let lead = |code: &mut Vec<u8>, shift: i64, mask: i64| {
21369        local_get(code, c);
21370        i64c(code, shift);
21371        code.push(0x88); // i64.shr_u
21372        i64c(code, mask);
21373        code.push(0x84); // i64.or
21374    };
21375    // c = arg
21376    local_get(code, arg as u32);
21377    local_set(code, c);
21378    // Trap on an invalid scalar value: (u64)c > 0x10FFFF  ||  (0xD800 <= c <= 0xDFFF).
21379    local_get(code, c);
21380    i64c(code, 0x10FFFF);
21381    code.push(0x56); // i64.gt_u
21382    local_get(code, c);
21383    i64c(code, 0xD800);
21384    code.push(0x5A); // i64.ge_u
21385    local_get(code, c);
21386    i64c(code, 0xDFFF);
21387    code.push(0x58); // i64.le_u
21388    code.push(0x71); // i32.and → in-surrogate-range
21389    code.push(0x72); // i32.or  → invalid
21390    code.push(0x04);
21391    code.push(0x40); // if (invalid)
21392    code.push(0x00); // unreachable (trap)
21393    code.push(0x0B); // end
21394                     // 1 byte: c < 0x80
21395    local_get(code, c);
21396    i64c(code, 0x80);
21397    code.push(0x54); // i64.lt_u
21398    code.push(0x04);
21399    code.push(0x40); // if
21400    local_get(code, c);
21401    local_set(code, packed);
21402    i32_const(code, 1);
21403    local_set(code, len);
21404    code.push(0x05); // else
21405                     // 2 bytes: c < 0x800
21406    local_get(code, c);
21407    i64c(code, 0x800);
21408    code.push(0x54); // i64.lt_u
21409    code.push(0x04);
21410    code.push(0x40); // if
21411    lead(code, 6, 0xC0);
21412    cont(code, 0, 8);
21413    code.push(0x84); // i64.or
21414    local_set(code, packed);
21415    i32_const(code, 2);
21416    local_set(code, len);
21417    code.push(0x05); // else
21418                     // 3 bytes: c < 0x10000
21419    local_get(code, c);
21420    i64c(code, 0x10000);
21421    code.push(0x54); // i64.lt_u
21422    code.push(0x04);
21423    code.push(0x40); // if
21424    lead(code, 12, 0xE0);
21425    cont(code, 6, 8);
21426    code.push(0x84); // i64.or
21427    cont(code, 0, 16);
21428    code.push(0x84); // i64.or
21429    local_set(code, packed);
21430    i32_const(code, 3);
21431    local_set(code, len);
21432    code.push(0x05); // else — 4 bytes
21433    lead(code, 18, 0xF0);
21434    cont(code, 12, 8);
21435    code.push(0x84); // i64.or
21436    cont(code, 6, 16);
21437    code.push(0x84); // i64.or
21438    cont(code, 0, 24);
21439    code.push(0x84); // i64.or
21440    local_set(code, packed);
21441    i32_const(code, 4);
21442    local_set(code, len);
21443    code.push(0x0B); // end (3-byte if)
21444    code.push(0x0B); // end (2-byte if)
21445    code.push(0x0B); // end (1-byte if)
21446                     // Build the Text: 16-byte header + an 8-byte data buffer (max 4 UTF-8 bytes ≤ 8).
21447    i32_const(code, 16);
21448    emit_alloc(code, ctx, hdr, AllocClass::TextHeader);
21449    i32_const(code, 8);
21450    emit_alloc(code, ctx, data, AllocClass::Raw);
21451    local_get(code, data);
21452    local_get(code, packed);
21453    i64_store(code, 0); // the packed bytes (low `len` are valid, the rest zero)
21454    local_get(code, hdr);
21455    local_get(code, len);
21456    i32_store(code, 0); // len (bytes)
21457    local_get(code, hdr);
21458    local_get(code, len);
21459    i32_store(code, 4); // cap
21460    local_get(code, hdr);
21461    local_get(code, data);
21462    i32_store(code, 8); // data_ptr
21463    local_get(code, hdr);
21464    local_set(code, dst as u32);
21465}
21466
21467/// `lhs followed by rhs` — concatenate two sequences into a fresh one (the tree-walker's
21468/// `arith::seq_concat`: lhs's elements then rhs's). Both element kinds match (raw 8-byte copy).
21469fn lower_seq_concat(
21470    code: &mut Vec<u8>,
21471    kinds: &KindTable,
21472    ctx: &Ctx,
21473    num_regs: u32,
21474    dst: u16,
21475    lhs: u16,
21476    rhs: u16,
21477) -> R<()> {
21478    let elem = seq_elem_kind(kinds, lhs)?;
21479    seq_elem_kind(kinds, rhs)?;
21480    let (a, b) = (lhs as u32, rhs as u32);
21481    let exact_ints = elem == Kind::Int && ctx.exact.sequence_ints();
21482    if exact_ints {
21483        exact::promote_sequence(code, ctx, num_regs, lhs as u32)?;
21484        exact::promote_sequence(code, ctx, num_regs, rhs as u32)?;
21485    }
21486    let (hdr, data, idx) = (num_regs + 5, num_regs + 6, num_regs + 7);
21487    // hdr = alloc(16); data = alloc((len_a + len_b) * 8)
21488    i32_const(code, 16);
21489    emit_alloc(
21490        code,
21491        ctx,
21492        hdr,
21493        if exact_ints {
21494            AllocClass::ExactIntegerHeader
21495        } else {
21496            AllocClass::of_elements(kind_is_handle(elem))
21497        },
21498    );
21499    local_get(code, a);
21500    i32_load(code, 0);
21501    local_get(code, b);
21502    i32_load(code, 0);
21503    code.push(0x6A); // len_a + len_b
21504    i32_const(code, 8);
21505    code.push(0x6C);
21506    emit_alloc(code, ctx, data, AllocClass::Raw);
21507    // copy lhs: for i in 0..len_a: data[i*8] = a_data[i*8]
21508    emit_seq_copy(code, idx, data, a, a, false);
21509    // copy rhs: for i in 0..len_b: data[(len_a + i)*8] = b_data[i*8]
21510    emit_seq_copy(code, idx, data, a, b, true);
21511    // header: len = cap = len_a + len_b; data_ptr = data
21512    for off in [0u32, 4] {
21513        local_get(code, hdr);
21514        local_get(code, a);
21515        i32_load(code, 0);
21516        local_get(code, b);
21517        i32_load(code, 0);
21518        code.push(0x6A);
21519        i32_store(code, off);
21520    }
21521    local_get(code, hdr);
21522    local_get(code, data);
21523    i32_store(code, 8);
21524    // S8's true count: the new list is a further holder of every element handle it copied.
21525    if kind_is_handle(elem) {
21526        emit_retain_children(code, ctx, hdr);
21527    }
21528    if exact_ints {
21529        let clone = (ctx.host_index)(HostFn::ExactClone)
21530            .ok_or(WasmLowerError::Unsupported("exact clone import"))?;
21531        emit_exact_buffer_holds(code, hdr, num_regs + 21, num_regs + 22, clone, true);
21532    }
21533    local_get(code, hdr);
21534    local_set(code, dst as u32);
21535    Ok(())
21536}
21537
21538/// Emit `for i in 0..len(src): dest[(base_off + i)*8] = src_data[i*8]`, a raw 8-byte element copy
21539/// loop. When `offset_by_a` the destination index is shifted by `len(a_for_offset)` (used to append
21540/// the second operand of a concat after the first); otherwise the copy is index-aligned.
21541fn emit_seq_copy(
21542    code: &mut Vec<u8>,
21543    idx: u32,
21544    dest_data: u32,
21545    a_for_offset: u32,
21546    src: u32,
21547    offset_by_a: bool,
21548) {
21549    i32_const(code, 0);
21550    local_set(code, idx);
21551    code.push(0x02);
21552    code.push(0x40); // block
21553    code.push(0x03);
21554    code.push(0x40); // loop
21555    local_get(code, idx);
21556    local_get(code, src);
21557    i32_load(code, 0); // len(src)
21558    code.push(0x4E); // i32.ge_s
21559    code.push(0x0D);
21560    leb_u32(code, 1); // br_if exit
21561                      // dest addr = dest_data + (offset + i)*8
21562    local_get(code, dest_data);
21563    if offset_by_a {
21564        local_get(code, a_for_offset);
21565        i32_load(code, 0); // len(a)
21566        local_get(code, idx);
21567        code.push(0x6A); // len(a) + i
21568    } else {
21569        local_get(code, idx);
21570    }
21571    i32_const(code, 8);
21572    code.push(0x6C);
21573    code.push(0x6A);
21574    // src addr = src_data + i*8
21575    local_get(code, src);
21576    i32_load(code, 8);
21577    local_get(code, idx);
21578    i32_const(code, 8);
21579    code.push(0x6C);
21580    code.push(0x6A);
21581    i64_load(code, 0);
21582    i64_store(code, 0);
21583    // i++
21584    local_get(code, idx);
21585    i32_const(code, 1);
21586    code.push(0x6A);
21587    local_set(code, idx);
21588    code.push(0x0C);
21589    leb_u32(code, 0); // br loop
21590    code.push(0x0B); // end loop
21591    code.push(0x0B); // end block
21592}
21593
21594/// `items start through end of seq` (1-based inclusive subsequence) — allocate a fresh sequence
21595/// and copy the in-range elements. Matches the tree-walker's `collections::slice` byte-for-byte,
21596/// including its out-of-range → empty rule: with `start0 = (start as usize).saturating_sub(1)` and
21597/// `end_excl = end as usize`, the result is non-empty iff `start0 < end_excl <= len` (the `usize`
21598/// casts are reproduced with unsigned i64 compares, so negative indices wrap huge → empty).
21599fn lower_slice(
21600    code: &mut Vec<u8>,
21601    kinds: &KindTable,
21602    ctx: &Ctx,
21603    num_regs: u32,
21604    dst: u16,
21605    collection: u16,
21606    start: u16,
21607    end: u16,
21608) -> R<()> {
21609    let elem = seq_elem_kind(kinds, collection)?; // require a scalar sequence; the copy is raw 8-byte either way
21610    let col = collection as u32;
21611    let (s0, ee) = (num_regs + 1, num_regs + 2); // i64 scratch: start0, end_excl
21612    let exact_ints = elem == Kind::Int && ctx.exact.sequence_ints();
21613    if exact_ints {
21614        exact::promote_sequence(code, ctx, num_regs, collection as u32)?;
21615    }
21616    let (hdr, data, idx) = (num_regs + 5, num_regs + 6, num_regs + 7); // i32 scratch
21617                                                                       // hdr = alloc(16)
21618    i32_const(code, 16);
21619    emit_alloc(
21620        code,
21621        ctx,
21622        hdr,
21623        if exact_ints {
21624            AllocClass::ExactIntegerHeader
21625        } else {
21626            AllocClass::of_elements(kind_is_handle(elem))
21627        },
21628    );
21629    // start0 = (start == 0) ? 0 : (start - 1)   [= saturating_sub((start as u64), 1)]
21630    code.push(0x42);
21631    leb_i64(code, 0); // 0
21632    local_get(code, start as u32);
21633    code.push(0x42);
21634    leb_i64(code, 1);
21635    code.push(0x7D); // start - 1
21636    local_get(code, start as u32);
21637    code.push(0x50); // i64.eqz(start)
21638    code.push(0x1B); // select → eqz ? 0 : start-1
21639    local_set(code, s0);
21640    // end_excl = end
21641    local_get(code, end as u32);
21642    local_set(code, ee);
21643    // nonempty = (start0 <u end_excl) && (end_excl <=u len)
21644    local_get(code, s0);
21645    local_get(code, ee);
21646    code.push(0x54); // i64.lt_u
21647    local_get(code, ee);
21648    local_get(code, col);
21649    i32_load(code, 0); // len
21650    code.push(0xAD); // i64.extend_i32_u
21651    code.push(0x58); // i64.le_u
21652    code.push(0x71); // i32.and
21653    code.push(0x04);
21654    code.push(0x40); // if (nonempty)
21655    {
21656        // count*8 → data = alloc(count*8)
21657        local_get(code, ee);
21658        local_get(code, s0);
21659        code.push(0x7D);
21660        code.push(0xA7); // count (i32)
21661        i32_const(code, 8);
21662        code.push(0x6C);
21663        emit_alloc(code, ctx, data, AllocClass::Raw);
21664        // for i in 0..count: data[i*8] = src_data[(start0+i)*8]  (raw 8-byte copy)
21665        i32_const(code, 0);
21666        local_set(code, idx);
21667        code.push(0x02);
21668        code.push(0x40); // block
21669        code.push(0x03);
21670        code.push(0x40); // loop
21671        local_get(code, idx);
21672        local_get(code, ee);
21673        local_get(code, s0);
21674        code.push(0x7D);
21675        code.push(0xA7); // count
21676        code.push(0x4E); // i32.ge_s
21677        code.push(0x0D);
21678        leb_u32(code, 1); // br_if exit
21679                          // dst addr = data + idx*8
21680        local_get(code, data);
21681        local_get(code, idx);
21682        i32_const(code, 8);
21683        code.push(0x6C);
21684        code.push(0x6A);
21685        // src addr = src_data_ptr + (start0_i32 + idx)*8
21686        local_get(code, col);
21687        i32_load(code, 8);
21688        local_get(code, s0);
21689        code.push(0xA7); // start0 as i32
21690        local_get(code, idx);
21691        code.push(0x6A); // start0 + idx
21692        i32_const(code, 8);
21693        code.push(0x6C);
21694        code.push(0x6A);
21695        i64_load(code, 0);
21696        i64_store(code, 0);
21697        // idx++
21698        local_get(code, idx);
21699        i32_const(code, 1);
21700        code.push(0x6A);
21701        local_set(code, idx);
21702        code.push(0x0C);
21703        leb_u32(code, 0); // br loop
21704        code.push(0x0B); // end loop
21705        code.push(0x0B); // end block
21706                         // header: len = cap = count; data_ptr = data
21707        for off in [0u32, 4] {
21708            local_get(code, hdr);
21709            local_get(code, ee);
21710            local_get(code, s0);
21711            code.push(0x7D);
21712            code.push(0xA7);
21713            i32_store(code, off);
21714        }
21715        local_get(code, hdr);
21716        local_get(code, data);
21717        i32_store(code, 8);
21718    }
21719    code.push(0x05); // else (empty)
21720    for off in [0u32, 4, 8] {
21721        local_get(code, hdr);
21722        i32_const(code, 0);
21723        i32_store(code, off);
21724    }
21725    code.push(0x0B); // end if
21726                     // S8's true count: the new list is a further holder of every element handle it copied.
21727    if kind_is_handle(elem) {
21728        emit_retain_children(code, ctx, hdr);
21729    }
21730    if exact_ints {
21731        let clone = (ctx.host_index)(HostFn::ExactClone)
21732            .ok_or(WasmLowerError::Unsupported("exact clone import"))?;
21733        emit_exact_buffer_holds(code, hdr, num_regs + 21, num_regs + 22, clone, true);
21734    }
21735    local_get(code, hdr);
21736    local_set(code, dst as u32);
21737    Ok(())
21738}
21739
21740/// A running `Repeat` loop's frame — one heap block from `IterPrepare` to `IterPop`, linked to the
21741/// frame below it:
21742///
21743/// ```text
21744/// [len @0][cursor @4][prev @8][size @12][payload @16…]
21745/// ```
21746///
21747/// Over a sequence the payload is the SNAPSHOT of its elements (8-byte slots), so a write to the
21748/// sequence inside the loop does not perturb the walk — the tree-walker's `iteration_snapshot`;
21749/// `len`/`cursor` count elements. Over a `Text` the payload is the text's handle (a Text is
21750/// immutable, so it needs no copy) and `len`/`cursor` count bytes. `size` is the block's byte size,
21751/// so whatever frees a frame needs nothing else.
21752const FRAME_LEN: u32 = 0;
21753const FRAME_CURSOR: u32 = 4;
21754const FRAME_PREV: u32 = 8;
21755const FRAME_SIZE: u32 = 12;
21756const FRAME_KIND: u32 = 16; // 0 = scalar/range, 1 = one Text handle, 2 = handle slots
21757const FRAME_PAYLOAD: u32 = 24;
21758
21759/// Whether a function starts `Repeat` loops, and so must unwind them on every way out.
21760fn runs_loops(plan: &Plan) -> bool {
21761    plan.ops
21762        .iter()
21763        .any(|op| matches!(op, Op::IterPrepare { .. }))
21764}
21765
21766/// The local holding the loop frame that was on top when the function was entered (see
21767/// [`encode_locals`]).
21768fn loop_base_local(plan: &Plan) -> u32 {
21769    plan.num_regs + 24
21770}
21771
21772/// Leave the function's loops: pop every frame above the one it was entered with, as the VM
21773/// truncates its iterator stack at a return. Self-contained, each frame goes back to the allocator
21774/// (`__logos_iter_unwind`); linked, the frames are the runtime's and the pointer is simply reset.
21775fn emit_leave_loops(code: &mut Vec<u8>, plan: &Plan, ctx: &Ctx) {
21776    if !runs_loops(plan) {
21777        return;
21778    }
21779    local_get(code, loop_base_local(plan));
21780    match ctx.runtime.and_then(|r| r.index(RuntimeFn::IterUnwind)) {
21781        Some(unwind) => {
21782            code.push(0x10); // call __logos_iter_unwind(base)
21783            leb_u32(code, unwind);
21784        }
21785        None => global_set(code, ctx.iter_global),
21786    }
21787}
21788
21789/// `__logos_iter_unwind(base)`: pop and free loop frames until `base` is on top.
21790fn emit_iter_unwind_helper(env: &RuntimeEnv) -> Vec<u8> {
21791    let mut c = Vec::new();
21792    // locals: 1 = frame, 2 = index, 3 = number of held handles
21793    c.push(0x01);
21794    leb_u32(&mut c, 4);
21795    c.push(I32);
21796    c.push(0x02);
21797    c.push(0x40); // block $done
21798    c.push(0x03);
21799    c.push(0x40); // loop $pop
21800    global_get(&mut c, env.iter_global);
21801    local_tee(&mut c, 1);
21802    local_get(&mut c, 0);
21803    c.push(0x46); // i32.eq — back to the base
21804    local_get(&mut c, 1);
21805    c.push(0x45); // i32.eqz — no frame at all
21806    c.push(0x72); // i32.or
21807    c.push(0x0D);
21808    leb_u32(&mut c, 1); // br_if $done
21809    if env.retain_base.is_some() {
21810        local_get(&mut c, 1);
21811        i32_load(&mut c, FRAME_KIND);
21812        c.push(0x04);
21813        c.push(0x40);
21814        i32_const(&mut c, 1);
21815        local_get(&mut c, 1);
21816        i32_load(&mut c, FRAME_LEN);
21817        local_get(&mut c, 1);
21818        i32_load(&mut c, FRAME_KIND);
21819        i32_const(&mut c, 1);
21820        c.push(0x46);
21821        c.push(0x1B); // a Text snapshot holds one handle; a sequence holds len handles
21822        local_set(&mut c, 3);
21823        i32_const(&mut c, 0);
21824        local_set(&mut c, 2);
21825        c.push(0x02);
21826        c.push(0x40);
21827        c.push(0x03);
21828        c.push(0x40);
21829        local_get(&mut c, 2);
21830        local_get(&mut c, 3);
21831        c.push(0x4F);
21832        c.push(0x0D);
21833        leb_u32(&mut c, 1);
21834        local_get(&mut c, 1);
21835        local_get(&mut c, 2);
21836        i32_const(&mut c, 8);
21837        c.push(0x6C);
21838        c.push(0x6A);
21839        if let Some(drop) = env.exact_drop {
21840            local_set(&mut c, 4);
21841            local_get(&mut c, 1);
21842            i32_load(&mut c, FRAME_KIND);
21843            i32_const(&mut c, 3);
21844            c.extend([0x46, 0x04, 0x40]);
21845            local_get(&mut c, 4);
21846            i64_load(&mut c, FRAME_PAYLOAD);
21847            c.push(0x42);
21848            leb_i64(&mut c, 1);
21849            c.extend([0x83, 0xa7, 0x04, 0x40]);
21850            local_get(&mut c, 4);
21851            i64_load(&mut c, FRAME_PAYLOAD);
21852            c.push(0x10);
21853            leb_u32(&mut c, drop);
21854            c.extend([0x0b, 0x05]);
21855            local_get(&mut c, 4);
21856            i32_load(&mut c, FRAME_PAYLOAD);
21857            c.push(0x10);
21858            leb_u32(&mut c, env.call(RuntimeFn::Release));
21859            c.push(0x0b);
21860        } else {
21861            i32_load(&mut c, FRAME_PAYLOAD);
21862            c.push(0x10);
21863            leb_u32(&mut c, env.call(RuntimeFn::Release));
21864        }
21865        local_get(&mut c, 2);
21866        i32_const(&mut c, 1);
21867        c.push(0x6A);
21868        local_set(&mut c, 2);
21869        c.push(0x0C);
21870        leb_u32(&mut c, 0);
21871        c.push(0x0B);
21872        c.push(0x0B);
21873        c.push(0x0B);
21874    }
21875    local_get(&mut c, 1);
21876    i32_load(&mut c, FRAME_PREV);
21877    global_set(&mut c, env.iter_global);
21878    local_get(&mut c, 1);
21879    local_get(&mut c, 1);
21880    i32_load(&mut c, FRAME_SIZE);
21881    c.push(0x10); // call __logos_free(frame, size)
21882    leb_u32(&mut c, env.call(RuntimeFn::Free));
21883    c.push(0x0C);
21884    leb_u32(&mut c, 0); // br $pop
21885    c.push(0x0B);
21886    c.push(0x0B);
21887    c.push(0x0B); // end function
21888    c
21889}
21890
21891/// A range-only iterator owns two captured i64 bounds, never an array of its elements.
21892fn lower_range_iter_prepare(code: &mut Vec<u8>, ctx: &Ctx, num_regs: u32, start: u16, end: u16) {
21893    let frame = num_regs + 5;
21894    i32_const(code, FRAME_PAYLOAD as i32 + 16);
21895    emit_alloc(code, ctx, frame, AllocClass::Raw);
21896    local_get(code, frame);
21897    local_get(code, start as u32);
21898    i64_store(code, FRAME_PAYLOAD);
21899    local_get(code, frame);
21900    local_get(code, end as u32);
21901    i64_store(code, FRAME_PAYLOAD + 8);
21902    // len is a has-next flag. An empty range never enters its body.
21903    local_get(code, frame);
21904    local_get(code, start as u32);
21905    local_get(code, end as u32);
21906    code.push(0x57); // i64.le_s
21907    i32_store(code, FRAME_LEN);
21908    local_get(code, frame);
21909    i32_const(code, 0);
21910    i32_store(code, FRAME_CURSOR);
21911    local_get(code, frame);
21912    i32_const(code, 0);
21913    i32_store(code, FRAME_KIND);
21914    local_get(code, frame);
21915    i32_const(code, FRAME_PAYLOAD as i32 + 16);
21916    i32_store(code, FRAME_SIZE);
21917    local_get(code, frame);
21918    global_get(code, ctx.iter_global);
21919    i32_store(code, FRAME_PREV);
21920    local_get(code, frame);
21921    global_set(code, ctx.iter_global);
21922}
21923
21924#[allow(clippy::too_many_arguments)]
21925fn lower_range_iter_next(
21926    code: &mut Vec<u8>,
21927    plan: &Plan,
21928    ctx: &Ctx,
21929    blocks: &Blocks,
21930    k: usize,
21931    dst: u16,
21932    exit: usize,
21933    pc: usize,
21934) -> R<()> {
21935    global_get(code, ctx.iter_global);
21936    i32_load(code, FRAME_LEN);
21937    code.push(0x04);
21938    code.push(0x40);
21939    global_get(code, ctx.iter_global);
21940    i64_load(code, FRAME_PAYLOAD);
21941    exact::set_word(code, plan, ctx, dst)?;
21942    // Never increment the last value: MAX..MAX runs once without overflowing.
21943    global_get(code, ctx.iter_global);
21944    i64_load(code, FRAME_PAYLOAD);
21945    global_get(code, ctx.iter_global);
21946    i64_load(code, FRAME_PAYLOAD + 8);
21947    code.push(0x51); // i64.eq
21948    code.push(0x04);
21949    code.push(0x40);
21950    global_get(code, ctx.iter_global);
21951    i32_const(code, 0);
21952    i32_store(code, FRAME_LEN);
21953    code.push(0x05);
21954    global_get(code, ctx.iter_global);
21955    global_get(code, ctx.iter_global);
21956    i64_load(code, FRAME_PAYLOAD);
21957    code.push(0x42);
21958    leb_i64(code, 1);
21959    code.push(0x7C);
21960    i64_store(code, FRAME_PAYLOAD);
21961    code.push(0x0B);
21962    set_next_block(code, plan.num_regs, blocks.block_of(pc + 1));
21963    code.push(0x05);
21964    set_next_block(code, plan.num_regs, blocks.block_of(exit));
21965    code.push(0x0B);
21966    code.push(0x0C);
21967    leb_u32(code, blocks.br_loop(k));
21968    Ok(())
21969}
21970
21971/// `IterPrepare`: open a loop frame over the sequence or Text in `iterable` and make it the top one.
21972fn lower_iter_prepare(
21973    code: &mut Vec<u8>,
21974    kinds: &KindTable,
21975    ctx: &Ctx,
21976    num_regs: u32,
21977    iterable: u16,
21978) -> R<()> {
21979    let exact_ints =
21980        ctx.exact.sequence_ints() && kinds.get(iterable as usize) == Some(Kind::SeqInt);
21981    if exact_ints {
21982        exact::promote_sequence(code, ctx, num_regs, iterable as u32)?;
21983    }
21984    let it = iterable as u32;
21985    let (frame, idx) = (num_regs + 5, num_regs + 6); // i32 scratch
21986    let text = kinds.get(iterable as usize) == Some(Kind::Text);
21987    let handles = empty_collection_class(kinds.get(iterable as usize))
21988        .held_handles()
21989        .0;
21990    if !text
21991        && !kinds
21992            .get(iterable as usize)
21993            .map(Kind::is_seq)
21994            .unwrap_or(false)
21995    {
21996        return Err(WasmLowerError::Unsupported(
21997            "iteration over a value that is neither a sequence nor a Text",
21998        ));
21999    }
22000    if text {
22001        i32_const(code, FRAME_PAYLOAD as i32 + 8);
22002        emit_alloc(code, ctx, frame, AllocClass::Raw);
22003        local_get(code, frame);
22004        local_get(code, it);
22005        i32_store(code, FRAME_PAYLOAD);
22006        emit_true_retain(code, ctx, iterable);
22007    } else {
22008        // frame = alloc(16 + len * 8); copy the elements into its payload
22009        local_get(code, it);
22010        i32_load(code, 0);
22011        i32_const(code, 8);
22012        code.push(0x6C);
22013        i32_const(code, FRAME_PAYLOAD as i32);
22014        code.push(0x6A);
22015        emit_alloc(code, ctx, frame, AllocClass::Raw);
22016        i32_const(code, 0);
22017        local_set(code, idx);
22018        code.push(0x02);
22019        code.push(0x40); // block $exit
22020        code.push(0x03);
22021        code.push(0x40); // loop $loop
22022        local_get(code, idx);
22023        local_get(code, it);
22024        i32_load(code, 0);
22025        code.push(0x4E); // i32.ge_s → i >= len
22026        code.push(0x0D);
22027        leb_u32(code, 1); // br_if $exit
22028        local_get(code, frame);
22029        local_get(code, idx);
22030        i32_const(code, 8);
22031        code.push(0x6C);
22032        code.push(0x6A);
22033        local_get(code, it);
22034        i32_load(code, 8);
22035        local_get(code, idx);
22036        i32_const(code, 8);
22037        code.push(0x6C);
22038        code.push(0x6A);
22039        i64_load(code, 0);
22040        if exact_ints {
22041            exact::clone_sequence_word(code, ctx, num_regs)?;
22042        }
22043        i64_store(code, FRAME_PAYLOAD);
22044        if handles {
22045            emit_true_retain_of(code, ctx, |c| {
22046                local_get(c, frame);
22047                local_get(c, idx);
22048                i32_const(c, 8);
22049                c.push(0x6C);
22050                c.push(0x6A);
22051                i32_load(c, FRAME_PAYLOAD);
22052            });
22053        }
22054        local_get(code, idx);
22055        i32_const(code, 1);
22056        code.push(0x6A);
22057        local_set(code, idx);
22058        code.push(0x0C);
22059        leb_u32(code, 0); // br $loop
22060        code.push(0x0B);
22061        code.push(0x0B);
22062    }
22063    local_get(code, frame);
22064    i32_const(
22065        code,
22066        if text {
22067            1
22068        } else if exact_ints {
22069            3
22070        } else if handles {
22071            2
22072        } else {
22073            0
22074        },
22075    );
22076    i32_store(code, FRAME_KIND);
22077    // frame.len = the iterable's length (elements, or a Text's bytes); cursor = 0
22078    local_get(code, frame);
22079    local_get(code, it);
22080    i32_load(code, 0);
22081    i32_store(code, FRAME_LEN);
22082    local_get(code, frame);
22083    i32_const(code, 0);
22084    i32_store(code, FRAME_CURSOR);
22085    // frame.size = the block's size
22086    local_get(code, frame);
22087    if text {
22088        i32_const(code, FRAME_PAYLOAD as i32 + 8);
22089    } else {
22090        local_get(code, it);
22091        i32_load(code, 0);
22092        i32_const(code, 8);
22093        code.push(0x6C);
22094        i32_const(code, FRAME_PAYLOAD as i32);
22095        code.push(0x6A);
22096    }
22097    i32_store(code, FRAME_SIZE);
22098    // frame.prev = the old top; the new top = frame
22099    local_get(code, frame);
22100    global_get(code, ctx.iter_global);
22101    i32_store(code, FRAME_PREV);
22102    local_get(code, frame);
22103    global_set(code, ctx.iter_global);
22104    Ok(())
22105}
22106
22107/// `IterNext { dst, exit }`: a conditional block terminator. If the top frame's `cursor < len`, bind
22108/// the next item to `dst`, advance, and fall through to the loop body; otherwise branch to `exit`
22109/// (the matching `IterPop`). Over a sequence the item is the snapshot slot, loaded at the loop
22110/// variable's width; over a Text it is a fresh one-character Text of the UTF-8 sequence at the
22111/// cursor, whose length the lead byte gives. Either way it sets the dispatch "next block" local and
22112/// `br`s to `$loop`, like every other branch terminator.
22113#[allow(clippy::too_many_arguments)]
22114fn lower_iter_next(
22115    code: &mut Vec<u8>,
22116    plan: &Plan,
22117    ctx: &Ctx,
22118    blocks: &Blocks,
22119    k: usize,
22120    dst: u16,
22121    exit: usize,
22122    pc: usize,
22123) -> R<()> {
22124    if !ctx.linked
22125        && plan
22126            .iter_iterable
22127            .get(pc)
22128            .copied()
22129            .flatten()
22130            .is_some_and(|r| plan.range_loops.contains_key(&(r as u16)))
22131    {
22132        return lower_range_iter_next(code, plan, ctx, blocks, k, dst, exit, pc);
22133    }
22134    let (kinds, num_regs) = (&plan.kinds, plan.num_regs);
22135    let text = plan
22136        .iter_iterable
22137        .get(pc)
22138        .copied()
22139        .flatten()
22140        .is_some_and(|r| kinds.get(r) == Some(Kind::Text));
22141    let ig = ctx.iter_global;
22142    let pc_local = num_regs;
22143    let fallthrough = blocks.block_of(pc + 1) as u32;
22144    let exit_block = blocks.block_of(exit) as u32;
22145    // cursor < len ?
22146    global_get(code, ig);
22147    i32_load(code, FRAME_CURSOR);
22148    global_get(code, ig);
22149    i32_load(code, FRAME_LEN);
22150    code.push(0x48); // i32.lt_s
22151    code.push(0x04);
22152    code.push(0x40); // if (void)
22153    if text {
22154        let (src, bytes, hdr, buf, i) = (
22155            num_regs + 5,
22156            num_regs + 6,
22157            num_regs + 7,
22158            num_regs + 8,
22159            num_regs + 9,
22160        );
22161        // src = the Text's bytes at the cursor
22162        global_get(code, ig);
22163        i32_load(code, FRAME_PAYLOAD);
22164        i32_load(code, 8);
22165        global_get(code, ig);
22166        i32_load(code, FRAME_CURSOR);
22167        code.push(0x6A);
22168        local_set(code, src);
22169        // bytes = 1 / 2 / 3 / 4 by the lead byte (< 0x80, < 0xE0, < 0xF0, else)
22170        i32_const(code, 1);
22171        i32_const(code, 2);
22172        i32_const(code, 3);
22173        i32_const(code, 4);
22174        local_get(code, src);
22175        i32_load8_u(code, 0);
22176        i32_const(code, 0xF0);
22177        code.push(0x49); // i32.lt_u
22178        code.push(0x1B); // select → b0 < 0xF0 ? 3 : 4
22179        local_get(code, src);
22180        i32_load8_u(code, 0);
22181        i32_const(code, 0xE0);
22182        code.push(0x49);
22183        code.push(0x1B); // select → b0 < 0xE0 ? 2 : …
22184        local_get(code, src);
22185        i32_load8_u(code, 0);
22186        i32_const(code, 0x80);
22187        code.push(0x49);
22188        code.push(0x1B); // select → b0 < 0x80 ? 1 : …
22189        local_set(code, bytes);
22190        // dst = a fresh Text of those bytes
22191        i32_const(code, 16);
22192        emit_alloc(code, ctx, hdr, AllocClass::TextHeader);
22193        local_get(code, bytes);
22194        emit_alloc(code, ctx, buf, AllocClass::Raw);
22195        i32_const(code, 0);
22196        local_set(code, i);
22197        code.push(0x02);
22198        code.push(0x40); // block
22199        code.push(0x03);
22200        code.push(0x40); // loop
22201        local_get(code, i);
22202        local_get(code, bytes);
22203        code.push(0x4E); // i32.ge_s
22204        code.push(0x0D);
22205        leb_u32(code, 1);
22206        local_get(code, buf);
22207        local_get(code, i);
22208        code.push(0x6A);
22209        local_get(code, src);
22210        local_get(code, i);
22211        code.push(0x6A);
22212        i32_load8_u(code, 0);
22213        i32_store8(code, 0);
22214        local_get(code, i);
22215        i32_const(code, 1);
22216        code.push(0x6A);
22217        local_set(code, i);
22218        code.push(0x0C);
22219        leb_u32(code, 0);
22220        code.push(0x0B);
22221        code.push(0x0B);
22222        for off in [0u32, 4] {
22223            local_get(code, hdr);
22224            local_get(code, bytes);
22225            i32_store(code, off);
22226        }
22227        local_get(code, hdr);
22228        local_get(code, buf);
22229        i32_store(code, 8);
22230        local_get(code, hdr);
22231        local_set(code, dst as u32);
22232        // cursor += bytes
22233        global_get(code, ig);
22234        global_get(code, ig);
22235        i32_load(code, FRAME_CURSOR);
22236        local_get(code, bytes);
22237        code.push(0x6A);
22238        i32_store(code, FRAME_CURSOR);
22239    } else {
22240        // The loop variable's kind IS the element kind; load it at its width (`f64`/`i64`, or `i32`
22241        // for a heap handle like Text/Struct/Enum).
22242        let elem_load: fn(&mut Vec<u8>, u32) = match kinds.get(dst as usize).map(Kind::wasm_valtype)
22243        {
22244            Some(F64) => f64_load,
22245            Some(I64) => i64_load,
22246            _ => i32_load,
22247        };
22248        // dst = payload[cursor]
22249        global_get(code, ig);
22250        global_get(code, ig);
22251        i32_load(code, FRAME_CURSOR);
22252        i32_const(code, 8);
22253        code.push(0x6C); // i32.mul
22254        code.push(0x6A); // i32.add → element addr - payload offset
22255        elem_load(code, FRAME_PAYLOAD);
22256        if ctx.exact.sequence_ints()
22257            && plan
22258                .iter_iterable
22259                .get(pc)
22260                .copied()
22261                .flatten()
22262                .is_some_and(|r| kinds.get(r) == Some(Kind::SeqInt))
22263        {
22264            exact::take_sequence_tagged(code, plan, ctx, dst)?;
22265        } else {
22266            exact::set_word(code, plan, ctx, dst)?;
22267        }
22268        // cursor++
22269        global_get(code, ig);
22270        global_get(code, ig);
22271        i32_load(code, FRAME_CURSOR);
22272        i32_const(code, 1);
22273        code.push(0x6A); // i32.add
22274        i32_store(code, FRAME_CURSOR);
22275    }
22276    // next block = fallthrough (the loop body)
22277    set_next_block(code, pc_local, fallthrough as usize);
22278    code.push(0x05); // else
22279                     // exhausted: next block = exit (the IterPop)
22280    set_next_block(code, pc_local, exit_block as usize);
22281    code.push(0x0B); // end if
22282    code.push(0x0C); // br $loop
22283    leb_u32(code, blocks.br_loop(k));
22284    Ok(())
22285}
22286
22287/// Whether an op touches the heap value model's linear memory (so the module needs a memory +
22288/// `__heap_ptr` global). Grows as heap ops are lowered.
22289fn op_uses_heap(op: &Op) -> bool {
22290    matches!(
22291        op,
22292        Op::NewEmptyList { .. }
22293            | Op::NewEmptyListWithCapacity { .. }
22294            | Op::NewEmptyListI32 { .. }
22295            | Op::NewEmptyListFixed { .. }
22296            | Op::Length { .. }
22297            | Op::ListPush { .. }
22298            | Op::ListPop { .. }
22299            | Op::Index { .. }
22300            | Op::IndexUnchecked { .. }
22301            | Op::SetIndex { .. }
22302            | Op::SetIndexUnchecked { .. }
22303            | Op::ListPushField { .. }
22304            // `ExactDiv` allocates a 16-byte Rational value in linear memory.
22305            | Op::ExactDiv { .. }
22306            | Op::NewRange { .. }
22307            | Op::NewList { .. }
22308            | Op::IterPrepare { .. }
22309            | Op::IterNext { .. }
22310            | Op::IterPop
22311            | Op::Contains { .. }
22312            | Op::SliceOp { .. }
22313            | Op::SeqConcat { .. }
22314            | Op::Concat { .. }
22315            | Op::FormatValue { .. }
22316            | Op::DeepClone { .. }
22317            | Op::NewStruct { .. }
22318            | Op::StructInsert { .. }
22319            | Op::GetField { .. }
22320            | Op::CheckPolicy { .. }
22321            | Op::CrdtBump { .. }
22322            | Op::CrdtMerge { .. }
22323            | Op::CrdtJoin { .. }
22324            | Op::NewCrdt { .. }
22325            | Op::CrdtResolve { .. }
22326            | Op::CrdtAppend { .. }
22327            | Op::ChanNew { .. }
22328            | Op::ChanSend { .. }
22329            | Op::ChanRecv { .. }
22330            // `Try to send` appends to (reallocs) the FIFO; `Try to receive` allocs an Optional box.
22331            | Op::ChanTrySend { .. }
22332            | Op::ChanTryRecv { .. }
22333            // A `select` recv arm pops from a channel's FIFO queue in linear memory.
22334            | Op::SelectWait { .. }
22335            // Offline networking models the inbox as a local FIFO in linear memory.
22336            | Op::NetListen { .. }
22337            | Op::NetSend { .. }
22338            | Op::NetStream { .. }
22339            | Op::NetAwait { .. }
22340            | Op::NewEmptyMap { .. }
22341            | Op::NewEmptyMapWithCapacity { .. }
22342            | Op::NewEmptySet { .. }
22343            | Op::SetAdd { .. }
22344            | Op::RemoveFrom { .. }
22345            | Op::UnionOp { .. }
22346            | Op::IntersectOp { .. }
22347            | Op::NewInductive { .. }
22348            | Op::BindArm { .. }
22349            | Op::NewTuple { .. }
22350            | Op::DestructureTuple { .. }
22351            | Op::MakeClosure { .. }
22352            | Op::CallValue { .. }
22353            // `args()` returns a `Seq of Text` HANDLE the host builds in this module's linear memory,
22354            // so the module must export a memory for the host to write into.
22355            | Op::Args { .. }
22356            // `chr(code)` builds a one-character Text object in linear memory.
22357            | Op::CallBuiltin { builtin: BuiltinId::Chr, .. }
22358            // `get`'s text half allocates the buffer its host writes into, and the Text header over it.
22359            | Op::CallBuiltin { builtin: BuiltinId::EnvValue, .. }
22360            // `repeatSeq(x, n)` bump-allocates a fresh `n`-element sequence.
22361            | Op::CallBuiltin { builtin: BuiltinId::RepeatSeq, .. }
22362            // Byte interop allocates a fresh seq / Text / 16-byte block in linear memory.
22363            | Op::CallBuiltin { builtin: BuiltinId::TextBytes, .. }
22364            | Op::CallBuiltin { builtin: BuiltinId::UuidBytes, .. }
22365            | Op::CallBuiltin { builtin: BuiltinId::TextFromBytes, .. }
22366            | Op::CallBuiltin { builtin: BuiltinId::UuidFromBytes, .. }
22367            | Op::CallBuiltin { builtin: BuiltinId::Lanes4Of, .. }
22368            | Op::CallBuiltin { builtin: BuiltinId::Lanes4Word32Make, .. }
22369            | Op::CallBuiltin { builtin: BuiltinId::SeqOfLanes4W32, .. }
22370            // `readWireProgram` bump-allocates a receive buffer (via `emit_alloc`), so it needs the runtime
22371            // allocator (`logos_rt_alloc`) imported — else `emit_alloc` falls to the `__heap_ptr` global,
22372            // undeclared in a linked module (an invalid global relocation in the emitted object).
22373            | Op::CallBuiltin { builtin: BuiltinId::ReadWireProgram, .. }
22374    )
22375}
22376
22377/// The local-declaration prefix of a Code entry: registers `num_params..num_regs` typed by
22378/// their inferred kind (coalesced into same-type groups), the i32 dispatch local, four i64
22379/// scratch locals (integer `pow`), and one i32 heap-allocation scratch.
22380fn encode_locals(plan: &Plan, root_count: usize) -> Vec<u8> {
22381    let mut groups: Vec<(u32, u8)> = Vec::new();
22382    let push = |vt: u8, groups: &mut Vec<(u32, u8)>| match groups.last_mut() {
22383        Some((count, t)) if *t == vt => *count += 1,
22384        _ => groups.push((1, vt)),
22385    };
22386    for r in plan.num_params..plan.num_regs {
22387        push(plan.kinds.valtype(r as usize), &mut groups);
22388    }
22389    push(I32, &mut groups); // the dispatch "next block" local at index num_regs
22390                            // Four i64 scratch locals (num_regs+1..=num_regs+4) for integer `pow`'s squaring loop
22391                            // (result, base, exponent, and a product temp distinct from them all).
22392    push(I64, &mut groups);
22393    push(I64, &mut groups);
22394    push(I64, &mut groups);
22395    push(I64, &mut groups);
22396    // Seven i32 heap scratch locals (num_regs+5..+11): header/alloc temps and a fill index
22397    // (+5/+6/+7), two operand-handle holders for `Concat`'s stringify-then-byte-copy (+8/+9), a
22398    // Text-keyed-Map per-entry key compare's +8/+9/+10, and a Text append's capacity and new length
22399    // (+10/+11) — so seven cover the deepest user.
22400    push(I32, &mut groups);
22401    push(I32, &mut groups);
22402    push(I32, &mut groups);
22403    push(I32, &mut groups);
22404    push(I32, &mut groups);
22405    push(I32, &mut groups);
22406    push(I32, &mut groups);
22407    // One f64 scratch local (num_regs+12): a Float tuple element loaded from its 8-byte slot needs an
22408    // `f64` holder before `emit_stringify` (the i64/i32 scratch above cannot type it). `Show`-tuple only.
22409    push(F64, &mut groups);
22410    // Two more i32 scratch (num_regs+13/+14): the whole `Seq of Enum` `Show` NESTS an enum display
22411    // inside the outer sequence loop, so the per-element assembly needs locals distinct from the
22412    // outer accumulator/counter/handle (+8/+10/+11) — a separator/piece temp and a field-i32 temp.
22413    push(I32, &mut groups);
22414    push(I32, &mut groups);
22415    // ── CRDT COUNTER scratch — the per-replica `ConvergentCount`/`Tally` object ops (project the
22416    //    Int total, bump this replica's slot, per-replica MAX merge). The merge NESTS an inner search
22417    //    over the target's records inside the outer scan over the source's records, so it needs locals
22418    //    disjoint from every op above. Two i64 (num_regs+15/+16): the running total / the max operands
22419    //    and record ids. Six i32 (num_regs+17..=+22): outer index, inner index, target data_ptr, source
22420    //    data_ptr, a matched-slot cursor, and a found flag — the deepest user is the merge.
22421    push(I64, &mut groups); // +15
22422    push(I64, &mut groups); // +16
22423    push(I32, &mut groups); // +17
22424    push(I32, &mut groups); // +18
22425    push(I32, &mut groups); // +19
22426    push(I32, &mut groups); // +20
22427    push(I32, &mut groups); // +21
22428    push(I32, &mut groups); // +22
22429                            // A Map/Set insert's growth doubling (num_regs+23): the new capacity, held across the alloc
22430                            // and copy that grow its buffer. Dedicated rather than sharing +5..+11 because `a union b` /
22431                            // `a intersection b` build their result through `emit_set_add_elem` with `s` ITSELF aliasing
22432                            // +8 and the outer scan counter live in +9 across the call — either would corrupt the set
22433                            // being built rather than merely a scratch value.
22434    push(I32, &mut groups); // +23
22435                            // The `Repeat` frame on top when the function was entered (`loop_base_local`), which every
22436                            // return unwinds back to.
22437    push(I32, &mut groups); // +24
22438                            // A module carrying tagged words: two operands and a result, then one saved word per exact register
22439                            // ([`exact`]).
22440    for _ in 0..exact::extra_locals(plan) {
22441        push(I64, &mut groups);
22442    }
22443    for _ in 0..absence::extra_locals(plan) {
22444        push(I32, &mut groups);
22445    }
22446    for _ in 0..tower::extra_locals(plan) {
22447        push(I32, &mut groups);
22448    }
22449    for _ in 0..root_count {
22450        push(I32, &mut groups);
22451    } // owning shadow roots, initially null
22452
22453    let mut out = Vec::new();
22454    leb_u32(&mut out, groups.len() as u32);
22455    for (count, vt) in groups {
22456        leb_u32(&mut out, count);
22457        out.push(vt);
22458    }
22459    out
22460}
22461
22462/// Encode a UTF-8 name as a wasm name (length-prefixed bytes).
22463fn encode_name(out: &mut Vec<u8>, name: &str) {
22464    leb_u32(out, name.len() as u32);
22465    out.extend_from_slice(name.as_bytes());
22466}
22467
22468/// A short, stable name for an op the scalar backend does not lower — what the corpus lock
22469/// reports as the remaining gap.
22470fn unsupported_op(op: &Op) -> WasmLowerError {
22471    let what = match op {
22472        Op::ExactDiv { .. } => "exact division (Rational)",
22473        Op::DivPow2 { .. } | Op::MagicDivU { .. } => "oracle division op",
22474        Op::Concat { .. } => "text op",
22475        Op::IndexUnchecked { .. } => "unchecked index (IndexUnchecked)",
22476        Op::CallValue { .. } | Op::MakeClosure { .. } => "closure call",
22477        _ => "op",
22478    };
22479    WasmLowerError::Unsupported(what)
22480}
22481
22482#[cfg(test)]
22483#[path = "../../../../logicaffeine_tests/unit/logicaffeine_compile/vm/wasm/module/alloc_class_tests.rs"]
22484mod alloc_class_tests;
22485
22486#[cfg(test)]
22487#[path = "../../../../logicaffeine_tests/unit/logicaffeine_compile/vm/wasm/module/transient_reads_tests.rs"]
22488mod transient_reads_tests;
22489
22490#[cfg(test)]
22491#[path = "../../../../logicaffeine_tests/unit/logicaffeine_compile/vm/wasm/module/range_storage_tests.rs"]
22492mod range_storage_tests;