Skip to main content

logicaffeine_compile/semantics/
builtins.rs

1//! Built-in functions over already-evaluated values.
2//!
3//! `show` is NOT here — output is an engine concern. Arity is checked by the
4//! caller BEFORE evaluating arguments (via [`check_arity`]) to preserve the
5//! tree-walker's error ordering: a wrong-arity call reports the arity error
6//! even when an argument expression would itself error.
7
8use std::cell::RefCell;
9use std::rc::Rc;
10
11use serde::{Deserialize, Serialize};
12
13use crate::interpreter::{InductiveValue, ListRepr, RuntimeValue};
14use logicaffeine_base::{Decimal, LanesVal, Word16, Word32, Word64, Word8, WordVal};
15
16/// A stdlib `Result` (core.lg: `Ok (value)` / `Err (error)`) as the executing
17/// tiers represent it — the shape `Inspect`'s `When Ok (…)`/`When Err (…)` arms
18/// match. The return seam for natives declared `-> Result …`.
19pub(crate) fn result_ok(v: RuntimeValue) -> RuntimeValue {
20    RuntimeValue::Inductive(std::rc::Rc::new(InductiveValue {
21        inductive_type: "Result".to_string(),
22        constructor: "Ok".to_string(),
23        args: vec![v],
24    }))
25}
26
27pub(crate) fn result_err(msg: String) -> RuntimeValue {
28    RuntimeValue::Inductive(std::rc::Rc::new(InductiveValue {
29        inductive_type: "Result".to_string(),
30        constructor: "Err".to_string(),
31        args: vec![RuntimeValue::Text(Rc::new(msg))],
32    }))
33}
34
35/// The standard library's system natives that run through [`call_builtin`] — file.lg's `read` and
36/// `write`, random.lg's `randomInt` and `randomFloat`, env.lg's `get`, time.lg's `now` — by name and
37/// arity. The one table the tree-walker and the VM compiler both consult, so a native cannot be wired
38/// on one tier and fall through to its empty body on the other. A caller asks it only for a
39/// `## To native` declaration: a program's own function of the same name always wins.
40pub fn system_native(name: &str, argc: usize) -> Option<BuiltinId> {
41    match (name, argc) {
42        ("read", 1) => Some(BuiltinId::FileRead),
43        ("write", 2) => Some(BuiltinId::FileWrite),
44        ("randomInt", 2) => Some(BuiltinId::RandomInt),
45        ("randomFloat", 0) => Some(BuiltinId::RandomFloat),
46        ("get", 1) => Some(BuiltinId::EnvGet),
47        ("now", 0) => Some(BuiltinId::TimeNow),
48        _ => None,
49    }
50}
51
52/// The natives the Rust backends link from `logicaffeine_system` and no other engine runs, as
53/// `(module, function)`: the FIPS-202 hashes, which a program declares native to take the Rust
54/// implementation in place of crypto.lg's pure-LOGOS sponge. The Rust backends' table reads this, and
55/// every other engine refuses a call to one by the Rust function it names.
56pub fn rust_only_native(name: &str) -> Option<(&'static str, &'static str)> {
57    match name {
58        "sha3_256" => Some(("keccak", "sha3_256")),
59        "sha3_512" => Some(("keccak", "sha3_512")),
60        "shake128" => Some(("keccak", "shake128")),
61        "shake256" => Some(("keccak", "shake256")),
62        _ => None,
63    }
64}
65
66/// What a call to a `## To native` declaration no engine implements is refused with, on every tier.
67/// A declaration naming a Rust path (`is native "crate::module::function"`), or a native only the
68/// Rust backends link ([`rust_only_native`]), runs only where Rust links it, as `Escape to Rust:`
69/// does; one naming no path and no system native is the Rust backends' own compile-time refusal, in
70/// their words.
71pub fn unimplemented_native(name: &str, rust_path: Option<&str>) -> String {
72    let linked = rust_only_native(name)
73        .map(|(module, function)| format!("logicaffeine_system::{module}::{function}"));
74    match rust_path.map(str::to_string).or(linked) {
75        Some(path) => format!(
76            "`{name}` is the Rust function `{path}`, which only the Rust backends compile. \
77             Use `largo build` or `largo run` to compile and run this program."
78        ),
79        None => format!(
80            "Unknown system native function: '{name}'. Use `is native \"crate::path\"` syntax for \
81             user-defined native functions."
82        ),
83    }
84}
85
86/// The variable `key` names in the environment the program runs in, or `None` when it is unset:
87/// the process environment through the system seam, which a sealed test world answers instead. A
88/// browser has no process environment, so there only a sealed world can name a variable.
89fn environment_variable(key: &str) -> Option<String> {
90    #[cfg(not(target_arch = "wasm32"))]
91    {
92        logicaffeine_system::env::get(key.to_string())
93    }
94    #[cfg(target_arch = "wasm32")]
95    {
96        logicaffeine_system::testworld::intercept_env_get(key).flatten()
97    }
98}
99
100/// Read a `Seq of Int` as raw bytes (each element masked to 0–255) — the byte-array convention the
101/// UUID/hash builtins share with `uuid.lg` so the version constructors can be written in LOGOS.
102/// Why a file statement's read of the sandboxed file system fails, as every tier reports it.
103pub fn vfs_read_failure(e: &logicaffeine_system::fs::VfsError) -> String {
104    format!("Read error: {e}")
105}
106
107/// Why a file statement's write to the sandboxed file system fails, as every tier reports it.
108pub fn vfs_write_failure(e: &logicaffeine_system::fs::VfsError) -> String {
109    format!("Write error: {e}")
110}
111
112/// The answer of one operation on the sandboxed in-memory file system. `MemVfs` never awaits anything, so
113/// its future is complete on its first poll; polling it once keeps a builtin callable from inside an async
114/// runner, where blocking on a nested executor would panic.
115fn sandboxed<T>(op: impl std::future::Future<Output = T>) -> Result<T, String> {
116    use futures::FutureExt as _;
117    Box::pin(op)
118        .now_or_never()
119        .ok_or_else(|| "the sandboxed file system did not answer at once".to_string())
120}
121
122pub(crate) fn byte_seq(v: &RuntimeValue) -> Result<Vec<u8>, String> {
123    match v {
124        RuntimeValue::List(l) => {
125            let l = l.borrow();
126            let mut out = Vec::with_capacity(l.len());
127            for i in 0..l.len() {
128                match l.get(i) {
129                    Some(RuntimeValue::Int(n)) => out.push((n & 0xff) as u8),
130                    _ => {
131                        return Err(format!(
132                            "expected a Seq of Int (bytes); element {} is not an Int",
133                            i + 1
134                        ))
135                    }
136                }
137            }
138            Ok(out)
139        }
140        _ => Err(format!(
141            "expected a Seq of Int (bytes), got {}",
142            v.type_name()
143        )),
144    }
145}
146
147/// A `Seq of Int` argument of `function` as bytes, refused as `crypto.lg`'s `cryptoRequireBytes` refuses
148/// it: an item outside 0..=255 is named, never folded into a byte.
149pub(crate) fn exact_byte_seq(function: &str, what: &str, v: &RuntimeValue) -> Result<Vec<u8>, String> {
150    let RuntimeValue::List(l) = v else {
151        return Err(format!(
152            "{function}(): the {what} must be a Seq of Int (bytes), got {}",
153            v.type_name()
154        ));
155    };
156    let l = l.borrow();
157    let mut out = Vec::with_capacity(l.len());
158    for i in 0..l.len() {
159        match l.get(i) {
160            Some(RuntimeValue::Int(n)) => match u8::try_from(n) {
161                Ok(b) => out.push(b),
162                Err(_) => {
163                    return Err(format!(
164                        "{function}(): the {what} must be bytes (0 to 255); item {} is {n}",
165                        i + 1
166                    ))
167                }
168            },
169            _ => {
170                return Err(format!(
171                    "{function}(): the {what} must be a Seq of Int (bytes); item {} is not an Int",
172                    i + 1
173                ))
174            }
175        }
176    }
177    Ok(out)
178}
179
180/// `pbkdf2Sha256`'s arguments as the pure `crypto.lg` body takes them, in its order and with its
181/// reports, for the tiers that run it on [`crate::crypto_accel::pbkdf2_sha256`]: a byte password, a byte
182/// salt, and an iteration count from 1 to 2^32 − 1 (RFC 8018 §5.2 runs a positive count).
183pub(crate) fn pbkdf2_arguments(
184    password: &RuntimeValue,
185    salt: &RuntimeValue,
186    iters: &RuntimeValue,
187) -> Result<(Vec<u8>, Vec<u8>, u32), String> {
188    let password = exact_byte_seq("pbkdf2Sha256", "password", password)?;
189    let salt = exact_byte_seq("pbkdf2Sha256", "salt", salt)?;
190    let iters = match iters {
191        RuntimeValue::Int(n) => u32::try_from(*n).ok().filter(|&c| c >= 1).ok_or_else(|| {
192            format!("pbkdf2Sha256(): the iteration count must be from 1 to 4294967295; it is {n}")
193        })?,
194        other => {
195            return Err(format!(
196                "pbkdf2Sha256(): the iteration count must be an Int, got {}",
197                other.type_name()
198            ))
199        }
200    };
201    Ok((password, salt, iters))
202}
203
204/// Read `fetchSend`'s headers argument: a `Seq of Text` alternating name,value —
205/// the flat shape that crosses the wasm ABI as one seq handle (a `Map` has no
206/// host-side layout there). An odd element count is a hard error at the seam.
207fn fetch_header_pairs(v: &RuntimeValue) -> Result<Vec<(String, String)>, String> {
208    let RuntimeValue::List(l) = v else {
209        return Err(format!(
210            "fetchSend headers must be a Seq of Text alternating name,value, got {}",
211            v.type_name()
212        ));
213    };
214    let l = l.borrow();
215    if l.len() % 2 != 0 {
216        return Err(format!(
217            "fetchSend headers must alternate name,value ({} elements is odd)",
218            l.len()
219        ));
220    }
221    let mut out = Vec::with_capacity(l.len() / 2);
222    for i in (0..l.len()).step_by(2) {
223        let name = l.get(i).map(|x| x.to_display_string()).unwrap_or_default();
224        let value = l
225            .get(i + 1)
226            .map(|x| x.to_display_string())
227            .unwrap_or_default();
228        out.push((name, value));
229    }
230    Ok(out)
231}
232
233/// `randomInt(lo, hi)` — a uniform draw from `lo..=hi` through the one system seam (a sealed test
234/// world decides it), or the refusal of a range whose low bound is above its high bound, which
235/// every host words alike.
236pub fn random_int(lo: i64, hi: i64) -> Result<i64, String> {
237    if lo > hi {
238        return Err(format!(
239            "randomInt({lo}, {hi}): the low bound is above the high bound"
240        ));
241    }
242    Ok(logicaffeine_system::random::randomInt(lo, hi))
243}
244
245/// A turn's changed fields from `noteTurn`'s flattened `[field, before, after, …]` Seq of Text, as
246/// the journal's `(field, before, after)` triples.
247fn journal_changes(v: &RuntimeValue) -> Result<Vec<(String, String, String)>, String> {
248    let RuntimeValue::List(l) = v else {
249        return Err(format!(
250            "noteTurn changes must be a Seq of Text [field, before, after, …], got {}",
251            v.type_name()
252        ));
253    };
254    let l = l.borrow();
255    if l.len() % 3 != 0 {
256        return Err(format!(
257            "noteTurn changes come in [field, before, after] triples ({} elements is not one)",
258            l.len()
259        ));
260    }
261    let text = |i: usize| l.get(i).map(|x| x.to_display_string()).unwrap_or_default();
262    Ok((0..l.len())
263        .step_by(3)
264        .map(|i| (text(i), text(i + 1), text(i + 2)))
265        .collect())
266}
267
268/// A 32-byte ChaCha20-Poly1305 key from a `Seq of Int`; an item that is not a byte or a wrong length is
269/// a hard error at the seam (a key is never masked, padded or truncated into a weaker one).
270fn read_aead_key(v: &RuntimeValue, who: &str) -> Result<[u8; 32], String> {
271    let bytes = exact_byte_seq(who, "key", v)?;
272    bytes
273        .as_slice()
274        .try_into()
275        .map_err(|_| format!("{who}(): key must be exactly 32 bytes, got {}", bytes.len()))
276}
277
278/// A box from a `Seq of Int`: bytes, and at least its nonce and tag long.
279fn read_box(v: &RuntimeValue, who: &str) -> Result<Vec<u8>, String> {
280    let sealed = exact_byte_seq(who, "box", v)?;
281    if sealed.len() < logicaffeine_system::aead::BOX_OVERHEAD {
282        return Err(format!(
283            "{who}(): the box is {} bytes; a box is at least {}",
284            sealed.len(),
285            logicaffeine_system::aead::BOX_OVERHEAD
286        ));
287    }
288    Ok(sealed)
289}
290
291/// What opening a box that does not authenticate stops with.
292fn box_refused(who: &str) -> String {
293    format!("{who}(): authentication failed — the box was tampered, truncated, or the key is wrong")
294}
295
296/// A 12-byte ChaCha20-Poly1305 nonce from a `Seq of Int`; an item that is not a byte or a wrong length
297/// is a hard error.
298fn read_aead_nonce(v: &RuntimeValue, who: &str) -> Result<[u8; 12], String> {
299    let bytes = exact_byte_seq(who, "nonce", v)?;
300    bytes.as_slice().try_into().map_err(|_| {
301        format!(
302            "{who}(): nonce must be exactly 12 bytes, got {}",
303            bytes.len()
304        )
305    })
306}
307
308/// Build a `Seq of Int` from raw bytes (the packed-`i64` list repr).
309pub(crate) fn bytes_to_seq(bytes: &[u8]) -> RuntimeValue {
310    RuntimeValue::List(Rc::new(RefCell::new(ListRepr::Ints(
311        bytes.iter().map(|&b| b as i64).collect(),
312    ))))
313}
314
315/// Read a `Seq of Seq of Int` as FEC shards — each inner `Seq of Int` decoded as bytes via
316/// [`byte_seq`]. Equal-length shards are enforced downstream by the codec.
317fn read_shards(v: &RuntimeValue) -> Result<Vec<Vec<u8>>, String> {
318    match v {
319        RuntimeValue::List(l) => {
320            let l = l.borrow();
321            let mut shards = Vec::with_capacity(l.len());
322            for i in 0..l.len() {
323                match l.get(i) {
324                    Some(elem) => shards.push(byte_seq(&elem)?),
325                    None => return Err(format!("shard {} is missing", i + 1)),
326                }
327            }
328            Ok(shards)
329        }
330        _ => Err(format!(
331            "expected a Seq of Seq of Int (shards), got {}",
332            v.type_name()
333        )),
334    }
335}
336
337/// Read a `Seq` of (`Seq of Int` | `nothing`) as received FEC shards — `nothing` marks an
338/// erased (lost) slot; any other element is a surviving shard decoded via [`byte_seq`].
339fn read_received(v: &RuntimeValue) -> Result<Vec<Option<Vec<u8>>>, String> {
340    match v {
341        RuntimeValue::List(l) => {
342            let l = l.borrow();
343            let mut out = Vec::with_capacity(l.len());
344            for i in 0..l.len() {
345                match l.get(i) {
346                    Some(RuntimeValue::Nothing) => out.push(None),
347                    Some(elem) => out.push(Some(byte_seq(&elem)?)),
348                    None => return Err(format!("received slot {} is missing", i + 1)),
349                }
350            }
351            Ok(out)
352        }
353        _ => Err(format!(
354            "expected a Seq of (Seq of Int or nothing), got {}",
355            v.type_name()
356        )),
357    }
358}
359
360/// Build a `Seq of Seq of Int` from FEC shards — the inverse of [`read_shards`].
361fn shards_to_seq(shards: &[Vec<u8>]) -> RuntimeValue {
362    let rows: Vec<RuntimeValue> = shards.iter().map(|s| bytes_to_seq(s)).collect();
363    RuntimeValue::List(Rc::new(RefCell::new(ListRepr::from_values(rows))))
364}
365
366/// Read a positive `Int` shard/parity count, with a labelled error on a non-positive or non-Int.
367fn read_positive_count(v: RuntimeValue, label: &str) -> Result<usize, String> {
368    match v {
369        RuntimeValue::Int(n) if n > 0 => Ok(n as usize),
370        RuntimeValue::Int(n) => Err(format!("{label} must be positive, got {n}")),
371        other => Err(format!("{label} must be an Int, got {}", other.type_name())),
372    }
373}
374
375#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
376pub enum BuiltinId {
377    Length,
378    /// `contains(haystack, needle)` — true iff `needle` is a substring of
379    /// `haystack` (both `Text`). The empty needle is contained in everything.
380    Contains,
381    Format,
382    ParseInt,
383    ParseFloat,
384    Chr,
385    Abs,
386    Sqrt,
387    Min,
388    Max,
389    Floor,
390    Ceil,
391    Round,
392    Pow,
393    /// `decimal(text)` / `decimal(int)` — construct an exact base-10 fixed-point (money)
394    /// from its literal text (`decimal("19.99")`) or an integer. The non-breaking entry
395    /// into the `Decimal` tower (it does NOT change how `19.99` literals parse).
396    Decimal,
397    /// `complex(re, im)` — an exact complex from two exact reals, or a floating-point complex (`ComplexF`) if either part is a `Float`.
398    /// `complex(0, 1)` is the imaginary unit `i`; `complex(0,1) * complex(0,1) = −1`.
399    Complex,
400    /// `conjugate(z)` — the complex conjugate `re − im·i` (exact `Complex` stays exact, `ComplexF`
401    /// stays float; a real number is its own conjugate). The primitive for Hermitian transpose and
402    /// the conjugated dot product `xᴴy` in complex BLAS/LAPACK.
403    Conjugate,
404    /// `re(z)` — the real part of a complex number as a `Float` (a real number → itself as a Float).
405    RealPart,
406    /// `im(z)` — the imaginary part of a complex number as a `Float` (a real number → 0.0).
407    ImagPart,
408    /// `modular(value, modulus)` — construct an element of ℤ/nℤ (the value reduced mod n).
409    Modular,
410    /// `quantity(value, "unit")` — construct a dimensioned physical quantity (`quantity(2, "inch")`).
411    /// The magnitude rides the exact rational tower; the unit name resolves through the catalog.
412    Quantity,
413    /// `money(amount, "USD")` — construct an exact monetary amount, quantised to the currency's
414    /// minor unit. The amount rides the Decimal tower (never float-drifts); the code resolves through
415    /// the ISO-4217 catalog.
416    Money,
417    /// `set_rate("EUR", 1.10)` — install/replace one exchange rate (vs the reference) in the ambient
418    /// rate context that `<money> in <currency>` reads. A side effect; returns nothing.
419    SetRate,
420    /// `to_currency(money, "EUR")` — convert money to another currency via the ambient rate context
421    /// (exact). Errors if no rates are in scope or the currency is unknown. Surface: `<money> in EUR`.
422    ToCurrency,
423    /// `set_rates(map)` — bulk-install a whole exchange-rate table from a `Map of Text to <number>`
424    /// (code → rate vs the reference) into the ambient rate context. The bridge a literal,
425    /// network-synced, or fetched rate table feeds. A side effect; returns nothing.
426    SetRates,
427    /// `uuid("550e8400-…")` — parse a UUID from text (canonical/simple/braced/urn); error on a bad id.
428    Uuid,
429    /// `uuid_nil()` / `uuid_max()` — the two special ids.
430    UuidNil,
431    UuidMax,
432    /// `uuid_version(u)` — the version nibble (0 nil, 1–8, 15 max).
433    UuidVersion,
434    /// The well-known namespace ids: `uuid_dns()`, `uuid_url()`, `uuid_oid()`, `uuid_x500()`.
435    UuidDns,
436    UuidUrl,
437    UuidOid,
438    UuidX500,
439    /// Byte-level primitives that let the UUID version constructors be written IN LOGOS (uuid.lg):
440    /// `text_bytes` is a Text's UTF-8 bytes; `uuid_bytes`/`uuid_from_bytes` convert a Uuid to/from its
441    /// 16 bytes. (`md5`/`sha1`/`uuid_v3`/`uuid_v5` are Logos stdlib functions now, not builtins.)
442    TextBytes,
443    /// `text_from_bytes(seq)` — the exact inverse of `text_bytes`: rebuild a Text from its UTF-8
444    /// `Seq of Int`. The wire medium for the Core-IR codec (`Seq of Int`) carries Text this way.
445    TextFromBytes,
446    /// `wireBytes(value)` — the value's plain wire form (peer codec `encode_value_raw`) as a
447    /// `Seq of Int`. Lets the host serialize a program AST for a compile-once native PE, byte-
448    /// identical to what the native binary's generated `wire_decode` reads.
449    WireBytes,
450    /// `compressBytes(seq)` — squeeze a `Seq of Int` byte payload with the SMALLEST of the codec's
451    /// built-in compressors (deflate/lz4/zstd, self-describing tag byte); stores raw when nothing
452    /// shrinks it, so it never grows by more than one byte. The streaming knob for redundant state
453    /// (CRDT deltas, rosters, keypoints) — run it BEFORE `encrypt`, since ciphertext is incompressible,
454    /// and never on a payload that carries a secret beside anything an attacker chooses: the compressed
455    /// length then gives the secret away a guess at a time (CRIME, BREACH).
456    CompressBytes,
457    /// `decompressBytes(seq)` — the exact inverse of `compressBytes`: read the codec tag and inflate
458    /// (with the decompression-bomb bound). Errors on a malformed frame.
459    DecompressBytes,
460    /// `sealBytes(key, nonce, plaintext)` — the secure streaming frame: ChaCha20-Poly1305
461    /// authenticated-encrypt the plaintext (32-byte key, 12-byte nonce, both `Seq of Int`), which is never
462    /// compressed first — a frame's length tells nothing of its plaintext but its length. The 16-byte
463    /// Poly1305 tag makes the frame tamper-evident. The caller keeps every nonce under a key distinct;
464    /// `sealBox` draws one instead. Inverse: `openBytes`.
465    SealBytes,
466    /// `openBytes(key, nonce, sealed)` — verify the Poly1305 tag (constant-time) and decrypt, returning
467    /// the plaintext. ERRORS on a wrong key, a tampered frame, or truncation — it never yields
468    /// unauthenticated bytes.
469    OpenBytes,
470    /// `fromWireBytes(seq)` — the inverse of `wireBytes`: decode a self-describing wire byte `Seq of
471    /// Int` back into the value it encoded (Int/Text/Bool/Seq/Set/Map/Struct/Tuple/…, no schema
472    /// needed). Errors on a malformed or trailing-byte frame. Completes the round trip a receiver needs.
473    FromWireBytes,
474    /// `sealFrame(key, nonce, value)` — the one-call secure streaming frame for a VALUE: wire-encode,
475    /// then ChaCha20-Poly1305 authenticated-encrypt. `openFrame` reverses it straight back to the value.
476    /// Fuses `wireBytes`+`sealBytes` with no intermediate Seq; `sealValueBox` draws its nonce instead.
477    SealFrame,
478    /// `openFrame(key, nonce, sealed)` — verify, decrypt, and wire-decode a `sealFrame` back into the
479    /// original value. Errors on tamper / wrong key / malformed frame.
480    OpenFrame,
481    /// `readWireProgram()` — read ONE length-framed `CProgram` from stdin (`u32` LE length, then
482    /// that many wire bytes, decoded via the generated `wire_decode`) and return it; on EOF the
483    /// process exits cleanly (the resident-server loop terminator). AOT-only (returns the generated
484    /// `CProgram`); the interpreter variant rebuilds a `RuntimeValue` for parity.
485    ReadWireProgram,
486    /// `writeWireResidual(text)` — write `text` back as a length-framed residual (`u32` LE length,
487    /// then the UTF-8 bytes) to stdout and flush, returning the byte count. The response half of the
488    /// resident PE server's request/response protocol.
489    WriteWireResidual,
490    UuidBytes,
491    UuidFromBytes,
492    /// `convert(quantity, "unit")` — re-express a quantity in another unit of the SAME dimension
493    /// (`convert(q, "foot")`); a different dimension is a clean error (the forbidden cast).
494    Convert,
495    /// `parse_timestamp("2024-03-10T07:30:00Z")` — parse an RFC 3339 / ISO 8601 timestamp into a
496    /// `Moment` (nanoseconds since the epoch). The wire-first "the timestamp is its own type" entry.
497    ParseTimestamp,
498    /// `format_timestamp(moment)` — render a `Moment` as an RFC 3339 / ISO 8601 UTC string.
499    FormatTimestamp,
500    /// Calendar component extractors on a `Moment` (UTC), each returning an `Int`:
501    /// `year_of` / `month_of` (1–12) / `day_of` (1–31) / `weekday_of` (ISO 8601: 1 = Monday … 7 = Sunday).
502    YearOf,
503    MonthOf,
504    DayOf,
505    WeekdayOf,
506    HourOf,
507    MinuteOf,
508    SecondOf,
509    /// `week_of(moment)` — the ISO-8601 week number (1..=53) of the Moment/Date (UTC).
510    WeekOf,
511    /// `quarter_of(moment)` — the calendar quarter (1..=4) of the Moment/Date (UTC).
512    QuarterOf,
513    /// `date_of(moment)` — the calendar day (a `Date`) the Moment falls on (UTC); identity on a Date.
514    DateOf,
515    /// `time_of(moment)` — the wall-clock time-of-day (a `Time`) of the Moment (UTC).
516    TimeOf,
517    /// `makeDate(year, month, day)` — construct a `Date` from civil components via base `days_from_civil`.
518    MakeDate,
519    /// `makeMoment(year, month, day, hour, minute, second)` — construct a UTC `Moment` from civil
520    /// components. Defined to agree with `calendar.timegm` to the second (same `days_from_civil` core).
521    MakeMoment,
522    /// `local_instant(moment, "zone")` — the local-as-UTC instant in a named zone (the lowering
523    /// target for `the <comp> of <m> in "<zone>"`, so every extractor reads the LOCAL component).
524    LocalInstant,
525    /// `seconds_between(a, b)` — whole seconds from Moment `a` to Moment `b` (signed `Int`).
526    SecondsBetween,
527    /// `months_between(a, b)` / `years_between(a, b)` — complete calendar months/years (signed `Int`).
528    MonthsBetween,
529    YearsBetween,
530    /// `add_seconds(moment, n)` — the Moment `n` seconds after `moment`.
531    AddSeconds,
532    /// `in_zone(moment, "America/New_York")` — the local wall-clock time (with offset) of a Moment
533    /// in a named IANA zone, as Text. The natural surface is `<moment> in "<zone>"`.
534    InZone,
535    Copy,
536    CountOnes,
537    /// `leading_zeros(x)` — count of high zero bits in the Int's u64 pattern
538    /// (`(x as u64).leading_zeros()`; 64 for x = 0). Backs `bitLength`.
539    LeadingZeros,
540    /// `trailing_zeros(x)` — count of low zero bits in the Int's u64 pattern
541    /// (`(x as u64).trailing_zeros()`; 64 for x = 0). Backs `trailingZeros`.
542    TrailingZeros,
543    RunAccepted,
544    /// `word32(n)` / `word64(n)` — construct a fixed-width wrapping integer from an `Int`.
545    Word32,
546    Word64,
547    /// `rotl(w, n)` / `rotr(w, n)` — rotate a word left/right by `n` bits.
548    Rotl,
549    Rotr,
550    /// `word_and(a, b)` / `word_or(a, b)` / `word_not(a)` — bitwise ops on the Word ring, CONSISTENT
551    /// across every tier (the `and`/`or` keywords are logical short-circuit on the VM, so word crypto
552    /// written in Logos — MD5/SHA-1 round functions — uses these instead).
553    Wand,
554    Wor,
555    Wnot,
556    /// The SHA-1 SHA-NI lane vocabulary: `lanes4Word32(s)`/`seqOfLanes4W32(v)` pack/unpack a
557    /// `Lanes4Word32` (128-bit), and `sha1rnds4`/`sha1msg1`/`sha1msg2`/`sha1nexte` are the four SHA-1
558    /// operations — the primitives a SHA-1 written IN LOGOS is built from (AOT → hardware `sha1rnds4`).
559    Lanes4Word32Make,
560    /// Pack four `Word32`s straight into a lane register — the alloc-free constructor (no `Seq`).
561    Lanes4Of,
562    SeqOfLanes4W32,
563    Sha1Rnds4,
564    Sha1Msg1,
565    Sha1Msg2,
566    Sha1Nexte,
567    /// Byte-shuffle lane (`Lanes16Word8` = one `__m128i`): pack/unpack + `shuffle` (pshufb), per-byte
568    /// shift, and the two interleaves — the vocabulary a SIMD hex codec WRITTEN in Logos is built from.
569    Lanes16Word8Make,
570    SeqOfLanes16W8,
571    Splat16Word8,
572    Shuffle16,
573    ShrBytes16,
574    InterleaveLo16,
575    InterleaveHi16,
576    ByteAdd16,
577    Maddubs16,
578    Packus16,
579    /// `lanes8Word32(s)` — pack the first 8 `Word32`s of a Seq into a SIMD lane vector.
580    Lanes8Word32,
581    /// `seqOfLanes8(v)` — unpack a `Lanes8Word32` back into a Seq of 8 `Word32`.
582    SeqOfLanes8,
583    /// `splat8Word32(x)` — broadcast a `Word32` into all 8 lanes.
584    Splat8Word32,
585    /// `intOfWord32(w)` — the unsigned value of a `Word32` as an `Int` (for byte serialization).
586    IntOfWord32,
587    /// `intOfWord64(w)` — the value of a `Word64` as an `Int` (byte-masked lanes in Keccak squeeze).
588    IntOfWord64,
589    /// `word64Shl(w, n)` — logical shift-left of a `Word64` (Keccak lane byte-packing).
590    Word64Shl,
591    /// `word64Shr(w, n)` — logical shift-right of a `Word64` (Keccak squeeze byte-extract).
592    Word64Shr,
593    /// `word64And(a, b)` — bitwise AND of two `Word64`s (Keccak χ's `¬b ∧ c`).
594    Word64And,
595    /// `word32Shr(w, n)` — logical shift-right of a `Word32` (SHA-256's `σ0`/`σ1`, a non-rotating
596    /// shift where the vacated high bits are zero).
597    Word32Shr,
598    /// `word16(n)` — the low 16 bits of an `Int` as a `Word16` (ℤ/2¹⁶ coefficient).
599    Word16Make,
600    /// `intOfWord16(w)` — the unsigned value of a `Word16` as an `Int` (0..2¹⁶−1).
601    IntOfWord16,
602    /// `lanes4Word64(s)` — pack the first 4 `Word64`/`Int`s of a Seq into a `Lanes4Word64`.
603    Lanes4Word64,
604    /// `seqOfLanes4(v)` — unpack a `Lanes4Word64` into a Seq of 4 `Int` lanes.
605    SeqOfLanes4,
606    /// `mul32x32to64(a, b)` — lane-wise widening multiply of the low 32 bits (`vpmuludq`).
607    Mul32x32To64,
608    /// `hsumLanes4(v)` — the horizontal sum of a lane vector's lanes as an `Int`.
609    HsumLanes4,
610    /// `splat4Word64(x)` — broadcast a `Word64` into all 4 Keccak lanes (ι constant, χ all-ones).
611    Splat4Word64,
612    /// `andNot4(a, b)` — 4-way Keccak χ's `(¬a) ∧ b` in one lane op (`vpandn`).
613    AndNot4,
614    /// `lanes16Word16(s)` — pack the first 16 `Word16`/`Int`s of a Seq into a `Lanes16Word16`.
615    Lanes16Word16,
616    /// `seqOfLanes16(v)` — unpack a `Lanes16Word16` into a Seq of 16 `Int` lanes.
617    SeqOfLanes16,
618    /// `splat16Word16(x)` — broadcast a `Word16`/`Int` into all 16 lanes.
619    Splat16Word16,
620    /// `mulhi16(a, b)` — lane-wise SIGNED high-16 multiply (`vpmulhw`, the Montgomery `mulhi`).
621    Mulhi16,
622    /// `montmul32(a, b, q, qinv)` — the signed i32 Montgomery multiply over 8 lanes (`vpmuldq`), the
623    /// ML-DSA (Dilithium) NTT butterfly multiply (`q`/`qinv` broadcast).
624    Montmul32,
625    /// `nttBcastLo(v, h)` — broadcast each `2h`-block's low `h` lanes into both halves (the
626    /// within-vector NTT source-low duplication; `vperm2i128`/`vpshufd` by stride).
627    NttBcastLo,
628    /// `nttBcastHi(v, h)` — broadcast each `2h`-block's high `h` lanes into both halves.
629    NttBcastHi,
630    /// `nttBlend(a, b, h)` — each `2h`-block's low `h` from `a`, high `h` from `b` (the butterfly
631    /// half-recombine; `vperm2i128`/`vpblendd` by stride).
632    NttBlend,
633    /// `mapOf(k1, v1, k2, v2, …)` — construct a Map from flat key/value pairs
634    /// in INSERTION order (the `{k: v, …}` literal's lowering). A duplicate
635    /// key keeps its first position with the last value, like repeated
636    /// `Set item k of m` writes.
637    MapOf,
638    /// `setOf(a, b, …)` — construct a Set from elements in insertion order,
639    /// deduplicating by value equality (the `{a, b, …}` literal's lowering).
640    SetOf,
641    /// `repeatSeq(x, n)` — a fresh sequence of `n` slots, each an INDEPENDENT
642    /// deep copy of `x` (the `n copies of x` / `[x] * n` fill; a repeated
643    /// inner collection is n rows, never n aliases). `n ≤ 0` is empty.
644    RepeatSeq,
645    /// `reedSolomonEncode(data, parity)` — systematic Reed-Solomon FEC over GF(2^8).
646    /// `data` is a `Seq of Seq of Int` (byte shards of equal length); returns
647    /// `data.count + parity` shards, the first `data.count` being the data unchanged
648    /// (systematic), the rest parity. Any `data.count` of the shards reconstruct the data.
649    ReedSolomonEncode,
650    /// `reedSolomonRecover(received, k)` — reconstruct every shard from `received` (a `Seq`
651    /// of `n` slots, each a `Seq of Int` shard or `nothing` for an erased slot); `k` is the
652    /// data-shard count. Succeeds when at least `k` of the `n` shards survived.
653    ReedSolomonRecover,
654    /// `fecProtect(payload, k, m)` — frame a flat byte `Seq of Int`, split into `k` shards, and
655    /// Reed-Solomon encode into `k + m` loss-resilient packets (any `k` reconstruct the payload).
656    FecProtect,
657    /// `fecRestore(received, k)` — recover the payload from `received` packets (`nothing` = lost),
658    /// stripping the length header + padding to return the exact original bytes.
659    FecRestore,
660    // --- DOM (the browser tier) — Element/Event are opaque handles. On the native
661    // tiers they land in the thread-local `semantics::dom::DomRecorder`; on wasm
662    // they lower to `dom_*` host imports (a `MockDom` in tests, the real DOM in the
663    // browser). See the DOM frontend plan. ---
664    /// `body()` — the document body (the render root), a stable Element handle.
665    DomBody,
666    /// `createElement(tag)` — a new element with the given tag name.
667    DomCreateElement,
668    /// `createTextNode(text)` — a new text node.
669    DomCreateTextNode,
670    /// `setText(el, text)` — set an element's text content.
671    DomSetText,
672    /// `setHtml(el, html)` — set an element's raw innerHTML (verbatim markup).
673    DomSetHtml,
674    /// `clearChildren(el)` — remove every child (the immediate-mode re-render
675    /// primitive: the view clears its root, then rebuilds it).
676    DomClearChildren,
677    /// `onMessage(topic, handler)` — subscribe to a relay topic; the handler runs per message.
678    ///
679    /// ★ THE TRANSPORT WAS ALREADY BUILT. `logicaffeine_system::relay` carries
680    /// `Subscribe`/`Publish`/`Event` frames over one wire protocol shared by the native server,
681    /// the native client and the browser WebSocket client. `When a message arrives on "…":` was
682    /// the last trigger no tier delivered, and what it was missing was this one call — not a
683    /// protocol. The host carries bytes for a topic; which topic, and what to do with the payload,
684    /// are compiled LOGOS.
685    DomOnMessage,
686    /// Retired: `moveChildren(from, to)` reparented a holding node's children for a `{children}`
687    /// slot. A slot's children are a range of the retained tree's tape (`vdom.lg`), which the
688    /// commit places, so no source spelling resolves to this id ([`retired_builtin`] refuses the
689    /// call); the variant stays so every id after it keeps its wire position.
690    DomMoveChildren,
691    /// Retired: `beginPaint()` opened a host-side staging pass. A repaint keeps its nodes by
692    /// drawing through the retained tree (`vdom.lg`), so no source spelling resolves to this id
693    /// ([`retired_builtin`] refuses the call); the variant stays so every id after it keeps its
694    /// wire position.
695    DomBeginPaint,
696    /// `setAttribute(el, name, value)` — set an attribute.
697    DomSetAttribute,
698    /// `appendChild(parent, child)` — append `child` to `parent`.
699    DomAppendChild,
700    /// `getText(el)` — an element's text content.
701    DomGetText,
702    /// `getValue(el)` — a form input's value.
703    DomGetValue,
704    /// `setValue(el, value)` — set a form input's value.
705    DomSetValue,
706    /// `applyPatches(bytes)` — apply a whole DOM patch stream in ONE call.
707    ///
708    /// The bulk form: a program builds a buffer of operations and hands it over once, instead of
709    /// making a host call per operation. That is what lets the browser host be a `for` loop over
710    /// a stream rather than fifty entry points with behaviour behind them — the stream is the
711    /// interface, and every decision belongs to the side that emitted it.
712    ///
713    /// A malformed buffer fails LOUDLY and applies NOTHING: silently applying the prefix that
714    /// happened to parse would leave a half-built page with nothing anywhere saying so.
715    DomApplyPatches,
716    /// `setChecked(el, on)` — set a checkbox's or radio's checked state.
717    ///
718    /// A checkbox's state is a PRESENCE, not a string, and it lives on the PROPERTY rather than
719    /// the attribute — `setAttribute(el, "checked", …)` writes `defaultChecked` and leaves the
720    /// box a visitor sees unchanged. So it gets an operation of its own rather than riding on
721    /// `setValue` (which a checkbox ignores) or `setAttribute` (which lies).
722    DomSetChecked,
723    /// `preventDefault(node, event)` — this listener cancels the browser's own action.
724    DomPreventDefault,
725    /// `storageSet(area, key, value)` / `storageGet(area, key)` / `storageRemove(area, key)` —
726    /// browser storage, where `area` is `"local"` (survives closing the tab) or `"session"`
727    /// (survives a reload, ends with the tab).
728    ///
729    /// The AREA IS AN ARGUMENT rather than two families of operation, so a third area later is
730    /// not a change to the host boundary; an area nobody defines is refused by name rather than
731    /// written somewhere nothing reads. `storageGet` answers an `Option of Text` because a
732    /// missing key and a stored empty string are different, and a page that confuses them will
733    /// overwrite one with the other.
734    StorageSet,
735    StorageGet,
736    /// `storageGetOr(area, key, fallback)` — the stored text, or `fallback` when the key is not
737    /// there. The absence-answering sibling of `storageGet`, and the one a stored value is
738    /// usually READ with: "what I saved, or what I start from" is the whole question a page has.
739    ///
740    /// It exists as its own operation rather than as sugar because an `Option of Text` is a
741    /// BOXED handle on the WebAssembly tier — its presence can be tested but its value cannot
742    /// yet be taken out — so a lowering that must USE a stored value goes through here, where no
743    /// Option crosses the boundary at all. No new host import: it is `storage_get` plus a test
744    /// of the answered handle.
745    StorageGetOr,
746    StorageRemove,
747    /// `setStream(el, streamHandle)` — attach an opaque host `MediaStream` to an element's
748    /// `srcObject`, rendering a live video/audio track in a `<video>`/`<audio>` tile.
749    DomSetStream,
750    /// WebRTC browser-P2P leg. `peerConnection()` mints an `RTCPeerConnection`; `dataChannel(pc,
751    /// label)` opens a channel; `createOffer`/`createAnswer` produce the SDP; `setLocalDescription`/
752    /// `setRemoteDescription` apply it; `addIceCandidate` adds a remote candidate; `channelSend`
753    /// pushes bytes down the channel.
754    RtcPeerConnection,
755    RtcDataChannel,
756    RtcCreateOffer,
757    RtcCreateAnswer,
758    RtcSetLocal,
759    RtcSetRemote,
760    RtcAddIce,
761    RtcSend,
762    /// `querySelector(sel)` — the first element matching a bare tag or `#id`
763    /// (a `-1` handle if none).
764    DomQuerySelector,
765    /// `addEventListener(el, event, handler)` — register a LOGOS closure to run
766    /// when `event` fires on `el`. The handler rides the B0 `__logos_call_closure`
767    /// trampoline on wasm; on native tiers it is stored and invoked to simulate.
768    DomAddEventListener,
769    /// `eventValue(event)` — the value of the input that dispatched `event`.
770    DomEventValue,
771    /// `eventKey(event)` — the key of the keyboard event being dispatched (`""` otherwise).
772    DomEventKey,
773    /// `tryReadBytes(path)` — a file's bytes as `Result of Seq of Int and Text`. The total form
774    /// of [`BuiltinId::ReadBytes`]: a missing or unreadable file is a value, not a trap.
775    TryReadBytes,
776    /// `eventTarget(event)` — the element that dispatched `event`.
777    DomEventTarget,
778    /// `fetchText(url, onDone)` — fetch `url`; when it resolves, run the completion
779    /// closure `onDone(reqId)`, which reads the body via `responseText()`.
780    DomFetchText,
781    /// `responseText()` — the body of the fetch currently being delivered.
782    DomResponseText,
783    /// `readBytes(path)` — a file's raw bytes as a `Seq of Int` (for serving
784    /// binary content like a `.wasm`). Native tiers only.
785    ReadBytes,
786    /// `signal(initial)` — a new reactive state cell; returns its `Int` handle.
787    SignalNew,
788    /// `signalSet(s, value)` — write a signal and mark the store dirty (→ re-render).
789    SignalSet,
790    /// `signalGetInt(s)` — a signal's current value as an `Int`.
791    SignalGetInt,
792    /// `signalGetText(s)` — a signal's current value as `Text`.
793    SignalGetText,
794    /// `beginRender()` — reset the signal hooks cursor; the view's first op on
795    /// every (re-)render so its `signal(...)` calls return the same cells.
796    SignalBeginRender,
797    /// `signalNewText(initial)` — a signal holding `Text` (distinct wasm ABI: the
798    /// initial value and writes are a `Text` handle, not an Int).
799    SignalNewText,
800    /// `signalSetText(s, value)` — write a `Text` signal; marks the store dirty.
801    SignalSetText,
802    /// `enterComponent(key)` — push a component's hook scope (its per-instance
803    /// identity) so its `signal(...)` calls get their own cells.
804    SignalEnterComponent,
805    /// `exitComponent()` — pop back to the parent component's hook scope.
806    SignalExitComponent,
807    /// `signalNewSeq(initial)` — a signal holding a `Seq` (a live collection).
808    /// Like [`BuiltinId::SignalNewText`] its wasm ABI is a handle (an `i32` Seq handle), the
809    /// element kind riding the `SeqText` representation; a live list re-renders a
810    /// `for each` view when `Push`/`Set` writes it.
811    SignalNewSeq,
812    /// `signalGetSeq(s)` — a signal's current value as a `Seq`.
813    SignalGetSeq,
814    /// `signalSetSeq(s, value)` — write a `Seq` signal; marks the store dirty.
815    SignalSetSeq,
816    /// `signalNewFloat(initial)` — a signal holding a `Real`.
817    ///
818    /// A signal's value family is settled at its declaration by the parser, which
819    /// is the only place that can see the whole program: a float initial value, an
820    /// explicit `Let rate: Real be a signal 2`, or a later fractional write all
821    /// name this family. Saying it in the BUILTIN — exactly as `Text` and `Seq`
822    /// signals already do — is what lets every function agree. A backend that had
823    /// to infer float-ness from a value's kind could only see one function at a
824    /// time, so a view that read a cell an event handler wrote would disagree with
825    /// it and render the float's raw bits.
826    SignalNewFloat,
827    /// `signalGetFloat(s)` — a signal's current value as a `Real`.
828    SignalGetFloat,
829    /// `signalSetFloat(s, value)` — write a `Real` signal; marks the store dirty.
830    SignalSetFloat,
831    /// file.lg's `## To native read (path) -> Result of Text and Text` — the shared
832    /// tree-walker/VM seam. NOT name-mapped in [`builtin_from_name`]: each tier
833    /// routes here only when the callee is the EMPTY-bodied native declaration, so
834    /// a user-defined `read` with a real body always wins (declarer-wins).
835    FileRead,
836    /// file.lg's `## To native write (path, content) -> Result of Unit and Text` —
837    /// same routing rule as [`BuiltinId::FileRead`].
838    FileWrite,
839    /// random.lg's `## To native randomInt (min, max) -> Int` — the shared
840    /// tree-walker/VM seam over `logicaffeine_system::random`. NOT name-mapped in
841    /// [`builtin_from_name`]: each tier routes here only when the callee is the
842    /// EMPTY-bodied native declaration, so a user-defined `randomInt` with a real
843    /// body always wins (declarer-wins).
844    RandomInt,
845    /// random.lg's `## To native randomFloat () -> Real` — same routing rule as
846    /// [`BuiltinId::RandomInt`].
847    RandomFloat,
848    // --- The correlated browser fetch contract (append-only tail; see the DOM
849    // block above). `fetchSend` mints a REQUEST ID; every response accessor is
850    // keyed by it, so concurrent fetches can never overwrite or misdeliver each
851    // other. `fetchText`/`responseText` remain as sugar over the same engine. ---
852    /// `fetchSend(method, url, body, headers, onDone) -> Int` — start a request
853    /// and return its correlation id. `headers` is a `Seq of Text` alternating
854    /// name,value (the flat form that crosses the wasm ABI as one seq handle);
855    /// names must be on the request-header allowlist. When the response (or a
856    /// structured failure) arrives the host runs `onDone(reqId)`.
857    DomFetchSend,
858    /// `responseStatus(reqId) -> Int` — the HTTP status; `0` while pending or on
859    /// any transport failure (`responseError` then names it).
860    DomResponseStatus,
861    /// `responseBody(reqId) -> Text` — the delivered body (`""` pending/failed).
862    DomResponseBody,
863    /// `responseHeader(reqId, name) -> Text` — a response header, case-insensitive
864    /// (`""` when absent).
865    DomResponseHeader,
866    /// `responseError(reqId) -> Text` — `""` when none; else `"timeout"` |
867    /// `"abort"` | `"toolarge"` | `"network: <detail>"`.
868    DomResponseError,
869    /// `fetchAbort(reqId)` — the request becomes final with the `"abort"` error;
870    /// a late response can never deliver.
871    DomFetchAbort,
872    /// `fetchSetTimeout(reqId, millis)` — arm (`> 0`) or clear (`0`) a timeout;
873    /// firing delivers the `"timeout"` error and runs the callback.
874    DomFetchSetTimeout,
875    // --- The history/location router (append-only tail; serde-stable variant order).
876    // `routePath`/`routeQuery` read `window.location`; `navigate`/`replaceRoute` are
877    // history.pushState/replaceState; `onRoute` registers the popstate handler. On the
878    // native tiers they land in the recorder's location model; on wasm they lower to
879    // `dom_*` router host imports. The `matchRoute`/`routeParam` pattern matcher is
880    // pure-LOGOS in web.lg over `routePath`. ---
881    /// `routePath() -> Text` — the current location pathname (`"/"` at boot).
882    DomRoutePath,
883    /// `routeQuery(name) -> Text` — a query param by name (`""` when absent).
884    DomRouteQuery,
885    /// `navigate(path)` — history.pushState + fires the router (records the navigation,
886    /// moves the current path).
887    DomNavigate,
888    /// `replaceRoute(path)` — history.replaceState (records a REPLACE navigation).
889    DomReplaceRoute,
890    /// `setTitle(t)` — the document's title. The one page-level property a page sets by name;
891    /// `docs/web.md` teaches `Set the title to "Todos".`, so it was taught and unbuildable.
892    DomSetTitle,
893    /// `clipboardWrite(t)` — put `t` on the system clipboard.
894    ///
895    /// ★ THREE IMPORTS RATHER THAN ONE FAMILY, unlike the element commands. Those differ only in
896    /// which single method is called on the same node; these are three different CAPABILITIES with
897    /// three different permission models and three different ways to be denied — a clipboard write
898    /// a browser may refuse, a file the viewer may decline, a notification that needs consent.
899    /// Folding them into one `pageCommand` would name three decisions with one word.
900    DomClipboardWrite,
901    /// `downloadFile(content, name)` — offer `content` to the viewer as a file called `name`.
902    DomDownloadFile,
903    /// `notify(message, tone)` — raise a notification.
904    DomNotify,
905    /// `publish(topic, message)` — send a frame on a relay topic.
906    ///
907    /// ★ THE OUTWARD LEG ONLY. A page's own subscribers are reached in compiled LOGOS, by
908    /// dispatching `message:<topic>` through the table `Raise` drives; this carries the frame that
909    /// genuinely leaves the page. Splitting it that way is what keeps the deciding — who hears a
910    /// publish, and when — inside the module rather than in a host nobody can test.
911    DomPublish,
912    /// `elementCommand(el, command)` — perform a named operation on ONE element: put the cursor in
913    /// it, take the cursor out, bring it into view, select its text.
914    ///
915    /// ★ ONE IMPORT FOR THE FAMILY, because they differ only in which single DOM call is made and
916    /// none of them decides anything. Five imports would have said the same thing five times, and
917    /// the ABI is a place where saying something twice is how it drifts.
918    DomElementCommand,
919    /// `eventFileName(ev) -> Text` — the name of the first file a drop carried, `""` when it
920    /// carried none. A READ of the drop's file (a browser's file transfer, or in process the file
921    /// the host delivering the drop handed over); what the page then does about it is compiled
922    /// LOGOS.
923    DomEventFileName,
924    /// `setInterval(ms, handler)` — the browser's clock, arming ONE repeating callback for the
925    /// whole page. Which of the page's timers that makes due is decided in compiled LOGOS
926    /// (`__lgx_tick`), so the arithmetic is the same on a tier with no clock at all.
927    DomSetInterval,
928    /// `scrollGap(el) -> Int` — how many pixels of `el`'s content sit BELOW what is visible.
929    ///
930    /// ★ A READING, NOT A DECISION. Whether that gap is small enough to count as "the bottom" is
931    /// the page's business and stays in compiled LOGOS; the host is only asked for the three
932    /// numbers a browser holds and no other tier can know. Node 0 means the page itself.
933    DomScrollGap,
934    /// `onWindowEvent(event, handler)` — register a handler for something that happens to the
935    /// PAGE rather than to an element: going offline, coming back online, the window resizing.
936    /// One builtin for all of them, because they differ only in the event's name.
937    DomOnWindowEvent,
938    /// `getAttribute(el, name) -> Text` — an element's attribute, `""` when it has none.
939    /// The READ half of the attribute pair. It exists so `Add class`/`Remove class` can be
940    /// COMPILED LOGOS over `setAttribute` rather than two more host functions: a class list is
941    /// space-separated words, and deciding which words survive is the framework's job, not the
942    /// host's.
943    DomGetAttribute,
944    /// `goBack()` — step one history entry back, as a visitor's Back button does. Answers
945    /// nothing; a page at its first entry simply stays where it is.
946    DomGoBack,
947    /// `reload()` — the page starts over: every instance, listener and mounted root goes and the
948    /// document is rebuilt. A browser does it by reloading the document; the in-process tiers do
949    /// it by clearing the same two stores the reference tier clears, so the observable result is
950    /// one page that has forgotten everything.
951    DomReload,
952    /// `onRoute(handler)` — register a popstate/navigation handler; a back/forward fires
953    /// it with the new path. The handler rides the closure trampoline on wasm (like
954    /// `addEventListener`/`fetchText`'s `onDone`).
955    DomOnRoute,
956    // ── Appended builtins: the wire format carries a builtin as its POSITION here, so new
957    // builtins are added at the END only (locked by `builtin_wire_id_lock`). ──
958    /// `Fail with <value>.` — stop with the value's display text as the reason. Reserved name
959    /// (`__logos_fail`): the compiler writes the call, an author never does.
960    Fail,
961    /// A broken contract's `, otherwise <reason>` — stop with the reason, which must be Text
962    /// ([`contract_reason_text`]). Reserved name (`__logos_fail_reason`).
963    FailReason,
964    /// `word8(n)` — the low 8 bits of an `Int` as a `Word8` (the ring ℤ/2⁸).
965    Word8Make,
966    /// `intOfWord8(w)` — the unsigned value of a `Word8` as an `Int` (0..255).
967    IntOfWord8,
968    /// A standard-library native kernel (`## To native` in `crypto.lg`): argument 0 is the kernel's
969    /// [`NativeKernel::code`], the rest are its arguments. Reserved name (`__logos_native_kernel`): the
970    /// VM compiler writes the call for a kernel's declaration, an author never does.
971    ///
972    /// [`NativeKernel::code`]: crate::semantics::native_kernels::NativeKernel::code
973    NativeKernel,
974    /// `noteTurn(name: Text, key: Text, changes: Seq of Text, failure: Text)` — records one turn
975    /// in the journal natively, so `the journal`/`Replay` work on a lowered tier without a
976    /// `## Store`-shaped mechanism to carry it: the action's journal name, the instance it ran
977    /// against, every field whose display changed as `[field, before, after, …]` in declaration
978    /// order, and the failure that rolled it back (`""` for a turn that committed). Reserved name
979    /// (`noteTurn`): the lowering emits the call at the end of every turn, never written by an
980    /// author. Browser-only: the journal it writes into is the page's turn history, which a
981    /// device tier has none of.
982    NoteTurn,
983    /// `setHeadHtml(html)` — the document `<head>`'s markup (`<title>`/`<meta>`/…), from a page's
984    /// `Head:` section, written through `semantics::dom::set_head_html`. Appended LAST, never
985    /// inserted among its `Dom*` siblings above: a builtin's wire id is its position in this enum
986    /// (`builtin_wire_id_lock.rs`), so a new one is always added at the END regardless of where it
987    /// reads best.
988    DomSetHeadHtml,
989    /// The ONE place a non-exhaustive `Inspect` with no statically-known enum (a dynamic value —
990    /// a kernel inductive, or a compilation with no type registry at all) fails LOUD instead of
991    /// falling through to `Fail`'s generic, value-display-only message. Compiler-emitted only
992    /// (`vm/compiler.rs`'s `compile_inspect`), never named from LOGOS source — it reads the ONE
993    /// scrutinee register `compile_inspect` already evaluated and calls the SAME
994    /// `semantics::builtins::inspect_unhandled_message` the tree-walker's own `inspect_unhandled`
995    /// calls, so a dynamic non-exhaustive match fails with byte-identical words on both tiers,
996    /// closing the class `Fail`'s fallback (a bare `to_display_string()` of the scrutinee, no
997    /// variant/type framing) could not.
998    InspectUnhandledDynamic,
999    /// `eventFileSize(ev) -> Int` — the size in bytes of the first file a drop carried, its
1000    /// sibling `eventFileName` beside it: a `File`'s `size` is the file's own, never a literal. A
1001    /// browser answers from the actual event through `dom_event_file_size` (`vm/wasm/module.rs`,
1002    /// `runtime.js`); an in-process tier answers from the file the host delivering the drop
1003    /// handed over (`semantics::dom::dropped_file`).
1004    DomEventFileSize,
1005    /// `eventFileType(ev) -> Text` — the first file's MIME type, `""` when it carried none or the
1006    /// browser named none. Answered from the same file as `eventFileSize` beside it.
1007    DomEventFileType,
1008    /// `eventFileBytes(ev) -> Seq of Int` — the first file's content, one byte per element. A
1009    /// browser reads the file's `arrayBuffer()` BEFORE the drop's turn runs and hands it over
1010    /// through `dom_event_file_bytes`, so the turn only ever runs with the content in hand; an
1011    /// in-process tier answers from the same file as `eventFileSize` beside it.
1012    DomEventFileBytes,
1013    /// `listenFlags(el, event, flags)` — register `event` on `el` with the behavioural modifiers
1014    /// `flags` names (`semantics::dom::LISTEN_*`: prevent 1, stop 2, once 4, capture 8, passive 16),
1015    /// replacing any flags an earlier registration gave it. A browser attaches its listener in the
1016    /// capture phase or not, passive or not, stopping propagation or not; an in-process tier walks an
1017    /// event by the same flags (`semantics::dom::dispatch_path`). Browser-only.
1018    DomListenFlags,
1019    /// `assignLocation(url)` — load another document at `url`, as `location.assign` does, once the
1020    /// running script is done: then the page that asked is gone, and `url` is where the browser
1021    /// stands. What `Navigate to` a page outside this module's own pattern lowers to; an in-process
1022    /// host carries the request out after the call that made it (`semantics::dom::request_load`),
1023    /// recording the load (`RouteOp::Load`) and starting an empty document there. Browser-only.
1024    DomAssignLocation,
1025    /// `journalDetail() -> Bool` — whether this host keeps the journal's detail, so a lowered turn
1026    /// captures the fields it changed only where something reads them: every in-process host
1027    /// records the journal and answers true; a browser answers true only under the test harness,
1028    /// so a shipped page pays nothing for a journal nobody keeps. Reserved name: the lowering
1029    /// writes the call, an author never does. Browser-only.
1030    DomJournalDetail,
1031    /// `applyPatchWords(words, wordCount, strings, stringCount)` — apply the first `wordCount` words
1032    /// of a wire-v2 patch stream, whose text operands index the first `stringCount` strings, in ONE
1033    /// call; answers how many adopted nodes did not match. What `vdom.lg`'s `vdApply` hands over.
1034    /// All or nothing, as `applyPatches` is.
1035    DomApplyWords,
1036    /// `wakeAfter(ms)` — ask the host to call the page's `__lgx_tick` with the time that passed once
1037    /// `ms` more milliseconds have gone by, replacing any earlier request; a negative `ms` cancels
1038    /// it. The page keeps its own clock and decides every timer in compiled LOGOS; this only says
1039    /// when its earliest one comes due. Reserved name: the lowering writes the call, an author never
1040    /// does. Browser-only: an in-process host moves time only by `Advance time by …`.
1041    DomWakeAfter,
1042    /// `enterValue(verb, selector, value)` — a visitor's `Type` or `Choose` on the element
1043    /// `selector` names, as the browser's own default action performs it: whether the control
1044    /// takes the verb ([`crate::semantics::dom::answers_by_itself`] — a text field a visitor can
1045    /// reach takes typing, a `<select>` offering `value` takes the choice), and when it does, the
1046    /// value entered into it ([`crate::semantics::dom::enter_value`]). `verb` is `"type"` or
1047    /// `"choose"`. The bytecode tier's driving verbs write the call; it has no source name.
1048    DomEnterValue,
1049    /// `dispatchEntry(dispatcher, context, hook, node, event, value)` — a driving verb the program
1050    /// runs on its own page, taken as the HOST's entry into the page: the page's dispatcher
1051    /// (function `dispatcher`, `__lgx_dispatch_node`) runs as an entry of its own, so a turn that
1052    /// fails there is contained to it — the page's failure door hears it (the text `context`
1053    /// answers, then the `hook` handler, each a function index or -1 for none), the first failure
1054    /// no handler absorbed becomes the program's own failure once nothing is left to run, and the
1055    /// program's next statement runs. Answers whether the page heard the event; a failed turn was
1056    /// heard. The bytecode tier's driving verbs write the call; it has no source name, and the
1057    /// engine running the page carries it out (it calls back into the program).
1058    DomDispatchEntry,
1059    /// `Read … from file "…".`'s runtime lookup on the bytecode VM: the SAME sandboxed
1060    /// [`logicaffeine_system::fs::MemVfs`] the tree-walker's `ReadFrom` reads through, so a file
1061    /// read errors identically on both tiers. Reserved name: `Stmt::ReadFrom`'s VM compiler arm
1062    /// writes the call; an author never spells it.
1063    VfsReadFile,
1064    /// `Write … to file "…".`'s runtime store on the bytecode VM: the SAME sandboxed
1065    /// [`logicaffeine_system::fs::MemVfs`] the tree-walker's `WriteFile` writes through, so what a
1066    /// program wrote on either tier is what it reads back on either. Reserved name:
1067    /// `Stmt::WriteFile`'s VM compiler arm writes the call; an author never spells it.
1068    VfsWriteFile,
1069    /// `Mount … at "…".`'s runtime load on the bytecode VM: the journal file's text from the SAME
1070    /// sandboxed [`logicaffeine_system::fs::MemVfs`] the tree-walker's `Mount` reads, or empty
1071    /// Text when there is none yet — the tree-walker's arm exactly. Reserved name: `Stmt::Mount`'s
1072    /// VM compiler arm writes the call; an author never spells it.
1073    VfsMount,
1074    /// env.lg's `## To native get (key) -> Option of Text` — the variable `key` names in the
1075    /// environment the program runs in, `none` when it is unset, through
1076    /// [`logicaffeine_system::env::get`] (sealed-world aware). Same routing rule as
1077    /// [`BuiltinId::FileRead`]: [`system_native`] answers it only for the empty-bodied native
1078    /// declaration, so a program's own `get` always wins.
1079    EnvGet,
1080    /// time.lg's `## To native now () -> Nat` — the Unix time in milliseconds, through
1081    /// [`logicaffeine_system::time::now`] (sealed-world aware). Not the bare `now` of a moment
1082    /// (`Op::LoadNow`): this is the stdlib function, same routing rule as [`BuiltinId::EnvGet`].
1083    TimeNow,
1084    /// Whether the environment sets the variable `name` — half of the VM compiler's expansion of
1085    /// [`BuiltinId::EnvGet`] into ops every downstream tier already lowers (`mapOf`'s rule): the
1086    /// `Option` is then built by `NewInductive`, as any other is. Reserved name: the VM compiler
1087    /// writes the call; an author never spells it.
1088    EnvHas,
1089    /// The text of the environment variable `name`, `""` when it is unset — the other half of the
1090    /// expansion [`BuiltinId::EnvHas`] describes. Reserved name, as there.
1091    EnvValue,
1092    /// `infinitesimal(name, modulus, residue…)` — the program's infinitesimal, the residues its
1093    /// reciprocal may take modulo `modulus` given (`Let dt be an infinitesimal …`).
1094    Infinitesimal,
1095    /// `standardPart(x[, at])` — the standard real infinitely close to a limited `x` (`the standard
1096    /// part of x`); an infinite value has none. Relative to the infinitesimal `at`, what `x` is
1097    /// infinitely close to among the values of `at` and the infinitesimals larger than it (`the
1098    /// standard part of x relative to dt`).
1099    StandardPart,
1100    /// `isInfinitesimal(x[, at])` — `x` is zero or smaller than every positive standard number, or
1101    /// every positive value of `at` and the infinitesimals larger than it.
1102    IsInfinitesimal,
1103    /// `isLimited(x[, at])` — `x` is bounded by a standard number, or a value of `at` and the
1104    /// infinitesimals larger than it.
1105    IsLimited,
1106    /// `infinitelyClose(x, y[, at])` — `x − y` is infinitesimal, relative to `at` when it is given.
1107    InfinitelyClose,
1108    /// `generatorOf(dt)` — the infinite natural `⌈1/dt⌉`.
1109    GeneratorOf,
1110    /// `limitOf(x, rule)` — a residue-dependent `x` resolved under a named limit rule.
1111    LimitOf,
1112    /// `provisional(value, cases, revisions)` — the answer of a search no proof settled.
1113    Provisional,
1114    /// `atTheLimit(rule)` — the limit rule supertasks below it take (`At the limit, take …`).
1115    AtTheLimit,
1116    /// `everyNatural(cases)` — the iterable of `Repeat for every natural n`; the supertask engine
1117    /// replaces every such loop before a program runs.
1118    EveryNatural,
1119    /// `tripCount(t0, step, bound, relation)` — how many times a loop stepped by a clock runs.
1120    TripCount,
1121    /// `affinePower(matrix, state, n)` — the state after `n` steps of an affine update.
1122    AffinePower,
1123    /// `cycleAt(states, repeated, n)` — the state at step `n` of a run that has entered a cycle.
1124    CycleAt,
1125    /// `searchCandidates(terms, periods)` — the naturals a search over every natural examines.
1126    SearchCandidates,
1127    /// `stateSize(state)` — the bits a supertask's state occupies, which bounds its cycle search.
1128    StateSize,
1129    /// `polynomialFlow(field, state, n)` — the state after `n` Euler steps of a polynomial update.
1130    PolynomialFlow,
1131    /// `exactSqrt(x)`, `exactExp(x)`, `exactLn(x)` — the square root, exponential and natural
1132    /// logarithm held exactly; `sqrt`, `exp` and `ln` are these in a context that declares an exact
1133    /// type.
1134    ExactSqrt,
1135    ExactExp,
1136    ExactLn,
1137    /// `exactPi()`, `exactE()` — π and e held exactly; `pi` and `e` are these in an exact context.
1138    ExactPi,
1139    ExactE,
1140    /// `exactOmega()` — ω, the first infinite ordinal; `omega` is this in an `Ordinal` context.
1141    ExactOmega,
1142    /// `hybridFlow(model, state, n)` — the state after `n` steps of a loop whose state flows by a
1143    /// polynomial Euler step between jumps.
1144    HybridFlow,
1145    /// `firstExit(t0, step, guard)` — how many passes a loop makes whose guard compares terms linear
1146    /// in a counter it steps.
1147    FirstExit,
1148    /// `definedReal(kind, base, name, f)` — the real number the function `f` defines by its digits in
1149    /// `base` or by its approximations (`the real number whose digits in base 3 are f`, `the real
1150    /// number approximated by f`).
1151    DefinedReal,
1152    /// `exactPower(base, exponent)` — `base ** exponent` to an exponent that is an exact number, which
1153    /// `**` is when its exponent is one: a fraction takes a root (`2 ** (1/2)` is `√2`).
1154    ExactPower,
1155    /// `orderedInfinitesimal(name, larger, smaller, modulus, residue…)` — an infinitesimal much smaller
1156    /// than `larger` and much larger than `smaller`, each an infinitesimal or `nothing` (`Let dx be an
1157    /// infinitesimal much smaller than dt …`).
1158    OrderedInfinitesimal,
1159    /// `sealBox(key, bytes)` — XChaCha20-Poly1305 under a 24-byte nonce drawn from the system's
1160    /// entropy for this seal, carried in front: `nonce ‖ ciphertext ‖ tag`. One key seals any number of
1161    /// boxes with no nonce for the caller to keep apart. Inverse: `openBox`.
1162    SealBox,
1163    /// `openBox(key, box)` — verify the box's tag (constant-time) and decrypt it under the nonce it
1164    /// carries. ERRORS on a wrong key, a tampered or truncated box, or a value box.
1165    OpenBox,
1166    /// `sealValueBox(key, value)` — `sealBox` of the value's wire encoding, under its own associated data
1167    /// so a value box never opens as a byte box. Inverse: `openValueBox`.
1168    SealValueBox,
1169    /// `openValueBox(key, box)` — open a `sealValueBox` and wire-decode it back into the value. ERRORS
1170    /// on a wrong key, a tampered or truncated box, or a byte box.
1171    OpenValueBox,
1172    /// `readReals(path)` — the `Seq of Real` a file of little-endian binary64 values holds, eight bytes a value in
1173    /// order ([`logicaffeine_system::file::read_reals`]). ERRORS on a file it cannot read or one that is not a whole
1174    /// number of values. The numbers a program reads at run time rather than carries as code: a model's weights.
1175    ReadReals,
1176}
1177
1178impl BuiltinId {
1179    /// The builtin of the exact extension this is, answered by [`logicaffeine_base::extension::call`]
1180    /// on every tier.
1181    pub fn extension(self) -> Option<logicaffeine_base::extension::Builtin> {
1182        use logicaffeine_base::extension::Builtin;
1183        Some(match self {
1184            BuiltinId::Infinitesimal => Builtin::Infinitesimal,
1185            BuiltinId::StandardPart => Builtin::StandardPart,
1186            BuiltinId::IsInfinitesimal => Builtin::IsInfinitesimal,
1187            BuiltinId::IsLimited => Builtin::IsLimited,
1188            BuiltinId::InfinitelyClose => Builtin::InfinitelyClose,
1189            BuiltinId::GeneratorOf => Builtin::GeneratorOf,
1190            BuiltinId::LimitOf => Builtin::LimitOf,
1191            BuiltinId::Provisional => Builtin::Provisional,
1192            BuiltinId::AtTheLimit => Builtin::AtTheLimit,
1193            BuiltinId::TripCount => Builtin::TripCount,
1194            BuiltinId::AffinePower => Builtin::AffinePower,
1195            BuiltinId::PolynomialFlow => Builtin::PolynomialFlow,
1196            BuiltinId::HybridFlow => Builtin::HybridFlow,
1197            BuiltinId::FirstExit => Builtin::FirstExit,
1198            BuiltinId::ExactPower => Builtin::ExactPower,
1199            BuiltinId::OrderedInfinitesimal => Builtin::OrderedInfinitesimal,
1200            BuiltinId::CycleAt => Builtin::CycleAt,
1201            BuiltinId::SearchCandidates => Builtin::SearchCandidates,
1202            BuiltinId::StateSize => Builtin::StateSize,
1203            BuiltinId::EveryNatural => Builtin::EveryNatural,
1204            BuiltinId::ExactSqrt => Builtin::ExactSqrt,
1205            BuiltinId::ExactExp => Builtin::ExactExp,
1206            BuiltinId::ExactLn => Builtin::ExactLn,
1207            BuiltinId::ExactPi => Builtin::ExactPi,
1208            BuiltinId::ExactE => Builtin::ExactE,
1209            BuiltinId::ExactOmega => Builtin::ExactOmega,
1210            _ => return None,
1211        })
1212    }
1213
1214    /// Whether this builtin answers a value of the exact extension: a builtin of it, or `definedReal`,
1215    /// whose real number every tier makes from the machine values of its kind, base, name and closure.
1216    pub fn answers_exact(self) -> bool {
1217        self.extension().is_some() || matches!(self, BuiltinId::DefinedReal)
1218    }
1219
1220    /// The width in bits of the fixed-width word this builtin returns, `arg` being the width of its
1221    /// first argument where the result is a word of that width (`rotr`, `word_and`, …); `None` where it
1222    /// returns no word. A word's arithmetic wraps at its width, so no tier holds one as an exact `Int`.
1223    pub fn word_result(self, arg: Option<u8>) -> Option<u8> {
1224        match self {
1225            BuiltinId::Word8Make => Some(8),
1226            BuiltinId::Word16Make => Some(16),
1227            BuiltinId::Word32 | BuiltinId::Word32Shr => Some(32),
1228            BuiltinId::Word64
1229            | BuiltinId::Word64Shl
1230            | BuiltinId::Word64Shr
1231            | BuiltinId::Word64And => Some(64),
1232            BuiltinId::Rotl
1233            | BuiltinId::Rotr
1234            | BuiltinId::Wnot
1235            | BuiltinId::Wand
1236            | BuiltinId::Wor => arg,
1237            _ => None,
1238        }
1239    }
1240
1241    /// The width of the words of the sequence this builtin returns, when it returns a sequence of
1242    /// fixed-width words (`seqOfLanes8` unpacks eight `Word32`s).
1243    pub fn word_seq_result(self) -> Option<u8> {
1244        match self {
1245            BuiltinId::SeqOfLanes8 => Some(32),
1246            _ => None,
1247        }
1248    }
1249
1250    /// Whether this builtin only exists in a BROWSER — the DOM, the reactive-signal store, and
1251    /// the WebRTC peer surface.
1252    ///
1253    /// A device tier has no document. Before this existed, a page compiled "successfully" to
1254    /// AOT-Rust, AOT-C and CUDA — 380 bytes of Rust, 121KB of C, a GPU kernel — none of which has
1255    /// anything to render into, so `largo build --target cuda` on a `## Page` produced an
1256    /// artifact that BUILT and could only ever draw nothing. The mistake then surfaced at run
1257    /// time on a device, a long way from the `--target` flag that caused it.
1258    pub fn is_browser_only(self) -> bool {
1259        match self {
1260            BuiltinId::DomBody
1261            | BuiltinId::DomCreateElement
1262            | BuiltinId::DomCreateTextNode
1263            | BuiltinId::DomSetText
1264            | BuiltinId::DomSetHtml
1265            | BuiltinId::DomClearChildren
1266            | BuiltinId::DomMoveChildren
1267            | BuiltinId::DomOnMessage
1268            | BuiltinId::DomBeginPaint
1269            | BuiltinId::DomSetAttribute
1270            | BuiltinId::DomAppendChild
1271            | BuiltinId::DomGetText
1272            | BuiltinId::DomGetValue
1273            | BuiltinId::DomSetValue
1274            | BuiltinId::DomSetChecked
1275            | BuiltinId::DomPreventDefault
1276            | BuiltinId::DomApplyPatches
1277            | BuiltinId::DomApplyWords
1278            | BuiltinId::DomWakeAfter
1279            | BuiltinId::DomEnterValue
1280            | BuiltinId::DomDispatchEntry
1281            | BuiltinId::StorageSet
1282            | BuiltinId::StorageGet
1283            | BuiltinId::StorageGetOr
1284            | BuiltinId::StorageRemove
1285            | BuiltinId::DomSetStream
1286            | BuiltinId::RtcPeerConnection
1287            | BuiltinId::RtcDataChannel
1288            | BuiltinId::RtcCreateOffer
1289            | BuiltinId::RtcCreateAnswer
1290            | BuiltinId::RtcSetLocal
1291            | BuiltinId::RtcSetRemote
1292            | BuiltinId::RtcAddIce
1293            | BuiltinId::RtcSend
1294            | BuiltinId::DomQuerySelector
1295            | BuiltinId::DomAddEventListener
1296            | BuiltinId::DomEventValue
1297            | BuiltinId::DomEventKey
1298            | BuiltinId::DomEventTarget
1299            | BuiltinId::DomFetchText
1300            | BuiltinId::DomResponseText
1301            | BuiltinId::SignalNew
1302            | BuiltinId::SignalSet
1303            | BuiltinId::SignalGetInt
1304            | BuiltinId::SignalGetText
1305            | BuiltinId::SignalBeginRender
1306            | BuiltinId::SignalNewText
1307            | BuiltinId::SignalSetText
1308            | BuiltinId::SignalEnterComponent
1309            | BuiltinId::SignalExitComponent
1310            | BuiltinId::SignalNewSeq
1311            | BuiltinId::SignalGetSeq
1312            | BuiltinId::SignalSetSeq
1313            | BuiltinId::SignalNewFloat
1314            | BuiltinId::SignalGetFloat
1315            | BuiltinId::SignalSetFloat
1316            | BuiltinId::DomFetchSend
1317            | BuiltinId::DomResponseStatus
1318            | BuiltinId::DomResponseBody
1319            | BuiltinId::DomResponseHeader
1320            | BuiltinId::DomResponseError
1321            | BuiltinId::DomFetchAbort
1322            | BuiltinId::DomFetchSetTimeout
1323            | BuiltinId::DomRoutePath
1324            | BuiltinId::DomRouteQuery
1325            | BuiltinId::DomNavigate
1326            | BuiltinId::DomReplaceRoute
1327            | BuiltinId::DomOnRoute
1328            | BuiltinId::DomSetTitle
1329            | BuiltinId::DomSetHeadHtml
1330            | BuiltinId::DomReload
1331            | BuiltinId::DomGoBack
1332            | BuiltinId::DomGetAttribute
1333            | BuiltinId::DomOnWindowEvent
1334            | BuiltinId::DomScrollGap
1335            | BuiltinId::DomSetInterval
1336            | BuiltinId::DomEventFileName
1337            | BuiltinId::DomEventFileSize
1338            | BuiltinId::DomEventFileType
1339            | BuiltinId::DomEventFileBytes
1340            | BuiltinId::DomListenFlags
1341            | BuiltinId::DomAssignLocation
1342            | BuiltinId::DomJournalDetail
1343            | BuiltinId::DomElementCommand
1344            | BuiltinId::DomClipboardWrite
1345            | BuiltinId::DomDownloadFile
1346            | BuiltinId::DomNotify
1347            | BuiltinId::DomPublish
1348            | BuiltinId::NoteTurn => true,
1349            _ => false,
1350        }
1351    }
1352
1353    /// Every variant, for exhaustive audits — the Syntax Guide's builtin census
1354    /// (`crates/logicaffeine_tests/tests/guide_coverage.rs::every_builtin_has_a_guide_home`)
1355    /// iterates this. Append new variants here; the census's no-wildcard `match`
1356    /// won't compile until the new variant is classified, and its raise-only
1357    /// floor asserts this list never shrinks.
1358    pub const ALL: &'static [BuiltinId] = &[
1359        BuiltinId::Length,
1360        BuiltinId::Contains,
1361        BuiltinId::Format,
1362        BuiltinId::ParseInt,
1363        BuiltinId::ParseFloat,
1364        BuiltinId::Chr,
1365        BuiltinId::Abs,
1366        BuiltinId::Sqrt,
1367        BuiltinId::Min,
1368        BuiltinId::Max,
1369        BuiltinId::Floor,
1370        BuiltinId::Ceil,
1371        BuiltinId::Round,
1372        BuiltinId::Pow,
1373        BuiltinId::Decimal,
1374        BuiltinId::Complex,
1375        BuiltinId::Conjugate,
1376        BuiltinId::RealPart,
1377        BuiltinId::ImagPart,
1378        BuiltinId::Modular,
1379        BuiltinId::Quantity,
1380        BuiltinId::Money,
1381        BuiltinId::SetRate,
1382        BuiltinId::ToCurrency,
1383        BuiltinId::SetRates,
1384        BuiltinId::Uuid,
1385        BuiltinId::UuidNil,
1386        BuiltinId::UuidMax,
1387        BuiltinId::UuidVersion,
1388        BuiltinId::UuidDns,
1389        BuiltinId::UuidUrl,
1390        BuiltinId::UuidOid,
1391        BuiltinId::UuidX500,
1392        BuiltinId::TextBytes,
1393        BuiltinId::TextFromBytes,
1394        BuiltinId::WireBytes,
1395        BuiltinId::CompressBytes,
1396        BuiltinId::DecompressBytes,
1397        BuiltinId::SealBytes,
1398        BuiltinId::OpenBytes,
1399        BuiltinId::FromWireBytes,
1400        BuiltinId::SealFrame,
1401        BuiltinId::OpenFrame,
1402        BuiltinId::ReadWireProgram,
1403        BuiltinId::WriteWireResidual,
1404        BuiltinId::UuidBytes,
1405        BuiltinId::UuidFromBytes,
1406        BuiltinId::Convert,
1407        BuiltinId::ParseTimestamp,
1408        BuiltinId::FormatTimestamp,
1409        BuiltinId::YearOf,
1410        BuiltinId::MonthOf,
1411        BuiltinId::DayOf,
1412        BuiltinId::WeekdayOf,
1413        BuiltinId::HourOf,
1414        BuiltinId::MinuteOf,
1415        BuiltinId::SecondOf,
1416        BuiltinId::WeekOf,
1417        BuiltinId::QuarterOf,
1418        BuiltinId::DateOf,
1419        BuiltinId::TimeOf,
1420        BuiltinId::MakeDate,
1421        BuiltinId::MakeMoment,
1422        BuiltinId::LocalInstant,
1423        BuiltinId::SecondsBetween,
1424        BuiltinId::MonthsBetween,
1425        BuiltinId::YearsBetween,
1426        BuiltinId::AddSeconds,
1427        BuiltinId::InZone,
1428        BuiltinId::Copy,
1429        BuiltinId::CountOnes,
1430        BuiltinId::LeadingZeros,
1431        BuiltinId::TrailingZeros,
1432        BuiltinId::RunAccepted,
1433        BuiltinId::Word32,
1434        BuiltinId::Word64,
1435        BuiltinId::Rotl,
1436        BuiltinId::Rotr,
1437        BuiltinId::Wand,
1438        BuiltinId::Wor,
1439        BuiltinId::Wnot,
1440        BuiltinId::Lanes4Word32Make,
1441        BuiltinId::Lanes4Of,
1442        BuiltinId::SeqOfLanes4W32,
1443        BuiltinId::Sha1Rnds4,
1444        BuiltinId::Sha1Msg1,
1445        BuiltinId::Sha1Msg2,
1446        BuiltinId::Sha1Nexte,
1447        BuiltinId::Lanes16Word8Make,
1448        BuiltinId::SeqOfLanes16W8,
1449        BuiltinId::Splat16Word8,
1450        BuiltinId::Shuffle16,
1451        BuiltinId::ShrBytes16,
1452        BuiltinId::InterleaveLo16,
1453        BuiltinId::InterleaveHi16,
1454        BuiltinId::ByteAdd16,
1455        BuiltinId::Maddubs16,
1456        BuiltinId::Packus16,
1457        BuiltinId::Lanes8Word32,
1458        BuiltinId::SeqOfLanes8,
1459        BuiltinId::Splat8Word32,
1460        BuiltinId::IntOfWord32,
1461        BuiltinId::IntOfWord64,
1462        BuiltinId::Word64Shl,
1463        BuiltinId::Word64Shr,
1464        BuiltinId::Word64And,
1465        BuiltinId::Word32Shr,
1466        BuiltinId::Word16Make,
1467        BuiltinId::IntOfWord16,
1468        BuiltinId::Lanes4Word64,
1469        BuiltinId::SeqOfLanes4,
1470        BuiltinId::Mul32x32To64,
1471        BuiltinId::HsumLanes4,
1472        BuiltinId::Splat4Word64,
1473        BuiltinId::AndNot4,
1474        BuiltinId::Lanes16Word16,
1475        BuiltinId::SeqOfLanes16,
1476        BuiltinId::Splat16Word16,
1477        BuiltinId::Mulhi16,
1478        BuiltinId::Montmul32,
1479        BuiltinId::NttBcastLo,
1480        BuiltinId::NttBcastHi,
1481        BuiltinId::NttBlend,
1482        BuiltinId::MapOf,
1483        BuiltinId::SetOf,
1484        BuiltinId::RepeatSeq,
1485        BuiltinId::ReedSolomonEncode,
1486        BuiltinId::ReedSolomonRecover,
1487        BuiltinId::FecProtect,
1488        BuiltinId::FecRestore,
1489        BuiltinId::DomBody,
1490        BuiltinId::DomCreateElement,
1491        BuiltinId::DomCreateTextNode,
1492        BuiltinId::DomSetText,
1493        BuiltinId::DomSetHtml,
1494        BuiltinId::DomClearChildren,
1495        BuiltinId::DomMoveChildren,
1496        BuiltinId::DomOnMessage,
1497        BuiltinId::DomBeginPaint,
1498        BuiltinId::DomSetAttribute,
1499        BuiltinId::DomAppendChild,
1500        BuiltinId::DomGetText,
1501        BuiltinId::DomGetValue,
1502        BuiltinId::DomSetValue,
1503        BuiltinId::DomSetChecked,
1504        BuiltinId::DomPreventDefault,
1505        BuiltinId::DomApplyPatches,
1506        BuiltinId::StorageSet,
1507        BuiltinId::StorageGet,
1508        BuiltinId::StorageGetOr,
1509        BuiltinId::StorageRemove,
1510        BuiltinId::DomSetStream,
1511        BuiltinId::RtcPeerConnection,
1512        BuiltinId::RtcDataChannel,
1513        BuiltinId::RtcCreateOffer,
1514        BuiltinId::RtcCreateAnswer,
1515        BuiltinId::RtcSetLocal,
1516        BuiltinId::RtcSetRemote,
1517        BuiltinId::RtcAddIce,
1518        BuiltinId::RtcSend,
1519        BuiltinId::DomQuerySelector,
1520        BuiltinId::DomAddEventListener,
1521        BuiltinId::DomEventValue,
1522        BuiltinId::DomEventKey,
1523        BuiltinId::DomEventTarget,
1524        BuiltinId::DomFetchText,
1525        BuiltinId::DomResponseText,
1526        BuiltinId::ReadBytes,
1527        BuiltinId::TryReadBytes,
1528        BuiltinId::SignalNew,
1529        BuiltinId::SignalSet,
1530        BuiltinId::SignalGetInt,
1531        BuiltinId::SignalGetText,
1532        BuiltinId::SignalBeginRender,
1533        BuiltinId::SignalNewText,
1534        BuiltinId::SignalSetText,
1535        BuiltinId::SignalEnterComponent,
1536        BuiltinId::SignalExitComponent,
1537        BuiltinId::SignalNewSeq,
1538        BuiltinId::SignalGetSeq,
1539        BuiltinId::SignalSetSeq,
1540        BuiltinId::SignalNewFloat,
1541        BuiltinId::SignalGetFloat,
1542        BuiltinId::SignalSetFloat,
1543        BuiltinId::FileRead,
1544        BuiltinId::FileWrite,
1545        BuiltinId::RandomInt,
1546        BuiltinId::RandomFloat,
1547        BuiltinId::DomFetchSend,
1548        BuiltinId::DomResponseStatus,
1549        BuiltinId::DomResponseBody,
1550        BuiltinId::DomResponseHeader,
1551        BuiltinId::DomResponseError,
1552        BuiltinId::DomFetchAbort,
1553        BuiltinId::DomFetchSetTimeout,
1554        BuiltinId::DomRoutePath,
1555        BuiltinId::DomRouteQuery,
1556        BuiltinId::DomNavigate,
1557        BuiltinId::DomReplaceRoute,
1558        BuiltinId::DomOnRoute,
1559        BuiltinId::DomSetTitle,
1560        BuiltinId::DomSetHeadHtml,
1561        BuiltinId::DomReload,
1562        BuiltinId::DomGoBack,
1563        BuiltinId::DomGetAttribute,
1564        BuiltinId::DomOnWindowEvent,
1565        BuiltinId::DomScrollGap,
1566        BuiltinId::DomSetInterval,
1567        BuiltinId::DomEventFileName,
1568        BuiltinId::DomElementCommand,
1569        BuiltinId::DomClipboardWrite,
1570        BuiltinId::DomDownloadFile,
1571        BuiltinId::DomNotify,
1572        BuiltinId::DomPublish,
1573        BuiltinId::Fail,
1574        BuiltinId::FailReason,
1575        BuiltinId::Word8Make,
1576        BuiltinId::IntOfWord8,
1577        BuiltinId::NativeKernel,
1578        BuiltinId::NoteTurn,
1579        BuiltinId::InspectUnhandledDynamic,
1580        BuiltinId::DomEventFileSize,
1581        BuiltinId::DomEventFileType,
1582        BuiltinId::DomEventFileBytes,
1583        BuiltinId::DomListenFlags,
1584        BuiltinId::DomAssignLocation,
1585        BuiltinId::DomJournalDetail,
1586        BuiltinId::DomApplyWords,
1587        BuiltinId::DomWakeAfter,
1588        BuiltinId::DomEnterValue,
1589        BuiltinId::DomDispatchEntry,
1590        BuiltinId::VfsReadFile,
1591        BuiltinId::VfsWriteFile,
1592        BuiltinId::VfsMount,
1593        BuiltinId::EnvGet,
1594        BuiltinId::TimeNow,
1595        BuiltinId::EnvHas,
1596        BuiltinId::EnvValue,
1597        BuiltinId::Infinitesimal,
1598        BuiltinId::StandardPart,
1599        BuiltinId::IsInfinitesimal,
1600        BuiltinId::IsLimited,
1601        BuiltinId::InfinitelyClose,
1602        BuiltinId::GeneratorOf,
1603        BuiltinId::LimitOf,
1604        BuiltinId::Provisional,
1605        BuiltinId::AtTheLimit,
1606        BuiltinId::EveryNatural,
1607        BuiltinId::TripCount,
1608        BuiltinId::AffinePower,
1609        BuiltinId::CycleAt,
1610        BuiltinId::SearchCandidates,
1611        BuiltinId::StateSize,
1612        BuiltinId::PolynomialFlow,
1613        BuiltinId::ExactSqrt,
1614        BuiltinId::ExactExp,
1615        BuiltinId::ExactLn,
1616        BuiltinId::ExactPi,
1617        BuiltinId::ExactE,
1618        BuiltinId::ExactOmega,
1619        BuiltinId::HybridFlow,
1620        BuiltinId::FirstExit,
1621        BuiltinId::DefinedReal,
1622        BuiltinId::ExactPower,
1623        BuiltinId::OrderedInfinitesimal,
1624        BuiltinId::SealBox,
1625        BuiltinId::OpenBox,
1626        BuiltinId::SealValueBox,
1627        BuiltinId::OpenValueBox,
1628        BuiltinId::ReadReals,
1629    ];
1630}
1631
1632/// What a call to `beginPaint` is refused with, on every tier.
1633pub const BEGIN_PAINT_RETIRED: &str = "`beginPaint` is gone: a repaint keeps its nodes by drawing through the retained tree — `vdOpen`/`vdText`/`vdClose`, then `vdCommit` and `vdApply` — which an LGX component's view does for you.";
1634
1635/// What a call to `moveChildren` is refused with, on every tier.
1636pub const MOVE_CHILDREN_RETIRED: &str = "`moveChildren` is gone: a caller's children are drawn where the caller is, as a range of the retained tree's tape (`vdRangeOpen`/`vdRangeClose`), and placed where the callee says `{children}` (`vdSlot`) — which an LGX component's view does for you.";
1637
1638/// Every builtin the language no longer has: its id, which keeps its wire position, the spelling a
1639/// program called it by, and the sentence that call is refused in.
1640pub const RETIRED_BUILTINS: &[(BuiltinId, &str, &str)] = &[
1641    (BuiltinId::DomBeginPaint, "beginPaint", BEGIN_PAINT_RETIRED),
1642    (
1643        BuiltinId::DomMoveChildren,
1644        "moveChildren",
1645        MOVE_CHILDREN_RETIRED,
1646    ),
1647];
1648
1649/// The sentence a call to a builtin the language no longer has is refused in, before the program
1650/// runs; `None` for every other name. A program that defines a function of the same name calls its
1651/// own.
1652pub fn retired_builtin(name: &str) -> Option<&'static str> {
1653    RETIRED_BUILTINS
1654        .iter()
1655        .find(|(_, spelling, _)| *spelling == name)
1656        .map(|(_, _, why)| *why)
1657}
1658
1659/// Resolve a function name to a builtin, if it is one.
1660pub fn builtin_from_name(name: &str) -> Option<BuiltinId> {
1661    Some(match name {
1662        "length" => BuiltinId::Length,
1663        "contains" => BuiltinId::Contains,
1664        "format" => BuiltinId::Format,
1665        "mapOf" => BuiltinId::MapOf,
1666        "setOf" => BuiltinId::SetOf,
1667        "repeatSeq" => BuiltinId::RepeatSeq,
1668        "reedSolomonEncode" => BuiltinId::ReedSolomonEncode,
1669        "reedSolomonRecover" => BuiltinId::ReedSolomonRecover,
1670        "fecProtect" => BuiltinId::FecProtect,
1671        "fecRestore" => BuiltinId::FecRestore,
1672        "body" => BuiltinId::DomBody,
1673        "createElement" => BuiltinId::DomCreateElement,
1674        "createTextNode" => BuiltinId::DomCreateTextNode,
1675        "setText" => BuiltinId::DomSetText,
1676        "setHtml" => BuiltinId::DomSetHtml,
1677        "clearChildren" => BuiltinId::DomClearChildren,
1678        "onMessage" => BuiltinId::DomOnMessage,
1679        "setAttribute" => BuiltinId::DomSetAttribute,
1680        "appendChild" => BuiltinId::DomAppendChild,
1681        "getText" => BuiltinId::DomGetText,
1682        "getValue" => BuiltinId::DomGetValue,
1683        "setValue" => BuiltinId::DomSetValue,
1684        "setChecked" => BuiltinId::DomSetChecked,
1685        "preventDefault" => BuiltinId::DomPreventDefault,
1686        "applyPatches" => BuiltinId::DomApplyPatches,
1687        "applyPatchWords" => BuiltinId::DomApplyWords,
1688        "wakeAfter" => BuiltinId::DomWakeAfter,
1689        "storageSet" => BuiltinId::StorageSet,
1690        "storageGet" => BuiltinId::StorageGet,
1691        "storageGetOr" => BuiltinId::StorageGetOr,
1692        "storageRemove" => BuiltinId::StorageRemove,
1693        "setStream" => BuiltinId::DomSetStream,
1694        "peerConnection" => BuiltinId::RtcPeerConnection,
1695        "dataChannel" => BuiltinId::RtcDataChannel,
1696        "createOffer" => BuiltinId::RtcCreateOffer,
1697        "createAnswer" => BuiltinId::RtcCreateAnswer,
1698        "setLocalDescription" => BuiltinId::RtcSetLocal,
1699        "setRemoteDescription" => BuiltinId::RtcSetRemote,
1700        "addIceCandidate" => BuiltinId::RtcAddIce,
1701        "channelSend" => BuiltinId::RtcSend,
1702        "querySelector" => BuiltinId::DomQuerySelector,
1703        "addEventListener" => BuiltinId::DomAddEventListener,
1704        "eventValue" => BuiltinId::DomEventValue,
1705        "eventKey" => BuiltinId::DomEventKey,
1706        "eventTarget" => BuiltinId::DomEventTarget,
1707        "fetchText" => BuiltinId::DomFetchText,
1708        "responseText" => BuiltinId::DomResponseText,
1709        "fetchSend" => BuiltinId::DomFetchSend,
1710        "responseStatus" => BuiltinId::DomResponseStatus,
1711        "responseBody" => BuiltinId::DomResponseBody,
1712        "responseHeader" => BuiltinId::DomResponseHeader,
1713        "responseError" => BuiltinId::DomResponseError,
1714        "fetchAbort" => BuiltinId::DomFetchAbort,
1715        "fetchSetTimeout" => BuiltinId::DomFetchSetTimeout,
1716        "routePath" => BuiltinId::DomRoutePath,
1717        "routeQuery" => BuiltinId::DomRouteQuery,
1718        "navigate" => BuiltinId::DomNavigate,
1719        "replaceRoute" => BuiltinId::DomReplaceRoute,
1720        "onRoute" => BuiltinId::DomOnRoute,
1721        "setTitle" => BuiltinId::DomSetTitle,
1722        "setHeadHtml" => BuiltinId::DomSetHeadHtml,
1723        "reloadPage" => BuiltinId::DomReload,
1724        "goBack" => BuiltinId::DomGoBack,
1725        "getAttribute" => BuiltinId::DomGetAttribute,
1726        "onWindowEvent" => BuiltinId::DomOnWindowEvent,
1727        "scrollGap" => BuiltinId::DomScrollGap,
1728        "setInterval" => BuiltinId::DomSetInterval,
1729        "eventFileName" => BuiltinId::DomEventFileName,
1730        "eventFileSize" => BuiltinId::DomEventFileSize,
1731        "eventFileType" => BuiltinId::DomEventFileType,
1732        "eventFileBytes" => BuiltinId::DomEventFileBytes,
1733        "listenFlags" => BuiltinId::DomListenFlags,
1734        "assignLocation" => BuiltinId::DomAssignLocation,
1735        "journalDetail" => BuiltinId::DomJournalDetail,
1736        "elementCommand" => BuiltinId::DomElementCommand,
1737        "clipboardWrite" => BuiltinId::DomClipboardWrite,
1738        "downloadFile" => BuiltinId::DomDownloadFile,
1739        "notify" => BuiltinId::DomNotify,
1740        "publish" => BuiltinId::DomPublish,
1741        "readBytes" => BuiltinId::ReadBytes,
1742        "tryReadBytes" => BuiltinId::TryReadBytes,
1743        "parseInt" => BuiltinId::ParseInt,
1744        "parseFloat" => BuiltinId::ParseFloat,
1745        "chr" => BuiltinId::Chr,
1746        "abs" => BuiltinId::Abs,
1747        "sqrt" => BuiltinId::Sqrt,
1748        "min" => BuiltinId::Min,
1749        "max" => BuiltinId::Max,
1750        "floor" => BuiltinId::Floor,
1751        "ceil" => BuiltinId::Ceil,
1752        "round" => BuiltinId::Round,
1753        "pow" => BuiltinId::Pow,
1754        "decimal" => BuiltinId::Decimal,
1755        "complex" => BuiltinId::Complex,
1756        "conjugate" => BuiltinId::Conjugate,
1757        "infinitesimal" => BuiltinId::Infinitesimal,
1758        "standardPart" => BuiltinId::StandardPart,
1759        "isInfinitesimal" => BuiltinId::IsInfinitesimal,
1760        "isLimited" => BuiltinId::IsLimited,
1761        "infinitelyClose" => BuiltinId::InfinitelyClose,
1762        "generatorOf" => BuiltinId::GeneratorOf,
1763        "limitOf" => BuiltinId::LimitOf,
1764        "provisional" => BuiltinId::Provisional,
1765        "atTheLimit" => BuiltinId::AtTheLimit,
1766        "everyNatural" => BuiltinId::EveryNatural,
1767        "exactSqrt" => BuiltinId::ExactSqrt,
1768        "exactExp" => BuiltinId::ExactExp,
1769        "exactLn" => BuiltinId::ExactLn,
1770        "exactPi" => BuiltinId::ExactPi,
1771        "exactE" => BuiltinId::ExactE,
1772        "exactOmega" => BuiltinId::ExactOmega,
1773        "tripCount" => BuiltinId::TripCount,
1774        "affinePower" => BuiltinId::AffinePower,
1775        "cycleAt" => BuiltinId::CycleAt,
1776        "searchCandidates" => BuiltinId::SearchCandidates,
1777        "stateSize" => BuiltinId::StateSize,
1778        "polynomialFlow" => BuiltinId::PolynomialFlow,
1779        "hybridFlow" => BuiltinId::HybridFlow,
1780        "firstExit" => BuiltinId::FirstExit,
1781        "exactPower" => BuiltinId::ExactPower,
1782        "orderedInfinitesimal" => BuiltinId::OrderedInfinitesimal,
1783        "definedReal" => BuiltinId::DefinedReal,
1784        "re" => BuiltinId::RealPart,
1785        "im" => BuiltinId::ImagPart,
1786        "modular" => BuiltinId::Modular,
1787        "quantity" => BuiltinId::Quantity,
1788        "money" => BuiltinId::Money,
1789        "set_rate" => BuiltinId::SetRate,
1790        "set_rates" => BuiltinId::SetRates,
1791        "to_currency" => BuiltinId::ToCurrency,
1792        "uuid" => BuiltinId::Uuid,
1793        "uuid_nil" => BuiltinId::UuidNil,
1794        "uuid_max" => BuiltinId::UuidMax,
1795        "uuid_version" => BuiltinId::UuidVersion,
1796        "uuid_dns" => BuiltinId::UuidDns,
1797        "uuid_url" => BuiltinId::UuidUrl,
1798        "uuid_oid" => BuiltinId::UuidOid,
1799        "uuid_x500" => BuiltinId::UuidX500,
1800        "text_bytes" => BuiltinId::TextBytes,
1801        "text_from_bytes" => BuiltinId::TextFromBytes,
1802        "wireBytes" => BuiltinId::WireBytes,
1803        "compressBytes" => BuiltinId::CompressBytes,
1804        "decompressBytes" => BuiltinId::DecompressBytes,
1805        "sealBytes" => BuiltinId::SealBytes,
1806        "openBytes" => BuiltinId::OpenBytes,
1807        "sealBox" => BuiltinId::SealBox,
1808        "openBox" => BuiltinId::OpenBox,
1809        "sealValueBox" => BuiltinId::SealValueBox,
1810        "openValueBox" => BuiltinId::OpenValueBox,
1811        "readReals" => BuiltinId::ReadReals,
1812        "fromWireBytes" => BuiltinId::FromWireBytes,
1813        "sealFrame" => BuiltinId::SealFrame,
1814        "openFrame" => BuiltinId::OpenFrame,
1815        "readWireProgram" => BuiltinId::ReadWireProgram,
1816        "writeWireResidual" => BuiltinId::WriteWireResidual,
1817        "uuid_bytes" => BuiltinId::UuidBytes,
1818        "uuid_from_bytes" => BuiltinId::UuidFromBytes,
1819        "convert" => BuiltinId::Convert,
1820        "parse_timestamp" => BuiltinId::ParseTimestamp,
1821        "format_timestamp" => BuiltinId::FormatTimestamp,
1822        "year_of" => BuiltinId::YearOf,
1823        "month_of" => BuiltinId::MonthOf,
1824        "day_of" => BuiltinId::DayOf,
1825        "weekday_of" => BuiltinId::WeekdayOf,
1826        "hour_of" => BuiltinId::HourOf,
1827        "minute_of" => BuiltinId::MinuteOf,
1828        "second_of" => BuiltinId::SecondOf,
1829        "week_of" => BuiltinId::WeekOf,
1830        "quarter_of" => BuiltinId::QuarterOf,
1831        "date_of" => BuiltinId::DateOf,
1832        "time_of" => BuiltinId::TimeOf,
1833        "makeDate" => BuiltinId::MakeDate,
1834        "makeMoment" => BuiltinId::MakeMoment,
1835        "local_instant" => BuiltinId::LocalInstant,
1836        "seconds_between" => BuiltinId::SecondsBetween,
1837        "months_between" => BuiltinId::MonthsBetween,
1838        "years_between" => BuiltinId::YearsBetween,
1839        "add_seconds" => BuiltinId::AddSeconds,
1840        "in_zone" => BuiltinId::InZone,
1841        "copy" => BuiltinId::Copy,
1842        "__logos_fail" => BuiltinId::Fail,
1843        "__logos_fail_reason" => BuiltinId::FailReason,
1844        "count_ones" => BuiltinId::CountOnes,
1845        "leading_zeros" => BuiltinId::LeadingZeros,
1846        "trailing_zeros" => BuiltinId::TrailingZeros,
1847        "run_accepted" => BuiltinId::RunAccepted,
1848        "word32" => BuiltinId::Word32,
1849        "word64" => BuiltinId::Word64,
1850        "lanes8Word32" => BuiltinId::Lanes8Word32,
1851        "seqOfLanes8" => BuiltinId::SeqOfLanes8,
1852        "splat8Word32" => BuiltinId::Splat8Word32,
1853        "intOfWord32" => BuiltinId::IntOfWord32,
1854        "intOfWord64" => BuiltinId::IntOfWord64,
1855        "word64Shl" => BuiltinId::Word64Shl,
1856        "word64Shr" => BuiltinId::Word64Shr,
1857        "word32Shr" => BuiltinId::Word32Shr,
1858        "word64And" => BuiltinId::Word64And,
1859        "word16" => BuiltinId::Word16Make,
1860        "word8" => BuiltinId::Word8Make,
1861        "intOfWord8" => BuiltinId::IntOfWord8,
1862        "__logos_native_kernel" => BuiltinId::NativeKernel,
1863        "noteTurn" => BuiltinId::NoteTurn,
1864        "intOfWord16" => BuiltinId::IntOfWord16,
1865        "lanes4Word64" => BuiltinId::Lanes4Word64,
1866        "seqOfLanes4" => BuiltinId::SeqOfLanes4,
1867        "mul32x32to64" => BuiltinId::Mul32x32To64,
1868        "hsumLanes4" => BuiltinId::HsumLanes4,
1869        "splat4Word64" => BuiltinId::Splat4Word64,
1870        "andNot4" => BuiltinId::AndNot4,
1871        "lanes16Word16" => BuiltinId::Lanes16Word16,
1872        "seqOfLanes16" => BuiltinId::SeqOfLanes16,
1873        "splat16Word16" => BuiltinId::Splat16Word16,
1874        "mulhi16" => BuiltinId::Mulhi16,
1875        "montmul32" => BuiltinId::Montmul32,
1876        "nttBcastLo" => BuiltinId::NttBcastLo,
1877        "nttBcastHi" => BuiltinId::NttBcastHi,
1878        "nttBlend" => BuiltinId::NttBlend,
1879        "rotl" => BuiltinId::Rotl,
1880        "word_and" => BuiltinId::Wand,
1881        "word_or" => BuiltinId::Wor,
1882        "word_not" => BuiltinId::Wnot,
1883        "lanes4Word32" => BuiltinId::Lanes4Word32Make,
1884        "lanes4Of" => BuiltinId::Lanes4Of,
1885        "seqOfLanes4W32" => BuiltinId::SeqOfLanes4W32,
1886        "sha1rnds4" => BuiltinId::Sha1Rnds4,
1887        "sha1msg1" => BuiltinId::Sha1Msg1,
1888        "sha1msg2" => BuiltinId::Sha1Msg2,
1889        "sha1nexte" => BuiltinId::Sha1Nexte,
1890        "lanes16Word8" => BuiltinId::Lanes16Word8Make,
1891        "seqOfLanes16W8" => BuiltinId::SeqOfLanes16W8,
1892        "splat16Word8" => BuiltinId::Splat16Word8,
1893        "shuffle16" => BuiltinId::Shuffle16,
1894        "shrBytes16" => BuiltinId::ShrBytes16,
1895        "interleaveLo16" => BuiltinId::InterleaveLo16,
1896        "interleaveHi16" => BuiltinId::InterleaveHi16,
1897        "byteAdd16" => BuiltinId::ByteAdd16,
1898        "maddubs16" => BuiltinId::Maddubs16,
1899        "packus16" => BuiltinId::Packus16,
1900        "rotr" => BuiltinId::Rotr,
1901        _ => return None,
1902    })
1903}
1904
1905/// Check the call's arity BEFORE evaluating arguments. `format` accepts any
1906/// arity (it reads only its first argument, or none).
1907pub fn check_arity(id: BuiltinId, n: usize) -> Result<(), String> {
1908    let expected: usize = match id {
1909        BuiltinId::Format => return Ok(()),
1910        // The kernel code, then the kernel's own arguments — the kernel checks its arity.
1911        BuiltinId::NativeKernel => {
1912            if n == 0 {
1913                return Err("a native kernel call carries its kernel code".to_string());
1914            }
1915            return Ok(());
1916        }
1917        BuiltinId::MapOf => {
1918            if n == 0 || n % 2 != 0 {
1919                return Err(format!(
1920                    "mapOf takes flat key/value pairs (an even, nonzero number of arguments), got {}",
1921                    n
1922                ));
1923            }
1924            return Ok(());
1925        }
1926        BuiltinId::SetOf => {
1927            if n == 0 {
1928                return Err("setOf takes at least one element (an empty set is `{} of T`)".to_string());
1929            }
1930            return Ok(());
1931        }
1932        BuiltinId::Infinitesimal => {
1933            if n < 2 {
1934                return Err("infinitesimal takes a name, a modulus and the allowed residues".to_string());
1935            }
1936            return Ok(());
1937        }
1938        BuiltinId::OrderedInfinitesimal => {
1939            if n < 4 {
1940                return Err(
1941                    "orderedInfinitesimal takes a name, the infinitesimals above and below, a modulus and the allowed residues"
1942                        .to_string(),
1943                );
1944            }
1945            return Ok(());
1946        }
1947        BuiltinId::StandardPart | BuiltinId::IsInfinitesimal | BuiltinId::IsLimited => {
1948            if !(1..=2).contains(&n) {
1949                let name = id.extension().expect("a builtin of the exact extension").name();
1950                return Err(format!(
1951                    "{name} takes a value and, relative to an infinitesimal, that infinitesimal; got {n} arguments"
1952                ));
1953            }
1954            return Ok(());
1955        }
1956        BuiltinId::InfinitelyClose => {
1957            if !(2..=3).contains(&n) {
1958                return Err(format!(
1959                    "infinitelyClose takes two values and, relative to an infinitesimal, that infinitesimal; got {n} arguments"
1960                ));
1961            }
1962            return Ok(());
1963        }
1964        BuiltinId::LimitOf | BuiltinId::SearchCandidates | BuiltinId::ExactPower => 2,
1965        BuiltinId::Provisional
1966        | BuiltinId::AffinePower
1967        | BuiltinId::CycleAt
1968        | BuiltinId::PolynomialFlow
1969        | BuiltinId::HybridFlow
1970        | BuiltinId::FirstExit => 3,
1971        BuiltinId::TripCount | BuiltinId::DefinedReal => 4,
1972        BuiltinId::ExactPi | BuiltinId::ExactE | BuiltinId::ExactOmega => 0,
1973        BuiltinId::Min | BuiltinId::Max | BuiltinId::Pow => 2,
1974        BuiltinId::Contains => 2,
1975        BuiltinId::RepeatSeq => 2,
1976        BuiltinId::ReedSolomonEncode | BuiltinId::ReedSolomonRecover => 2,
1977        BuiltinId::FecRestore => 2,
1978        BuiltinId::FecProtect => 3,
1979        BuiltinId::SealBytes | BuiltinId::OpenBytes => 3,
1980        BuiltinId::SealBox
1981        | BuiltinId::OpenBox
1982        | BuiltinId::SealValueBox
1983        | BuiltinId::OpenValueBox => 2,
1984        BuiltinId::SealFrame | BuiltinId::OpenFrame => 3,
1985        BuiltinId::Complex => 2,
1986        BuiltinId::Modular => 2,
1987        BuiltinId::Quantity | BuiltinId::Convert | BuiltinId::Money => 2,
1988        BuiltinId::SetRate | BuiltinId::ToCurrency => 2,
1989        BuiltinId::SetRates => 1,
1990        BuiltinId::UuidNil
1991        | BuiltinId::UuidMax
1992        | BuiltinId::UuidDns
1993        | BuiltinId::UuidUrl
1994        | BuiltinId::UuidOid
1995        | BuiltinId::ReadWireProgram
1996        | BuiltinId::UuidX500 => 0,
1997        BuiltinId::Uuid | BuiltinId::UuidVersion => 1,
1998        BuiltinId::TextBytes | BuiltinId::TextFromBytes | BuiltinId::WireBytes | BuiltinId::FromWireBytes | BuiltinId::CompressBytes | BuiltinId::DecompressBytes | BuiltinId::WriteWireResidual | BuiltinId::UuidBytes | BuiltinId::UuidFromBytes => 1,
1999        BuiltinId::SecondsBetween | BuiltinId::AddSeconds | BuiltinId::InZone => 2,
2000        BuiltinId::MonthsBetween | BuiltinId::YearsBetween => 2,
2001        BuiltinId::MakeDate => 3,
2002        BuiltinId::MakeMoment => 6,
2003        BuiltinId::LocalInstant => 2,
2004        BuiltinId::Rotl | BuiltinId::Rotr => 2,
2005        BuiltinId::Wand | BuiltinId::Wor => 2,
2006        BuiltinId::Wnot => 1,
2007        BuiltinId::Lanes4Word32Make | BuiltinId::SeqOfLanes4W32 => 1,
2008        BuiltinId::AndNot4 => 2,
2009        BuiltinId::Lanes4Of => 4,
2010        BuiltinId::Sha1Rnds4 => 3,
2011        BuiltinId::Sha1Msg1 | BuiltinId::Sha1Msg2 | BuiltinId::Sha1Nexte => 2,
2012        BuiltinId::Lanes16Word8Make | BuiltinId::SeqOfLanes16W8 | BuiltinId::Splat16Word8 => 1,
2013        BuiltinId::Shuffle16 | BuiltinId::ShrBytes16 => 2,
2014        BuiltinId::InterleaveLo16 | BuiltinId::InterleaveHi16 => 2,
2015        BuiltinId::ByteAdd16 | BuiltinId::Maddubs16 | BuiltinId::Packus16 => 2,
2016        BuiltinId::Mul32x32To64 => 2,
2017        BuiltinId::DomBody => 0,
2018        BuiltinId::DomCreateElement
2019        | BuiltinId::DomCreateTextNode
2020        | BuiltinId::DomGetText
2021        | BuiltinId::DomGetValue
2022        | BuiltinId::DomClearChildren
2023        | BuiltinId::DomApplyPatches
2024        | BuiltinId::DomWakeAfter
2025        | BuiltinId::DomQuerySelector => 1,
2026        BuiltinId::DomApplyWords => 4,
2027        BuiltinId::DomSetText
2028        | BuiltinId::DomSetHtml
2029        | BuiltinId::DomMoveChildren
2030        | BuiltinId::DomOnMessage
2031        | BuiltinId::DomAppendChild
2032        | BuiltinId::DomSetValue
2033        | BuiltinId::DomSetChecked
2034        // `preventDefault(element, event)` — the element the listener is on, and which event's
2035        // default to suppress. Omitting it here left the fall-through default of ONE, so every
2036        // caller of the `.prevent` lowering was refused before it ran: the VM said so by name and
2037        // the wasm module trapped at mount. See `prevent_default_arity_lock`.
2038        | BuiltinId::DomPreventDefault
2039        | BuiltinId::DomSetStream => 2,
2040        BuiltinId::RtcPeerConnection => 0,
2041        BuiltinId::RtcCreateOffer | BuiltinId::RtcCreateAnswer => 1,
2042        BuiltinId::RtcDataChannel
2043        | BuiltinId::RtcSetLocal
2044        | BuiltinId::RtcSetRemote
2045        | BuiltinId::RtcAddIce
2046        | BuiltinId::RtcSend => 2,
2047        BuiltinId::StorageGet | BuiltinId::StorageRemove => 2,
2048        BuiltinId::StorageSet | BuiltinId::StorageGetOr => 3,
2049        BuiltinId::DomSetAttribute | BuiltinId::DomAddEventListener | BuiltinId::DomListenFlags | BuiltinId::DomEnterValue => 3,
2050        BuiltinId::DomDispatchEntry => 6,
2051        BuiltinId::DomGetAttribute
2052        | BuiltinId::DomOnWindowEvent
2053        | BuiltinId::DomElementCommand => 2,
2054        BuiltinId::DomScrollGap
2055        | BuiltinId::DomEventFileName
2056        | BuiltinId::DomClipboardWrite => 1,
2057        BuiltinId::DomDownloadFile | BuiltinId::DomNotify | BuiltinId::DomPublish => 2,
2058        BuiltinId::NoteTurn => 4,
2059        BuiltinId::DomSetInterval => 2,
2060        BuiltinId::DomEventValue | BuiltinId::DomEventKey | BuiltinId::DomEventTarget => 1,
2061        BuiltinId::DomFetchText => 2,
2062        BuiltinId::DomResponseText | BuiltinId::DomBeginPaint => 0,
2063        BuiltinId::DomFetchSend => 5,
2064        BuiltinId::DomResponseStatus
2065        | BuiltinId::DomResponseBody
2066        | BuiltinId::DomResponseError
2067        | BuiltinId::DomFetchAbort => 1,
2068        BuiltinId::DomResponseHeader | BuiltinId::DomFetchSetTimeout => 2,
2069        BuiltinId::DomRoutePath | BuiltinId::DomReload | BuiltinId::DomGoBack | BuiltinId::DomJournalDetail => 0,
2070        BuiltinId::DomRouteQuery
2071        | BuiltinId::DomNavigate
2072        | BuiltinId::DomReplaceRoute
2073        | BuiltinId::DomOnRoute
2074        | BuiltinId::DomSetTitle
2075        | BuiltinId::DomSetHeadHtml => 1,
2076        BuiltinId::ReadBytes | BuiltinId::TryReadBytes | BuiltinId::ReadReals => 1,
2077        BuiltinId::FileRead => 1,
2078        BuiltinId::FileWrite => 2,
2079        BuiltinId::VfsWriteFile => 2,
2080        BuiltinId::RandomInt => 2,
2081        BuiltinId::RandomFloat => 0,
2082        BuiltinId::EnvGet | BuiltinId::EnvHas | BuiltinId::EnvValue => 1,
2083        BuiltinId::TimeNow => 0,
2084        // The reactive-signal dialect is retired (see `execute_builtin`); wire-frozen, kept exact
2085        // so an old encoded program's genuinely-correct call is never misreported as wrong-arity.
2086        BuiltinId::SignalNew | BuiltinId::SignalGetInt | BuiltinId::SignalGetText | BuiltinId::SignalNewText => 1,
2087        BuiltinId::SignalSet | BuiltinId::SignalSetText => 2,
2088        BuiltinId::SignalBeginRender | BuiltinId::SignalExitComponent => 0,
2089        BuiltinId::SignalEnterComponent => 1,
2090        BuiltinId::SignalNewSeq | BuiltinId::SignalGetSeq => 1,
2091        BuiltinId::SignalSetSeq => 2,
2092        BuiltinId::SignalNewFloat | BuiltinId::SignalGetFloat => 1,
2093        BuiltinId::SignalSetFloat => 2,
2094        BuiltinId::Mulhi16 => 2,
2095        BuiltinId::Montmul32 => 4,
2096        BuiltinId::Word64Shl | BuiltinId::Word64Shr | BuiltinId::Word64And => 2,
2097        BuiltinId::Word32Shr => 2,
2098        BuiltinId::NttBcastLo | BuiltinId::NttBcastHi => 2,
2099        BuiltinId::NttBlend => 3,
2100        // run_accepted(fn, arg, lo, hi): the shipped computation + the argument + the
2101        // inclusive bounds of the acceptance contract.
2102        BuiltinId::RunAccepted => 4,
2103        _ => 1,
2104    };
2105    if n != expected {
2106        let name = match id {
2107            BuiltinId::Length => "length",
2108            BuiltinId::Contains => "contains",
2109            BuiltinId::Format => unreachable!(),
2110            // MapOf/SetOf return early above (variadic with their own errors).
2111            BuiltinId::MapOf | BuiltinId::SetOf => unreachable!(),
2112            BuiltinId::RepeatSeq => "repeatSeq",
2113            BuiltinId::ReedSolomonEncode => "reedSolomonEncode",
2114            BuiltinId::ReedSolomonRecover => "reedSolomonRecover",
2115            BuiltinId::FecProtect => "fecProtect",
2116            BuiltinId::FecRestore => "fecRestore",
2117            BuiltinId::ParseInt => "parseInt",
2118            BuiltinId::ParseFloat => "parseFloat",
2119            BuiltinId::Chr => "chr",
2120            BuiltinId::Abs => "abs",
2121            BuiltinId::Sqrt => "sqrt",
2122            BuiltinId::Min => "min",
2123            BuiltinId::Max => "max",
2124            BuiltinId::Floor => "floor",
2125            BuiltinId::Ceil => "ceil",
2126            BuiltinId::Round => "round",
2127            BuiltinId::Pow => "pow",
2128            BuiltinId::Decimal => "decimal",
2129            BuiltinId::Complex => "complex",
2130            BuiltinId::Conjugate => "conjugate",
2131            BuiltinId::Infinitesimal => "infinitesimal",
2132            BuiltinId::StandardPart => "standardPart",
2133            BuiltinId::IsInfinitesimal => "isInfinitesimal",
2134            BuiltinId::IsLimited => "isLimited",
2135            BuiltinId::InfinitelyClose => "infinitelyClose",
2136            BuiltinId::GeneratorOf => "generatorOf",
2137            BuiltinId::LimitOf => "limitOf",
2138            BuiltinId::Provisional => "provisional",
2139            BuiltinId::AtTheLimit => "atTheLimit",
2140            BuiltinId::EveryNatural => "everyNatural",
2141            BuiltinId::ExactSqrt => "exactSqrt",
2142            BuiltinId::ExactExp => "exactExp",
2143            BuiltinId::ExactLn => "exactLn",
2144            BuiltinId::ExactPi => "exactPi",
2145            BuiltinId::ExactE => "exactE",
2146            BuiltinId::ExactOmega => "exactOmega",
2147            BuiltinId::TripCount => "tripCount",
2148            BuiltinId::AffinePower => "affinePower",
2149            BuiltinId::CycleAt => "cycleAt",
2150            BuiltinId::SearchCandidates => "searchCandidates",
2151            BuiltinId::StateSize => "stateSize",
2152            BuiltinId::PolynomialFlow => "polynomialFlow",
2153            BuiltinId::HybridFlow => "hybridFlow",
2154            BuiltinId::FirstExit => "firstExit",
2155            BuiltinId::ExactPower => "exactPower",
2156            BuiltinId::OrderedInfinitesimal => "orderedInfinitesimal",
2157            BuiltinId::DefinedReal => "definedReal",
2158            BuiltinId::RealPart => "re",
2159            BuiltinId::ImagPart => "im",
2160            BuiltinId::Modular => "modular",
2161            BuiltinId::Quantity => "quantity",
2162            BuiltinId::Money => "money",
2163            BuiltinId::SetRate => "set_rate",
2164            BuiltinId::SetRates => "set_rates",
2165            BuiltinId::ToCurrency => "to_currency",
2166            BuiltinId::Uuid => "uuid",
2167            BuiltinId::UuidNil => "uuid_nil",
2168            BuiltinId::UuidMax => "uuid_max",
2169            BuiltinId::UuidVersion => "uuid_version",
2170            BuiltinId::UuidDns => "uuid_dns",
2171            BuiltinId::UuidUrl => "uuid_url",
2172            BuiltinId::UuidOid => "uuid_oid",
2173            BuiltinId::UuidX500 => "uuid_x500",
2174            BuiltinId::TextBytes => "text_bytes",
2175            BuiltinId::TextFromBytes => "text_from_bytes",
2176            BuiltinId::WireBytes => "wireBytes",
2177            BuiltinId::CompressBytes => "compressBytes",
2178            BuiltinId::DecompressBytes => "decompressBytes",
2179            BuiltinId::SealBytes => "sealBytes",
2180            BuiltinId::OpenBytes => "openBytes",
2181            BuiltinId::SealBox => "sealBox",
2182            BuiltinId::OpenBox => "openBox",
2183            BuiltinId::SealValueBox => "sealValueBox",
2184            BuiltinId::OpenValueBox => "openValueBox",
2185            BuiltinId::ReadReals => "readReals",
2186            BuiltinId::FromWireBytes => "fromWireBytes",
2187            BuiltinId::SealFrame => "sealFrame",
2188            BuiltinId::OpenFrame => "openFrame",
2189            BuiltinId::ReadWireProgram => "readWireProgram",
2190            BuiltinId::WriteWireResidual => "writeWireResidual",
2191            BuiltinId::UuidBytes => "uuid_bytes",
2192            BuiltinId::UuidFromBytes => "uuid_from_bytes",
2193            BuiltinId::Convert => "convert",
2194            BuiltinId::ParseTimestamp => "parse_timestamp",
2195            BuiltinId::FormatTimestamp => "format_timestamp",
2196            BuiltinId::YearOf => "year_of",
2197            BuiltinId::MonthOf => "month_of",
2198            BuiltinId::DayOf => "day_of",
2199            BuiltinId::WeekdayOf => "weekday_of",
2200            BuiltinId::HourOf => "hour_of",
2201            BuiltinId::MinuteOf => "minute_of",
2202            BuiltinId::SecondOf => "second_of",
2203            BuiltinId::WeekOf => "week_of",
2204            BuiltinId::QuarterOf => "quarter_of",
2205            BuiltinId::DateOf => "date_of",
2206            BuiltinId::TimeOf => "time_of",
2207            BuiltinId::MakeDate => "makeDate",
2208            BuiltinId::MakeMoment => "makeMoment",
2209            BuiltinId::LocalInstant => "local_instant",
2210            BuiltinId::SecondsBetween => "seconds_between",
2211            BuiltinId::MonthsBetween => "months_between",
2212            BuiltinId::YearsBetween => "years_between",
2213            BuiltinId::AddSeconds => "add_seconds",
2214            BuiltinId::InZone => "in_zone",
2215            BuiltinId::Copy => "copy",
2216            BuiltinId::Fail => "__logos_fail",
2217            BuiltinId::FailReason => "__logos_fail_reason",
2218            BuiltinId::CountOnes => "count_ones",
2219            BuiltinId::LeadingZeros => "leading_zeros",
2220            BuiltinId::TrailingZeros => "trailing_zeros",
2221            BuiltinId::RunAccepted => "run_accepted",
2222            BuiltinId::Word32 => "word32",
2223            BuiltinId::Word64 => "word64",
2224            BuiltinId::Lanes8Word32 => "lanes8Word32",
2225            BuiltinId::SeqOfLanes8 => "seqOfLanes8",
2226            BuiltinId::Splat8Word32 => "splat8Word32",
2227            BuiltinId::IntOfWord32 => "intOfWord32",
2228            BuiltinId::IntOfWord64 => "intOfWord64",
2229            BuiltinId::Word64Shl => "word64Shl",
2230            BuiltinId::Word64Shr => "word64Shr",
2231            BuiltinId::Word32Shr => "word32Shr",
2232            BuiltinId::Word64And => "word64And",
2233            BuiltinId::Word16Make => "word16",
2234            BuiltinId::Word8Make => "word8",
2235            BuiltinId::IntOfWord8 => "intOfWord8",
2236            BuiltinId::NativeKernel => "__logos_native_kernel",
2237            BuiltinId::NoteTurn => "noteTurn",
2238            BuiltinId::IntOfWord16 => "intOfWord16",
2239            BuiltinId::Lanes4Word64 => "lanes4Word64",
2240            BuiltinId::SeqOfLanes4 => "seqOfLanes4",
2241            BuiltinId::Mul32x32To64 => "mul32x32to64",
2242            BuiltinId::HsumLanes4 => "hsumLanes4",
2243            BuiltinId::Splat4Word64 => "splat4Word64",
2244            BuiltinId::AndNot4 => "andNot4",
2245            BuiltinId::Lanes16Word16 => "lanes16Word16",
2246            BuiltinId::SeqOfLanes16 => "seqOfLanes16",
2247            BuiltinId::Splat16Word16 => "splat16Word16",
2248            BuiltinId::Mulhi16 => "mulhi16",
2249            BuiltinId::Montmul32 => "montmul32",
2250            BuiltinId::NttBcastLo => "nttBcastLo",
2251            BuiltinId::NttBcastHi => "nttBcastHi",
2252            BuiltinId::NttBlend => "nttBlend",
2253            BuiltinId::Rotl => "rotl",
2254            BuiltinId::Wand => "word_and",
2255            BuiltinId::Wor => "word_or",
2256            BuiltinId::Wnot => "word_not",
2257            BuiltinId::Lanes4Word32Make => "lanes4Word32",
2258            BuiltinId::Lanes4Of => "lanes4Of",
2259            BuiltinId::SeqOfLanes4W32 => "seqOfLanes4W32",
2260            BuiltinId::Sha1Rnds4 => "sha1rnds4",
2261            BuiltinId::Sha1Msg1 => "sha1msg1",
2262            BuiltinId::Sha1Msg2 => "sha1msg2",
2263            BuiltinId::Sha1Nexte => "sha1nexte",
2264            BuiltinId::Lanes16Word8Make => "lanes16Word8",
2265            BuiltinId::SeqOfLanes16W8 => "seqOfLanes16W8",
2266            BuiltinId::Splat16Word8 => "splat16Word8",
2267            BuiltinId::Shuffle16 => "shuffle16",
2268            BuiltinId::ShrBytes16 => "shrBytes16",
2269            BuiltinId::InterleaveLo16 => "interleaveLo16",
2270            BuiltinId::InterleaveHi16 => "interleaveHi16",
2271            BuiltinId::ByteAdd16 => "byteAdd16",
2272            BuiltinId::Maddubs16 => "maddubs16",
2273            BuiltinId::Packus16 => "packus16",
2274            BuiltinId::Rotr => "rotr",
2275            BuiltinId::DomBody => "body",
2276            BuiltinId::DomCreateElement => "createElement",
2277            BuiltinId::DomCreateTextNode => "createTextNode",
2278            BuiltinId::DomSetText => "setText",
2279            BuiltinId::DomSetHtml => "setHtml",
2280            BuiltinId::DomClearChildren => "clearChildren",
2281            BuiltinId::DomMoveChildren => "moveChildren",
2282            BuiltinId::DomOnMessage => "onMessage",
2283            BuiltinId::DomBeginPaint => "beginPaint",
2284            BuiltinId::DomSetAttribute => "setAttribute",
2285            BuiltinId::DomAppendChild => "appendChild",
2286            BuiltinId::DomGetText => "getText",
2287            BuiltinId::DomGetValue => "getValue",
2288            BuiltinId::DomSetValue => "setValue",
2289            BuiltinId::DomSetChecked => "setChecked",
2290            BuiltinId::DomPreventDefault => "preventDefault",
2291            BuiltinId::DomApplyPatches => "applyPatches",
2292            BuiltinId::DomApplyWords => "applyPatchWords",
2293            BuiltinId::DomWakeAfter => "wakeAfter",
2294            BuiltinId::DomEnterValue => "enterValue",
2295            BuiltinId::DomDispatchEntry => "dispatchEntry",
2296            BuiltinId::StorageSet => "storageSet",
2297            BuiltinId::StorageGet => "storageGet",
2298            BuiltinId::StorageGetOr => "storageGetOr",
2299            BuiltinId::StorageRemove => "storageRemove",
2300            BuiltinId::DomSetStream => "setStream",
2301            BuiltinId::RtcPeerConnection => "peerConnection",
2302            BuiltinId::RtcDataChannel => "dataChannel",
2303            BuiltinId::RtcCreateOffer => "createOffer",
2304            BuiltinId::RtcCreateAnswer => "createAnswer",
2305            BuiltinId::RtcSetLocal => "setLocalDescription",
2306            BuiltinId::RtcSetRemote => "setRemoteDescription",
2307            BuiltinId::RtcAddIce => "addIceCandidate",
2308            BuiltinId::RtcSend => "channelSend",
2309            BuiltinId::DomQuerySelector => "querySelector",
2310            BuiltinId::DomAddEventListener => "addEventListener",
2311            BuiltinId::DomEventValue => "eventValue",
2312            BuiltinId::DomEventKey => "eventKey",
2313            BuiltinId::DomEventTarget => "eventTarget",
2314            BuiltinId::DomFetchText => "fetchText",
2315            BuiltinId::DomResponseText => "responseText",
2316            BuiltinId::DomFetchSend => "fetchSend",
2317            BuiltinId::DomResponseStatus => "responseStatus",
2318            BuiltinId::DomResponseBody => "responseBody",
2319            BuiltinId::DomResponseHeader => "responseHeader",
2320            BuiltinId::DomResponseError => "responseError",
2321            BuiltinId::DomFetchAbort => "fetchAbort",
2322            BuiltinId::DomFetchSetTimeout => "fetchSetTimeout",
2323            BuiltinId::DomRoutePath => "routePath",
2324            BuiltinId::DomRouteQuery => "routeQuery",
2325            BuiltinId::DomNavigate => "navigate",
2326            BuiltinId::DomReplaceRoute => "replaceRoute",
2327            BuiltinId::DomOnRoute => "onRoute",
2328            BuiltinId::DomSetTitle => "setTitle",
2329            BuiltinId::DomSetHeadHtml => "setHeadHtml",
2330            BuiltinId::DomReload => "reloadPage",
2331            BuiltinId::DomGoBack => "goBack",
2332            BuiltinId::DomGetAttribute => "getAttribute",
2333            BuiltinId::DomOnWindowEvent => "onWindowEvent",
2334            BuiltinId::DomScrollGap => "scrollGap",
2335            BuiltinId::DomSetInterval => "setInterval",
2336            BuiltinId::DomEventFileName => "eventFileName",
2337            BuiltinId::DomElementCommand => "elementCommand",
2338            BuiltinId::DomClipboardWrite => "clipboardWrite",
2339            BuiltinId::DomDownloadFile => "downloadFile",
2340            BuiltinId::DomNotify => "notify",
2341            BuiltinId::DomPublish => "publish",
2342            BuiltinId::ReadBytes => "readBytes",
2343            BuiltinId::TryReadBytes => "tryReadBytes",
2344            BuiltinId::FileRead => "read",
2345            BuiltinId::FileWrite => "write",
2346            BuiltinId::VfsReadFile => "__logos_read_from_file",
2347            BuiltinId::VfsWriteFile => "__logos_write_to_file",
2348            BuiltinId::VfsMount => "__logos_mount_at",
2349            BuiltinId::RandomInt => "randomInt",
2350            BuiltinId::RandomFloat => "randomFloat",
2351            BuiltinId::EnvGet => "get",
2352            BuiltinId::TimeNow => "now",
2353            BuiltinId::EnvHas => "__logos_env_has",
2354            BuiltinId::EnvValue => "__logos_env_value",
2355            // The reactive-signal dialect is retired (see `execute_builtin`); these ids are
2356            // wire-frozen and unreachable from any source a parser emits today, but an old
2357            // encoded program's wrong-arity call must still name itself in the error.
2358            BuiltinId::SignalNew => "signal",
2359            BuiltinId::SignalSet => "signalSet",
2360            BuiltinId::SignalGetInt => "signalGetInt",
2361            BuiltinId::SignalGetText => "signalGetText",
2362            BuiltinId::SignalBeginRender => "beginRender",
2363            BuiltinId::SignalNewText => "signalNewText",
2364            BuiltinId::SignalSetText => "signalSetText",
2365            BuiltinId::SignalEnterComponent => "enterComponent",
2366            BuiltinId::SignalExitComponent => "exitComponent",
2367            BuiltinId::SignalNewSeq => "signalNewSeq",
2368            BuiltinId::SignalGetSeq => "signalGetSeq",
2369            BuiltinId::SignalSetSeq => "signalSetSeq",
2370            BuiltinId::SignalNewFloat => "signalNewFloat",
2371            BuiltinId::SignalGetFloat => "signalGetFloat",
2372            BuiltinId::SignalSetFloat => "signalSetFloat",
2373            BuiltinId::InspectUnhandledDynamic => "__logos_inspect_unhandled",
2374            BuiltinId::DomEventFileSize => "eventFileSize",
2375            BuiltinId::DomEventFileType => "eventFileType",
2376            BuiltinId::DomEventFileBytes => "eventFileBytes",
2377            BuiltinId::DomListenFlags => "listenFlags",
2378            BuiltinId::DomAssignLocation => "assignLocation",
2379            BuiltinId::DomJournalDetail => "journalDetail",
2380        };
2381        return Err(format!(
2382            "{}() takes exactly {} argument{}",
2383            name,
2384            expected,
2385            if expected == 1 { "" } else { "s" }
2386        ));
2387    }
2388    Ok(())
2389}
2390
2391/// Apply a builtin to already-evaluated arguments. The caller has already
2392/// validated arity with [`check_arity`].
2393/// Validate a within-vector NTT stride argument: an `Int` that is one of the supported half-widths
2394/// 8/4/2 (the AVX2 shuffle path is defined only at these granularities).
2395fn ntt_stride(v: RuntimeValue, name: &str) -> Result<usize, String> {
2396    match v {
2397        // i16 within-vector strides are 8/4/2; the i32 (Lanes8Word32) ones are 4/2/1.
2398        RuntimeValue::Int(n @ (8 | 4 | 2 | 1)) => Ok(n as usize),
2399        RuntimeValue::Int(n) => Err(format!("{name} stride must be 8, 4, 2, or 1, got {n}")),
2400        other => Err(format!(
2401            "{name} stride must be an Int, got {}",
2402            other.type_name()
2403        )),
2404    }
2405}
2406
2407pub fn call_builtin(id: BuiltinId, args: Vec<RuntimeValue>) -> Result<RuntimeValue, String> {
2408    if let Some(builtin) = id.extension() {
2409        return logicaffeine_base::extension::call(builtin, args);
2410    }
2411    if id == BuiltinId::DefinedReal {
2412        return crate::semantics::defined::outside_a_run(args);
2413    }
2414    let mut args = args;
2415    match id {
2416        BuiltinId::MapOf => {
2417            // Flat key/value pairs, insertion-ordered; a duplicate key keeps
2418            // its first position with the last value (IndexMap `insert`).
2419            let mut m = crate::interpreter::MapStorage::default();
2420            let mut it = args.into_iter();
2421            while let (Some(k), Some(v)) = (it.next(), it.next()) {
2422                crate::semantics::collections::assert_hashable_key(&k)?;
2423                m.insert(k, v);
2424            }
2425            Ok(RuntimeValue::Map(Rc::new(RefCell::new(m))))
2426        }
2427        BuiltinId::SetOf => {
2428            // Elements in insertion order, deduplicated by value equality —
2429            // the same semantics as consecutive `Add x to s` statements.
2430            let set = RuntimeValue::Set(Rc::new(RefCell::new(Vec::new())));
2431            for v in args {
2432                crate::semantics::collections::set_add(&set, v)?;
2433            }
2434            Ok(set)
2435        }
2436        BuiltinId::RepeatSeq => {
2437            // The element evaluates ONCE; each slot deep-copies it, so a
2438            // repeated inner collection is n independent rows.
2439            let count = args.remove(1);
2440            let element = args.remove(0);
2441            let n = match count {
2442                RuntimeValue::Int(n) => n.max(0) as usize,
2443                other => {
2444                    return Err(format!(
2445                        "repeatSeq count must be an Int, got {}",
2446                        other.type_name()
2447                    ))
2448                }
2449            };
2450            let slots: Vec<RuntimeValue> = (0..n).map(|_| element.deep_clone()).collect();
2451            Ok(RuntimeValue::List(Rc::new(RefCell::new(
2452                ListRepr::from_values(slots),
2453            ))))
2454        }
2455        BuiltinId::ReedSolomonEncode => {
2456            // Systematic FEC: the first k outputs are the data shards unchanged, followed by
2457            // `parity` recovery shards (any k of the k+parity shards reconstruct the data).
2458            let parity = args.remove(1);
2459            let data = args.remove(0);
2460            let m = match parity {
2461                RuntimeValue::Int(n) if n > 0 => n as usize,
2462                RuntimeValue::Int(n) => {
2463                    return Err(format!(
2464                        "reedSolomonEncode parity count must be positive, got {}",
2465                        n
2466                    ))
2467                }
2468                other => {
2469                    return Err(format!(
2470                        "reedSolomonEncode parity count must be an Int, got {}",
2471                        other.type_name()
2472                    ))
2473                }
2474            };
2475            let shards = read_shards(&data)?;
2476            let k = shards.len();
2477            let rs = logicaffeine_base::fec::ReedSolomon::new(k, m).ok_or_else(|| {
2478                format!(
2479                    "reedSolomonEncode: invalid code ({k} data + {m} parity) — need at least one \
2480                     data shard, at least one parity shard, and a total of at most 256"
2481                )
2482            })?;
2483            let encoded = rs.encode(&shards).ok_or_else(|| {
2484                format!(
2485                    "reedSolomonEncode: the {k} data shards must be non-empty and of equal length"
2486                )
2487            })?;
2488            Ok(shards_to_seq(&encoded))
2489        }
2490        BuiltinId::ReedSolomonRecover => {
2491            // Reconstruct every shard from the surviving slots (`nothing` = a loss); the code is
2492            // rebuilt deterministically from (k data shards, received.count − k parity shards).
2493            let kv = args.remove(1);
2494            let received = args.remove(0);
2495            let k = match kv {
2496                RuntimeValue::Int(n) if n > 0 => n as usize,
2497                RuntimeValue::Int(n) => {
2498                    return Err(format!(
2499                        "reedSolomonRecover data-shard count must be positive, got {}",
2500                        n
2501                    ))
2502                }
2503                other => {
2504                    return Err(format!(
2505                        "reedSolomonRecover data-shard count must be an Int, got {}",
2506                        other.type_name()
2507                    ))
2508                }
2509            };
2510            let slots = read_received(&received)?;
2511            let n = slots.len();
2512            if n <= k {
2513                return Err(format!(
2514                    "reedSolomonRecover: {n} slots cannot carry {k} data shards plus parity"
2515                ));
2516            }
2517            let rs = logicaffeine_base::fec::ReedSolomon::new(k, n - k).ok_or_else(|| {
2518                format!(
2519                    "reedSolomonRecover: invalid code ({k} data + {} parity)",
2520                    n - k
2521                )
2522            })?;
2523            let recovered = rs.reconstruct(&slots).ok_or_else(|| {
2524                "reedSolomonRecover: insufficient surviving shards to reconstruct".to_string()
2525            })?;
2526            Ok(shards_to_seq(&recovered))
2527        }
2528        BuiltinId::FecProtect => {
2529            // Frame a flat byte payload with a 4-byte big-endian length header, zero-pad to a
2530            // multiple of `k`, split into `k` shards, and Reed-Solomon encode into `k + m` packets.
2531            let m_arg = args.remove(2);
2532            let k_arg = args.remove(1);
2533            let payload_arg = args.remove(0);
2534            let k = read_positive_count(k_arg, "fecProtect data-shard count")?;
2535            let m = read_positive_count(m_arg, "fecProtect parity-shard count")?;
2536            let payload = byte_seq(&payload_arg)?;
2537            if payload.len() > u32::MAX as usize {
2538                return Err("fecProtect: payload is too large to frame (over 4 GiB)".to_string());
2539            }
2540            let mut framed = Vec::with_capacity(4 + payload.len());
2541            framed.extend_from_slice(&(payload.len() as u32).to_be_bytes());
2542            framed.extend_from_slice(&payload);
2543            let shard_len = (framed.len() + k - 1) / k; // ceil, so every shard is equal length
2544            framed.resize(shard_len * k, 0); // zero-pad the last shard
2545            let shards: Vec<Vec<u8>> = framed.chunks(shard_len).map(|c| c.to_vec()).collect();
2546            let rs = logicaffeine_base::fec::ReedSolomon::new(k, m).ok_or_else(|| {
2547                format!("fecProtect: invalid code ({k} data + {m} parity; total must be ≤ 256)")
2548            })?;
2549            let encoded = rs
2550                .encode(&shards)
2551                .ok_or_else(|| "fecProtect: shard encoding failed".to_string())?;
2552            Ok(shards_to_seq(&encoded))
2553        }
2554        BuiltinId::FecRestore => {
2555            // Recover the `k` data shards from the surviving packets, reassemble the framed
2556            // buffer, and strip the length header + padding to return the exact original payload.
2557            let k_arg = args.remove(1);
2558            let received_arg = args.remove(0);
2559            let k = read_positive_count(k_arg, "fecRestore data-shard count")?;
2560            let slots = read_received(&received_arg)?;
2561            let n = slots.len();
2562            if n <= k {
2563                return Err(format!(
2564                    "fecRestore: {n} packets cannot carry {k} data shards plus parity"
2565                ));
2566            }
2567            let rs = logicaffeine_base::fec::ReedSolomon::new(k, n - k)
2568                .ok_or_else(|| format!("fecRestore: invalid code ({k} data + {} parity)", n - k))?;
2569            let recovered = rs.reconstruct(&slots).ok_or_else(|| {
2570                "fecRestore: insufficient surviving packets to reconstruct".to_string()
2571            })?;
2572            let mut framed: Vec<u8> = Vec::new();
2573            for shard in recovered.iter().take(k) {
2574                framed.extend_from_slice(shard);
2575            }
2576            if framed.len() < 4 {
2577                return Err(
2578                    "fecRestore: recovered data is too short for a length header".to_string(),
2579                );
2580            }
2581            let len = u32::from_be_bytes([framed[0], framed[1], framed[2], framed[3]]) as usize;
2582            if 4 + len > framed.len() {
2583                return Err("fecRestore: length header exceeds the recovered data".to_string());
2584            }
2585            Ok(bytes_to_seq(&framed[4..4 + len]))
2586        }
2587        BuiltinId::Length => {
2588            let val = args.remove(0);
2589            match &val {
2590                RuntimeValue::List(items) => Ok(RuntimeValue::Int(items.borrow().len() as i64)),
2591                RuntimeValue::Text(s) => Ok(RuntimeValue::Int(s.len() as i64)),
2592                RuntimeValue::Map(map) => Ok(RuntimeValue::Int(map.borrow().len() as i64)),
2593                _ => Err(format!("Cannot get length of {}", val.type_name())),
2594            }
2595        }
2596        BuiltinId::Contains => {
2597            let needle = args.remove(1);
2598            let haystack = args.remove(0);
2599            match (&haystack, &needle) {
2600                (RuntimeValue::Text(h), RuntimeValue::Text(n)) => {
2601                    Ok(RuntimeValue::Bool(h.contains(n.as_str())))
2602                }
2603                _ => Err(format!(
2604                    "contains expects two Text arguments, got {} and {}",
2605                    haystack.type_name(),
2606                    needle.type_name()
2607                )),
2608            }
2609        }
2610        BuiltinId::Format => {
2611            if args.is_empty() {
2612                return Ok(RuntimeValue::Text(Rc::new(String::new())));
2613            }
2614            let val = args.remove(0);
2615            Ok(RuntimeValue::Text(Rc::new(val.to_display_string())))
2616        }
2617        BuiltinId::ParseInt => {
2618            let val = args.remove(0);
2619            if let RuntimeValue::Text(s) = &val {
2620                Ok(RuntimeValue::Int(
2621                    s.trim()
2622                        .parse::<i64>()
2623                        .map_err(|_| format!("Cannot parse '{}' as Int", s))?,
2624                ))
2625            } else {
2626                Err("parseInt requires a Text argument".to_string())
2627            }
2628        }
2629        BuiltinId::ParseFloat => {
2630            let val = args.remove(0);
2631            if let RuntimeValue::Text(s) = &val {
2632                Ok(RuntimeValue::Float(
2633                    s.trim()
2634                        .parse::<f64>()
2635                        .map_err(|_| format!("Cannot parse '{}' as Float", s))?,
2636                ))
2637            } else {
2638                Err("parseFloat requires a Text argument".to_string())
2639            }
2640        }
2641        BuiltinId::Chr => {
2642            let val = args.remove(0);
2643            if let RuntimeValue::Int(code) = val {
2644                match char::from_u32(code as u32) {
2645                    Some(c) => Ok(RuntimeValue::Text(Rc::new(c.to_string()))),
2646                    None => Err(format!("Invalid character code: {}", code)),
2647                }
2648            } else {
2649                Err("chr() requires an Int argument".to_string())
2650            }
2651        }
2652        BuiltinId::Abs => {
2653            let val = args.remove(0);
2654            match val {
2655                // |i64::MIN| = 2^63 does not fit i64, so abs is EXACT via promotion
2656                // (wrapping_abs would have returned i64::MIN — a sign bug).
2657                RuntimeValue::Int(n) => Ok(match n.checked_abs() {
2658                    Some(a) => RuntimeValue::Int(a),
2659                    None => RuntimeValue::from_bigint(logicaffeine_base::BigInt::from_i64(n).abs()),
2660                }),
2661                RuntimeValue::BigInt(b) => Ok(RuntimeValue::from_bigint(b.abs())),
2662                // |·| of a rational stays a rational (`|-7/2| = 7/2`), downsized if whole.
2663                RuntimeValue::Rational(r) => Ok(RuntimeValue::from_rational(r.abs())),
2664                // |·| of a decimal stays a decimal, scale preserved (`|-0.05| = 0.05`).
2665                RuntimeValue::Decimal(d) => Ok(RuntimeValue::Decimal(Rc::new(d.abs()))),
2666                // |z| of a complex is its modulus √(re²+im²) — generally irrational, a Float view.
2667                RuntimeValue::Complex(c) => Ok(RuntimeValue::Float(c.abs_f64())),
2668                // |z| of a float-complex is its f64 modulus.
2669                RuntimeValue::ComplexF(c) => Ok(RuntimeValue::Float(c.abs())),
2670                RuntimeValue::Float(f) => Ok(RuntimeValue::Float(f.abs())),
2671                _ => Err(format!("abs() requires a number, got {}", val.type_name())),
2672            }
2673        }
2674        BuiltinId::Sqrt => {
2675            let val = args.remove(0);
2676            match val {
2677                RuntimeValue::Float(f) => Ok(RuntimeValue::Float(f.sqrt())),
2678                RuntimeValue::Int(n) => Ok(RuntimeValue::Float((n as f64).sqrt())),
2679                RuntimeValue::BigInt(b) => Ok(RuntimeValue::Float(b.to_f64().sqrt())),
2680                // The floating-point complex sqrt (`√(3+4i) = 2+i`) — the operation the exact
2681                // Gaussian complex cannot do, and the one the complex decompositions need.
2682                RuntimeValue::ComplexF(c) => Ok(RuntimeValue::ComplexF(Rc::new(c.sqrt()))),
2683                // An exact complex has an irrational magnitude, so its sqrt is inexact → `ComplexF`.
2684                RuntimeValue::Complex(c) => {
2685                    let cf = logicaffeine_base::ComplexF::new(c.re().to_f64(), c.im().to_f64());
2686                    Ok(RuntimeValue::ComplexF(Rc::new(cf.sqrt())))
2687                }
2688                _ => Err(format!("sqrt() requires a number, got {}", val.type_name())),
2689            }
2690        }
2691        BuiltinId::Infinitesimal
2692        | BuiltinId::StandardPart
2693        | BuiltinId::IsInfinitesimal
2694        | BuiltinId::IsLimited
2695        | BuiltinId::InfinitelyClose
2696        | BuiltinId::GeneratorOf
2697        | BuiltinId::LimitOf
2698        | BuiltinId::Provisional
2699        | BuiltinId::AtTheLimit
2700        | BuiltinId::TripCount
2701        | BuiltinId::AffinePower
2702        | BuiltinId::PolynomialFlow
2703        | BuiltinId::HybridFlow
2704        | BuiltinId::FirstExit
2705        | BuiltinId::CycleAt
2706        | BuiltinId::SearchCandidates
2707        | BuiltinId::StateSize
2708        | BuiltinId::EveryNatural
2709        | BuiltinId::ExactSqrt
2710        | BuiltinId::ExactExp
2711        | BuiltinId::ExactLn
2712        | BuiltinId::ExactPi
2713        | BuiltinId::ExactE
2714        | BuiltinId::ExactOmega
2715        | BuiltinId::ExactPower
2716        | BuiltinId::OrderedInfinitesimal => unreachable!("answered by logicaffeine_base::extension above"),
2717        BuiltinId::DefinedReal => unreachable!("refused by semantics::defined above"),
2718        BuiltinId::Conjugate => {
2719            let val = args.remove(0);
2720            match val {
2721                // The exact conjugate stays in the Gaussian-rational tower; the float conjugate
2722                // stays a `ComplexF`. Both just negate the imaginary part.
2723                RuntimeValue::Complex(c) => Ok(RuntimeValue::Complex(Rc::new(c.conjugate()))),
2724                RuntimeValue::ComplexF(c) => Ok(RuntimeValue::ComplexF(Rc::new(c.conjugate()))),
2725                // A real number is its own conjugate — pass it through unchanged so `conjugate`
2726                // is total over the whole numeric tower (a real column of a complex matrix is fine).
2727                RuntimeValue::Int(_)
2728                | RuntimeValue::BigInt(_)
2729                | RuntimeValue::Rational(_)
2730                | RuntimeValue::Decimal(_)
2731                | RuntimeValue::Float(_) => Ok(val),
2732                _ => Err(format!(
2733                    "conjugate() requires a number, got {}",
2734                    val.type_name()
2735                )),
2736            }
2737        }
2738        BuiltinId::RealPart => {
2739            let val = args.remove(0);
2740            match val {
2741                RuntimeValue::ComplexF(c) => Ok(RuntimeValue::Float(c.re())),
2742                RuntimeValue::Complex(c) => Ok(RuntimeValue::Float(c.re().to_f64())),
2743                RuntimeValue::Float(f) => Ok(RuntimeValue::Float(f)),
2744                RuntimeValue::Int(n) => Ok(RuntimeValue::Float(n as f64)),
2745                RuntimeValue::BigInt(b) => Ok(RuntimeValue::Float(b.to_f64())),
2746                RuntimeValue::Rational(r) => Ok(RuntimeValue::Float(r.to_f64())),
2747                _ => Err(format!("re() requires a number, got {}", val.type_name())),
2748            }
2749        }
2750        BuiltinId::ImagPart => {
2751            let val = args.remove(0);
2752            match val {
2753                RuntimeValue::ComplexF(c) => Ok(RuntimeValue::Float(c.im())),
2754                RuntimeValue::Complex(c) => Ok(RuntimeValue::Float(c.im().to_f64())),
2755                // A real number has zero imaginary part.
2756                RuntimeValue::Float(_)
2757                | RuntimeValue::Int(_)
2758                | RuntimeValue::BigInt(_)
2759                | RuntimeValue::Rational(_) => Ok(RuntimeValue::Float(0.0)),
2760                _ => Err(format!("im() requires a number, got {}", val.type_name())),
2761            }
2762        }
2763        BuiltinId::Min => {
2764            let b = args.remove(1);
2765            let a = args.remove(0);
2766            match (&a, &b) {
2767                (RuntimeValue::Int(x), RuntimeValue::Int(y)) => Ok(RuntimeValue::Int(*x.min(y))),
2768                (RuntimeValue::Float(x), RuntimeValue::Float(y)) => {
2769                    Ok(RuntimeValue::Float(logicaffeine_base::numeric::float_min(*x, *y)))
2770                }
2771                (RuntimeValue::Int(x), RuntimeValue::Float(y)) => {
2772                    Ok(RuntimeValue::Float(logicaffeine_base::numeric::float_min(*x as f64, *y)))
2773                }
2774                (RuntimeValue::Float(x), RuntimeValue::Int(y)) => {
2775                    Ok(RuntimeValue::Float(logicaffeine_base::numeric::float_min(*x, *y as f64)))
2776                }
2777                // Exact decimal min (value-based, scale of the chosen operand preserved).
2778                (RuntimeValue::Decimal(x), RuntimeValue::Decimal(y)) => {
2779                    Ok(RuntimeValue::Decimal(if x <= y {
2780                        x.clone()
2781                    } else {
2782                        y.clone()
2783                    }))
2784                }
2785                _ => Err("min() requires numbers".to_string()),
2786            }
2787        }
2788        BuiltinId::Max => {
2789            let b = args.remove(1);
2790            let a = args.remove(0);
2791            match (&a, &b) {
2792                (RuntimeValue::Int(x), RuntimeValue::Int(y)) => Ok(RuntimeValue::Int(*x.max(y))),
2793                (RuntimeValue::Float(x), RuntimeValue::Float(y)) => {
2794                    Ok(RuntimeValue::Float(logicaffeine_base::numeric::float_max(*x, *y)))
2795                }
2796                (RuntimeValue::Int(x), RuntimeValue::Float(y)) => {
2797                    Ok(RuntimeValue::Float(logicaffeine_base::numeric::float_max(*x as f64, *y)))
2798                }
2799                (RuntimeValue::Float(x), RuntimeValue::Int(y)) => {
2800                    Ok(RuntimeValue::Float(logicaffeine_base::numeric::float_max(*x, *y as f64)))
2801                }
2802                // Exact decimal max (value-based, scale of the chosen operand preserved).
2803                (RuntimeValue::Decimal(x), RuntimeValue::Decimal(y)) => {
2804                    Ok(RuntimeValue::Decimal(if x >= y {
2805                        x.clone()
2806                    } else {
2807                        y.clone()
2808                    }))
2809                }
2810                _ => Err("max() requires numbers".to_string()),
2811            }
2812        }
2813        BuiltinId::Floor => {
2814            let val = args.remove(0);
2815            let recurse = |x| call_builtin(BuiltinId::Floor, vec![x]);
2816            if let Some(r) = crate::semantics::exact::integer_part(&val, crate::semantics::exact::Rounding::Floor, &recurse) {
2817                return r;
2818            }
2819            // An exact integer (Int/BigInt) is already whole; a Rational rounds toward
2820            // −∞ to an exact integer — the explicit floor of `floor(7 / 2) → 3`.
2821            match &val {
2822                RuntimeValue::Float(f) => Ok(RuntimeValue::Int(f.floor() as i64)),
2823                RuntimeValue::Int(_) | RuntimeValue::BigInt(_) => Ok(val.clone()),
2824                RuntimeValue::Rational(r) => Ok(RuntimeValue::from_bigint(r.floor())),
2825                RuntimeValue::Decimal(d) => Ok(RuntimeValue::from_bigint(d.to_rational().floor())),
2826                _ => Err(format!(
2827                    "floor() requires a number, got {}",
2828                    val.type_name()
2829                )),
2830            }
2831        }
2832        BuiltinId::Ceil => {
2833            let val = args.remove(0);
2834            let recurse = |x| call_builtin(BuiltinId::Ceil, vec![x]);
2835            if let Some(r) = crate::semantics::exact::integer_part(&val, crate::semantics::exact::Rounding::Ceil, &recurse) {
2836                return r;
2837            }
2838            match &val {
2839                RuntimeValue::Float(f) => Ok(RuntimeValue::Int(f.ceil() as i64)),
2840                RuntimeValue::Int(_) | RuntimeValue::BigInt(_) => Ok(val.clone()),
2841                RuntimeValue::Rational(r) => Ok(RuntimeValue::from_bigint(r.ceil())),
2842                RuntimeValue::Decimal(d) => Ok(RuntimeValue::from_bigint(d.to_rational().ceil())),
2843                _ => Err(format!("ceil() requires a number, got {}", val.type_name())),
2844            }
2845        }
2846        BuiltinId::Round => {
2847            let val = args.remove(0);
2848            let recurse = |x| call_builtin(BuiltinId::Round, vec![x]);
2849            if let Some(r) = crate::semantics::exact::integer_part(&val, crate::semantics::exact::Rounding::Nearest, &recurse) {
2850                return r;
2851            }
2852            match &val {
2853                RuntimeValue::Float(f) => Ok(RuntimeValue::Int(f.round() as i64)),
2854                RuntimeValue::Int(_) | RuntimeValue::BigInt(_) => Ok(val.clone()),
2855                RuntimeValue::Rational(r) => Ok(RuntimeValue::from_bigint(r.round())),
2856                RuntimeValue::Decimal(d) => Ok(RuntimeValue::from_bigint(d.to_rational().round())),
2857                _ => Err(format!(
2858                    "round() requires a number, got {}",
2859                    val.type_name()
2860                )),
2861            }
2862        }
2863        BuiltinId::Pow => {
2864            let exp = args.remove(1);
2865            let base = args.remove(0);
2866            match (&base, &exp) {
2867                // EXACT integer power: on i64 overflow, promote to BigInt rather than
2868                // wrapping (e.g. 2^63 is the value, not i64::MIN). A negative exponent
2869                // is a fractional power, so it falls to f64 as before.
2870                (RuntimeValue::Int(b), RuntimeValue::Int(e)) => {
2871                    if *e >= 0 {
2872                        Ok(match b.checked_pow(*e as u32) {
2873                            Some(p) => RuntimeValue::Int(p),
2874                            None => RuntimeValue::from_bigint(
2875                                logicaffeine_base::BigInt::from_i64(*b).pow(*e as u32),
2876                            ),
2877                        })
2878                    } else {
2879                        Ok(RuntimeValue::Float((*b as f64).powi(*e as i32)))
2880                    }
2881                }
2882                (RuntimeValue::BigInt(b), RuntimeValue::Int(e)) => {
2883                    if *e >= 0 {
2884                        Ok(RuntimeValue::from_bigint(b.pow(*e as u32)))
2885                    } else {
2886                        Ok(RuntimeValue::Float(b.to_f64().powi(*e as i32)))
2887                    }
2888                }
2889                (RuntimeValue::Float(b), RuntimeValue::Int(e)) => {
2890                    Ok(RuntimeValue::Float(b.powi(*e as i32)))
2891                }
2892                (RuntimeValue::Float(b), RuntimeValue::Float(e)) => {
2893                    Ok(RuntimeValue::Float(b.powf(*e)))
2894                }
2895                (RuntimeValue::Int(b), RuntimeValue::Float(e)) => {
2896                    Ok(RuntimeValue::Float((*b as f64).powf(*e)))
2897                }
2898                // Modular exponentiation: x^e in ℤ/nℤ (fast square-and-multiply). Exponent ≥ 0.
2899                (RuntimeValue::Modular(b), RuntimeValue::Int(e)) if *e >= 0 => {
2900                    Ok(RuntimeValue::Modular(Rc::new(b.pow(*e as u64))))
2901                }
2902                _ => Err("pow() requires numbers".to_string()),
2903            }
2904        }
2905        BuiltinId::Decimal => {
2906            let val = args.remove(0);
2907            match &val {
2908                // Parse the exact base-10 value from its literal text (`decimal("19.99")`).
2909                RuntimeValue::Text(s) => Decimal::parse(s)
2910                    .map(|d| RuntimeValue::Decimal(Rc::new(d)))
2911                    .ok_or_else(|| logicaffeine_data::failure::not_a_decimal(s)),
2912                // An integer is already exact — widen it to a scale-0 Decimal, a big one digit for digit.
2913                RuntimeValue::Int(n) => Ok(RuntimeValue::Decimal(Rc::new(Decimal::from_i64(*n)))),
2914                RuntimeValue::BigInt(b) => Decimal::parse(&b.to_string())
2915                    .map(|d| RuntimeValue::Decimal(Rc::new(d)))
2916                    .ok_or_else(|| logicaffeine_data::failure::not_a_decimal(&b.to_string())),
2917                // Already a Decimal — identity.
2918                RuntimeValue::Decimal(_) => Ok(val.clone()),
2919                _ => Err(logicaffeine_data::failure::decimal_needs_text_or_int(
2920                    val.type_name(),
2921                )),
2922            }
2923        }
2924        BuiltinId::Complex => {
2925            let im = args.remove(1);
2926            let re = args.remove(0);
2927            let to_rat = |v: &RuntimeValue| -> Option<logicaffeine_base::Rational> {
2928                match v {
2929                    RuntimeValue::Int(n) => Some(logicaffeine_base::Rational::from_i64(*n)),
2930                    RuntimeValue::BigInt(b) => {
2931                        Some(logicaffeine_base::Rational::from_bigint((**b).clone()))
2932                    }
2933                    RuntimeValue::Rational(r) => Some((**r).clone()),
2934                    RuntimeValue::Decimal(d) => Some(d.to_rational()),
2935                    _ => None,
2936                }
2937            };
2938            // A `Float` in EITHER part makes the result a floating-point complex (`ComplexF`) — the
2939            // same promotion `Rational` meets `Float` with. Two exact parts stay an exact `Complex`
2940            // (Gaussian rationals). Never the lossy direction silently.
2941            let has_float =
2942                matches!(re, RuntimeValue::Float(_)) || matches!(im, RuntimeValue::Float(_));
2943            if has_float {
2944                let to_f = |v: &RuntimeValue| -> Option<f64> {
2945                    if let RuntimeValue::Float(f) = v {
2946                        Some(*f)
2947                    } else {
2948                        to_rat(v).map(|r| r.to_f64())
2949                    }
2950                };
2951                match (to_f(&re), to_f(&im)) {
2952                    (Some(a), Some(b)) => Ok(RuntimeValue::ComplexF(Rc::new(
2953                        logicaffeine_base::ComplexF::new(a, b),
2954                    ))),
2955                    _ => Err(format!(
2956                        "complex() requires two real numbers, got {} and {}",
2957                        re.type_name(),
2958                        im.type_name()
2959                    )),
2960                }
2961            } else {
2962                match (to_rat(&re), to_rat(&im)) {
2963                    (Some(re_r), Some(im_r)) => Ok(RuntimeValue::Complex(Rc::new(
2964                        logicaffeine_base::Complex::new(re_r, im_r),
2965                    ))),
2966                    _ => Err(format!(
2967                        "complex() requires two real numbers, got {} and {}",
2968                        re.type_name(),
2969                        im.type_name()
2970                    )),
2971                }
2972            }
2973        }
2974        BuiltinId::Modular => {
2975            let modulus = args.remove(1);
2976            let value = args.remove(0);
2977            let to_int = |v: &RuntimeValue| -> Option<logicaffeine_base::BigInt> {
2978                match v {
2979                    RuntimeValue::Int(n) => Some(logicaffeine_base::BigInt::from_i64(*n)),
2980                    RuntimeValue::BigInt(b) => Some((**b).clone()),
2981                    _ => None,
2982                }
2983            };
2984            match (to_int(&value), to_int(&modulus)) {
2985                (Some(v), Some(n)) => match logicaffeine_base::Modular::new(v, n) {
2986                    Some(m) => Ok(RuntimeValue::Modular(Rc::new(m))),
2987                    None => Err(logicaffeine_data::failure::MODULUS_NOT_POSITIVE.to_string()),
2988                },
2989                _ => Err(format!(
2990                    "modular() requires two integers, got {} and {}",
2991                    value.type_name(),
2992                    modulus.type_name()
2993                )),
2994            }
2995        }
2996        BuiltinId::Quantity => {
2997            let unit_arg = args.remove(1);
2998            let value = args.remove(0);
2999            // The magnitude must be an EXACT number (Int/BigInt/Rational/Decimal) — a Float would
3000            // make the quantity inexact, defeating lossless conversion, so it is refused.
3001            let magnitude = match &value {
3002                RuntimeValue::Int(n) => logicaffeine_base::Rational::from_i64(*n),
3003                RuntimeValue::BigInt(b) => logicaffeine_base::Rational::from_bigint((**b).clone()),
3004                RuntimeValue::Rational(r) => (**r).clone(),
3005                RuntimeValue::Decimal(d) => d.to_rational(),
3006                _ => {
3007                    return Err(format!(
3008                        "quantity() requires an exact number, got {}",
3009                        value.type_name()
3010                    ))
3011                }
3012            };
3013            let unit = match &unit_arg {
3014                RuntimeValue::Text(s) => logicaffeine_base::quantity::units::by_name(s)
3015                    .ok_or_else(|| logicaffeine_data::failure::unknown_unit(s))?,
3016                _ => {
3017                    return Err(format!(
3018                        "quantity() requires a unit name (Text), got {}",
3019                        unit_arg.type_name()
3020                    ))
3021                }
3022            };
3023            let q = logicaffeine_base::Quantity::of(magnitude, &unit);
3024            Ok(RuntimeValue::Quantity(Rc::new(
3025                crate::interpreter::QuantityValue { q, unit },
3026            )))
3027        }
3028        BuiltinId::Money => {
3029            let code_arg = args.remove(1);
3030            let value = args.remove(0);
3031            // The amount must be EXACT base-10 (Int or Decimal); a Float or non-terminating Rational
3032            // would not be representable money, so it is refused.
3033            let amount = match &value {
3034                RuntimeValue::Int(n) => logicaffeine_base::Decimal::from_i64(*n),
3035                RuntimeValue::Decimal(d) => (**d).clone(),
3036                _ => {
3037                    return Err(format!(
3038                        "money() requires an exact base-10 amount (Int or Decimal), got {}",
3039                        value.type_name()
3040                    ))
3041                }
3042            };
3043            let currency = match &code_arg {
3044                RuntimeValue::Text(s) => logicaffeine_base::money::currency::by_code(s)
3045                    .ok_or_else(|| logicaffeine_data::failure::unknown_currency(s))?,
3046                _ => {
3047                    return Err(format!(
3048                        "money() requires a currency code (Text), got {}",
3049                        code_arg.type_name()
3050                    ))
3051                }
3052            };
3053            Ok(RuntimeValue::Money(Rc::new(logicaffeine_base::Money::of(
3054                amount, currency,
3055            ))))
3056        }
3057        BuiltinId::SetRate => {
3058            let rate_arg = args.remove(1);
3059            let code_arg = args.remove(0);
3060            let code = match &code_arg {
3061                RuntimeValue::Text(s) => s.to_string(),
3062                _ => {
3063                    return Err(format!(
3064                        "set_rate() requires a currency code (Text), got {}",
3065                        code_arg.type_name()
3066                    ))
3067                }
3068            };
3069            let rate = match &rate_arg {
3070                RuntimeValue::Int(n) => logicaffeine_base::Rational::from_i64(*n),
3071                RuntimeValue::Decimal(d) => d.to_rational(),
3072                RuntimeValue::Rational(r) => (**r).clone(),
3073                _ => {
3074                    return Err(format!(
3075                        "set_rate() requires an exact rate (Int/Decimal), got {}",
3076                        rate_arg.type_name()
3077                    ))
3078                }
3079            };
3080            logicaffeine_base::money::set_ambient_rate(&code, rate);
3081            Ok(RuntimeValue::Nothing)
3082        }
3083        BuiltinId::SetRates => {
3084            let table = args.remove(0);
3085            let map = match &table {
3086                RuntimeValue::Map(m) => m,
3087                _ => {
3088                    return Err(format!(
3089                        "set_rates() requires a Map of currency code to rate, got {}",
3090                        table.type_name()
3091                    ))
3092                }
3093            };
3094            for (key, value) in map.borrow().iter() {
3095                let code = match key {
3096                    RuntimeValue::Text(s) => s.to_string(),
3097                    _ => {
3098                        return Err(format!(
3099                            "set_rates() keys must be currency codes (Text), got {}",
3100                            key.type_name()
3101                        ))
3102                    }
3103                };
3104                let rate = match value {
3105                    RuntimeValue::Int(n) => logicaffeine_base::Rational::from_i64(*n),
3106                    RuntimeValue::Decimal(d) => d.to_rational(),
3107                    RuntimeValue::Rational(r) => (**r).clone(),
3108                    _ => {
3109                        return Err(format!(
3110                            "set_rates() values must be exact rates (Int/Decimal), got {}",
3111                            value.type_name()
3112                        ))
3113                    }
3114                };
3115                logicaffeine_base::money::set_ambient_rate(&code, rate);
3116            }
3117            Ok(RuntimeValue::Nothing)
3118        }
3119        BuiltinId::Uuid => {
3120            let arg = args.remove(0);
3121            match &arg {
3122                RuntimeValue::Text(s) => logicaffeine_base::Uuid::parse(s)
3123                    .map(|u| RuntimeValue::Uuid(Rc::new(u)))
3124                    .ok_or_else(|| logicaffeine_data::failure::invalid_uuid(s)),
3125                _ => Err(format!("uuid() requires text, got {}", arg.type_name())),
3126            }
3127        }
3128        BuiltinId::UuidNil => Ok(RuntimeValue::Uuid(Rc::new(logicaffeine_base::Uuid::NIL))),
3129        BuiltinId::UuidMax => Ok(RuntimeValue::Uuid(Rc::new(logicaffeine_base::Uuid::MAX))),
3130        BuiltinId::UuidDns => Ok(RuntimeValue::Uuid(Rc::new(
3131            logicaffeine_base::Uuid::NAMESPACE_DNS,
3132        ))),
3133        BuiltinId::UuidUrl => Ok(RuntimeValue::Uuid(Rc::new(
3134            logicaffeine_base::Uuid::NAMESPACE_URL,
3135        ))),
3136        BuiltinId::UuidOid => Ok(RuntimeValue::Uuid(Rc::new(
3137            logicaffeine_base::Uuid::NAMESPACE_OID,
3138        ))),
3139        BuiltinId::UuidX500 => Ok(RuntimeValue::Uuid(Rc::new(
3140            logicaffeine_base::Uuid::NAMESPACE_X500,
3141        ))),
3142        BuiltinId::UuidVersion => {
3143            let arg = args.remove(0);
3144            match &arg {
3145                RuntimeValue::Uuid(u) => Ok(RuntimeValue::Int(u.version() as i64)),
3146                _ => Err(format!(
3147                    "uuid_version() requires a Uuid, got {}",
3148                    arg.type_name()
3149                )),
3150            }
3151        }
3152        BuiltinId::TextBytes => {
3153            let arg = args.remove(0);
3154            match &arg {
3155                RuntimeValue::Text(s) => Ok(bytes_to_seq(s.as_bytes())),
3156                _ => Err(format!(
3157                    "text_bytes() requires text, got {}",
3158                    arg.type_name()
3159                )),
3160            }
3161        }
3162        BuiltinId::TextFromBytes => {
3163            let bytes = byte_seq(&args.remove(0))?;
3164            match String::from_utf8(bytes) {
3165                Ok(s) => Ok(RuntimeValue::Text(Rc::new(s))),
3166                Err(e) => Err(logicaffeine_data::failure::invalid_utf8(e)),
3167            }
3168        }
3169        BuiltinId::WireBytes => {
3170            let arg = args.remove(0);
3171            match crate::concurrency::marshal::encode_value_raw(&arg) {
3172                Ok(bytes) => Ok(bytes_to_seq(&bytes)),
3173                Err(e) => Err(format!("wireBytes(): {}", e)),
3174            }
3175        }
3176        BuiltinId::CompressBytes => {
3177            let bytes = byte_seq(&args.remove(0))?;
3178            Ok(bytes_to_seq(&crate::concurrency::marshal::compress_best(
3179                &bytes,
3180            )))
3181        }
3182        BuiltinId::DecompressBytes => {
3183            let frame = byte_seq(&args.remove(0))?;
3184            match crate::concurrency::marshal::decompress_any(&frame) {
3185                Some(bytes) => Ok(bytes_to_seq(&bytes)),
3186                None => {
3187                    Err("decompressBytes(): malformed or oversized compressed frame".to_string())
3188                }
3189            }
3190        }
3191        BuiltinId::SealBytes => {
3192            let key = read_aead_key(&args.remove(0), "sealBytes")?;
3193            let nonce = read_aead_nonce(&args.remove(0), "sealBytes")?;
3194            let plaintext = exact_byte_seq("sealBytes", "plaintext", &args.remove(0))?;
3195            // Nothing is compressed first: a ciphertext as long as a compressed plaintext tells how
3196            // compressible the plaintext was, which gives away a secret sealed beside chosen data.
3197            let sealed =
3198                logicaffeine_system::aead::chacha20poly1305_seal(&key, &nonce, &[], &plaintext);
3199            Ok(bytes_to_seq(&sealed))
3200        }
3201        BuiltinId::OpenBytes => {
3202            let key = read_aead_key(&args.remove(0), "openBytes")?;
3203            let nonce = read_aead_nonce(&args.remove(0), "openBytes")?;
3204            let sealed = exact_byte_seq("openBytes", "sealed frame", &args.remove(0))?;
3205            let plaintext = logicaffeine_system::aead::chacha20poly1305_open(&key, &nonce, &[], &sealed)
3206                .ok_or_else(|| {
3207                    "openBytes(): authentication failed — the frame was tampered, truncated, or the key is wrong".to_string()
3208                })?;
3209            Ok(bytes_to_seq(&plaintext))
3210        }
3211        BuiltinId::FromWireBytes => {
3212            let bytes = byte_seq(&args.remove(0))?;
3213            crate::concurrency::marshal::decode_value_raw(&bytes)
3214                .ok_or_else(|| "fromWireBytes(): malformed or trailing-byte wire input".to_string())
3215        }
3216        BuiltinId::SealFrame => {
3217            let key = read_aead_key(&args.remove(0), "sealFrame")?;
3218            let nonce = read_aead_nonce(&args.remove(0), "sealFrame")?;
3219            let value = args.remove(0);
3220            // wire-encode → authenticated-encrypt, fused (no intermediate Logos Seq), and never
3221            // compressed between, for the reason `sealBytes` gives.
3222            let wire = crate::concurrency::marshal::encode_value_raw(&value)
3223                .map_err(|e| format!("sealFrame(): {}", e))?;
3224            let sealed = logicaffeine_system::aead::chacha20poly1305_seal(&key, &nonce, &[], &wire);
3225            Ok(bytes_to_seq(&sealed))
3226        }
3227        BuiltinId::OpenFrame => {
3228            let key = read_aead_key(&args.remove(0), "openFrame")?;
3229            let nonce = read_aead_nonce(&args.remove(0), "openFrame")?;
3230            let sealed = exact_byte_seq("openFrame", "sealed frame", &args.remove(0))?;
3231            let wire = logicaffeine_system::aead::chacha20poly1305_open(&key, &nonce, &[], &sealed)
3232                .ok_or_else(|| {
3233                    "openFrame(): authentication failed — the frame was tampered, truncated, or the key is wrong".to_string()
3234                })?;
3235            crate::concurrency::marshal::decode_value_raw(&wire)
3236                .ok_or_else(|| "openFrame(): malformed wire value after decryption".to_string())
3237        }
3238        BuiltinId::SealBox => {
3239            let key = read_aead_key(&args.remove(0), "sealBox")?;
3240            let plaintext = exact_byte_seq("sealBox", "plaintext", &args.remove(0))?;
3241            let sealed = logicaffeine_system::aead::seal_box(
3242                &key,
3243                logicaffeine_system::aead::BOX_BYTES_LABEL,
3244                &plaintext,
3245            )
3246            .map_err(|why| format!("sealBox(): {why}"))?;
3247            Ok(bytes_to_seq(&sealed))
3248        }
3249        BuiltinId::OpenBox => {
3250            let key = read_aead_key(&args.remove(0), "openBox")?;
3251            let sealed = read_box(&args.remove(0), "openBox")?;
3252            let plaintext =
3253                logicaffeine_system::aead::open_box(&key, logicaffeine_system::aead::BOX_BYTES_LABEL, &sealed)
3254                    .ok_or_else(|| box_refused("openBox"))?;
3255            Ok(bytes_to_seq(&plaintext))
3256        }
3257        BuiltinId::SealValueBox => {
3258            let key = read_aead_key(&args.remove(0), "sealValueBox")?;
3259            let wire = crate::concurrency::marshal::encode_value_raw(&args.remove(0))
3260                .map_err(|e| format!("sealValueBox(): {e}"))?;
3261            let sealed =
3262                logicaffeine_system::aead::seal_box(&key, logicaffeine_system::aead::BOX_VALUE_LABEL, &wire)
3263                    .map_err(|why| format!("sealValueBox(): {why}"))?;
3264            Ok(bytes_to_seq(&sealed))
3265        }
3266        BuiltinId::OpenValueBox => {
3267            let key = read_aead_key(&args.remove(0), "openValueBox")?;
3268            let sealed = read_box(&args.remove(0), "openValueBox")?;
3269            let wire =
3270                logicaffeine_system::aead::open_box(&key, logicaffeine_system::aead::BOX_VALUE_LABEL, &sealed)
3271                    .ok_or_else(|| box_refused("openValueBox"))?;
3272            crate::concurrency::marshal::decode_value_raw(&wire)
3273                .ok_or_else(|| "openValueBox(): malformed wire value after decryption".to_string())
3274        }
3275        BuiltinId::ReadWireProgram => {
3276            use std::io::Read;
3277            let mut len = [0u8; 4];
3278            if std::io::stdin().read_exact(&mut len).is_err() {
3279                std::process::exit(0);
3280            }
3281            let n = u32::from_le_bytes(len) as usize;
3282            let mut buf = vec![0u8; n];
3283            std::io::stdin()
3284                .read_exact(&mut buf)
3285                .map_err(|e| format!("readWireProgram(): frame read failed: {e}"))?;
3286            crate::concurrency::marshal::decode_value_raw(&buf)
3287                .ok_or_else(|| "readWireProgram(): malformed wire program".to_string())
3288        }
3289        BuiltinId::WriteWireResidual => {
3290            use std::io::Write;
3291            let arg = args.remove(0);
3292            let s = match &arg {
3293                RuntimeValue::Text(t) => (**t).clone(),
3294                _ => return Err("writeWireResidual() expects text".to_string()),
3295            };
3296            let b = s.as_bytes();
3297            let out = std::io::stdout();
3298            let mut h = out.lock();
3299            h.write_all(&(b.len() as u32).to_le_bytes())
3300                .and_then(|_| h.write_all(b))
3301                .and_then(|_| h.flush())
3302                .map_err(|e| format!("writeWireResidual(): {e}"))?;
3303            Ok(RuntimeValue::Int(b.len() as i64))
3304        }
3305        BuiltinId::UuidBytes => {
3306            let arg = args.remove(0);
3307            match &arg {
3308                RuntimeValue::Uuid(u) => Ok(bytes_to_seq(u.as_bytes())),
3309                _ => Err(format!(
3310                    "uuid_bytes() requires a Uuid, got {}",
3311                    arg.type_name()
3312                )),
3313            }
3314        }
3315        BuiltinId::UuidFromBytes => {
3316            let bytes = byte_seq(&args.remove(0))?;
3317            if bytes.len() < 16 {
3318                return Err(logicaffeine_data::failure::uuid_needs_16_bytes(bytes.len()));
3319            }
3320            let mut b = [0u8; 16];
3321            b.copy_from_slice(&bytes[..16]);
3322            Ok(RuntimeValue::Uuid(Rc::new(
3323                logicaffeine_base::Uuid::from_bytes(b),
3324            )))
3325        }
3326        BuiltinId::ToCurrency => {
3327            let code_arg = args.remove(1);
3328            let money = args.remove(0);
3329            match (&money, &code_arg) {
3330                (RuntimeValue::Money(m), RuntimeValue::Text(code)) => {
3331                    let to = logicaffeine_base::money::currency::by_code(code)
3332                        .ok_or_else(|| logicaffeine_data::failure::unknown_currency(code))?;
3333                    logicaffeine_base::money::ambient_convert(m, to)
3334                        .map(|c| RuntimeValue::Money(Rc::new(c)))
3335                        .ok_or_else(|| {
3336                            if logicaffeine_base::money::has_ambient_rates() {
3337                                logicaffeine_data::failure::no_exchange_rate(
3338                                    m.currency.code,
3339                                    to.code,
3340                                )
3341                            } else {
3342                                logicaffeine_data::failure::NO_EXCHANGE_RATES.to_string()
3343                            }
3344                        })
3345                }
3346                _ => Err(format!(
3347                    "to_currency() requires money and a currency code, got {} and {}",
3348                    money.type_name(),
3349                    code_arg.type_name()
3350                )),
3351            }
3352        }
3353        BuiltinId::Convert => {
3354            let unit_arg = args.remove(1);
3355            let value = args.remove(0);
3356            let unit = match &unit_arg {
3357                RuntimeValue::Text(s) => logicaffeine_base::quantity::units::by_name(s)
3358                    .ok_or_else(|| logicaffeine_data::failure::unknown_unit(s))?,
3359                _ => {
3360                    return Err(format!(
3361                        "convert() requires a unit name (Text), got {}",
3362                        unit_arg.type_name()
3363                    ))
3364                }
3365            };
3366            match &value {
3367                // Same dimension → re-express (the SI magnitude is unchanged, only the display unit);
3368                // a different dimension is the forbidden cast.
3369                RuntimeValue::Quantity(qv) => {
3370                    if qv.q.dimension() != unit.dimension {
3371                        return Err(logicaffeine_data::failure::cannot_convert(
3372                            qv.unit.symbol,
3373                            unit.symbol,
3374                        ));
3375                    }
3376                    Ok(RuntimeValue::Quantity(Rc::new(
3377                        crate::interpreter::QuantityValue {
3378                            q: qv.q.clone(),
3379                            unit,
3380                        },
3381                    )))
3382                }
3383                _ => Err(format!(
3384                    "convert() requires a quantity, got {}",
3385                    value.type_name()
3386                )),
3387            }
3388        }
3389        BuiltinId::ParseTimestamp => {
3390            let val = args.remove(0);
3391            match &val {
3392                RuntimeValue::Text(s) => logicaffeine_base::temporal::parse_rfc3339(s.trim())
3393                    .map(RuntimeValue::Moment)
3394                    .ok_or_else(|| logicaffeine_data::failure::not_a_timestamp(s)),
3395                _ => Err(format!(
3396                    "parse_timestamp() requires a Text, got {}",
3397                    val.type_name()
3398                )),
3399            }
3400        }
3401        BuiltinId::FormatTimestamp => {
3402            let val = args.remove(0);
3403            match &val {
3404                RuntimeValue::Moment(nanos) => Ok(RuntimeValue::Text(Rc::new(
3405                    logicaffeine_base::temporal::format_rfc3339(*nanos),
3406                ))),
3407                _ => Err(format!(
3408                    "format_timestamp() requires a Moment, got {}",
3409                    val.type_name()
3410                )),
3411            }
3412        }
3413        BuiltinId::YearOf
3414        | BuiltinId::MonthOf
3415        | BuiltinId::DayOf
3416        | BuiltinId::WeekdayOf
3417        | BuiltinId::WeekOf
3418        | BuiltinId::QuarterOf
3419        | BuiltinId::HourOf
3420        | BuiltinId::MinuteOf
3421        | BuiltinId::SecondOf => {
3422            let val = args.remove(0);
3423            match &val {
3424                RuntimeValue::Moment(nanos) => {
3425                    use logicaffeine_base::temporal;
3426                    let civil = temporal::civil_from_unix_nanos(*nanos);
3427                    let component = match id {
3428                        BuiltinId::YearOf => civil.year,
3429                        BuiltinId::MonthOf => civil.month as i64,
3430                        BuiltinId::DayOf => civil.day as i64,
3431                        BuiltinId::HourOf => civil.hour as i64,
3432                        BuiltinId::MinuteOf => civil.minute as i64,
3433                        BuiltinId::SecondOf => civil.second as i64,
3434                        BuiltinId::WeekdayOf => temporal::iso_weekday_from_days(
3435                            nanos.div_euclid(temporal::NANOS_PER_DAY),
3436                        ) as i64,
3437                        BuiltinId::WeekOf => {
3438                            temporal::iso_week_from_days(nanos.div_euclid(temporal::NANOS_PER_DAY))
3439                                .1 as i64
3440                        }
3441                        BuiltinId::QuarterOf => (civil.month as i64 - 1) / 3 + 1,
3442                        _ => unreachable!(),
3443                    };
3444                    Ok(RuntimeValue::Int(component))
3445                }
3446                // The same accessors on a calendar Date (no time-of-day, so hour/minute/second
3447                // don't apply) — `the year of 2024-03-10`.
3448                RuntimeValue::Date(days) => {
3449                    use logicaffeine_base::temporal;
3450                    let (y, m, d) = temporal::civil_from_days(*days as i64);
3451                    let component = match id {
3452                        BuiltinId::YearOf => y,
3453                        BuiltinId::MonthOf => m as i64,
3454                        BuiltinId::DayOf => d as i64,
3455                        BuiltinId::WeekdayOf => {
3456                            temporal::iso_weekday_from_days(*days as i64) as i64
3457                        }
3458                        BuiltinId::WeekOf => temporal::iso_week_from_days(*days as i64).1 as i64,
3459                        BuiltinId::QuarterOf => (m as i64 - 1) / 3 + 1,
3460                        BuiltinId::HourOf | BuiltinId::MinuteOf | BuiltinId::SecondOf => {
3461                            return Err(
3462                                "a Date has no time-of-day — use a timestamp/Moment".to_string()
3463                            );
3464                        }
3465                        _ => unreachable!(),
3466                    };
3467                    Ok(RuntimeValue::Int(component))
3468                }
3469                _ => Err(format!(
3470                    "a date component extractor requires a Moment or Date, got {}",
3471                    val.type_name()
3472                )),
3473            }
3474        }
3475        BuiltinId::DateOf => {
3476            let val = args.remove(0);
3477            match &val {
3478                // The calendar day a Moment falls on (UTC); a Date is already a date (identity).
3479                RuntimeValue::Moment(nanos) => Ok(RuntimeValue::Date(
3480                    nanos.div_euclid(logicaffeine_base::temporal::NANOS_PER_DAY) as i32,
3481                )),
3482                RuntimeValue::Date(days) => Ok(RuntimeValue::Date(*days)),
3483                _ => Err(format!(
3484                    "date_of() requires a Moment or Date, got {}",
3485                    val.type_name()
3486                )),
3487            }
3488        }
3489        BuiltinId::TimeOf => {
3490            let val = args.remove(0);
3491            match &val {
3492                // The wall-clock time-of-day a Moment falls on (UTC). A Date has no time-of-day.
3493                RuntimeValue::Moment(nanos) => Ok(RuntimeValue::Time(
3494                    nanos.rem_euclid(logicaffeine_base::temporal::NANOS_PER_DAY),
3495                )),
3496                RuntimeValue::Date(_) => {
3497                    Err("a Date has no time-of-day — use a timestamp/Moment".to_string())
3498                }
3499                _ => Err(format!(
3500                    "time_of() requires a Moment, got {}",
3501                    val.type_name()
3502                )),
3503            }
3504        }
3505        BuiltinId::MakeDate => {
3506            let d = args.remove(2);
3507            let m = args.remove(1);
3508            let y = args.remove(0);
3509            match (&y, &m, &d) {
3510                (RuntimeValue::Int(y), RuntimeValue::Int(mo), RuntimeValue::Int(da)) => Ok(
3511                    RuntimeValue::Date(logicaffeine_base::temporal::days_from_civil(
3512                        *y, *mo as u32, *da as u32,
3513                    ) as i32),
3514                ),
3515                _ => Err(format!(
3516                    "makeDate() requires three Ints (year, month, day), got {}, {}, {}",
3517                    y.type_name(),
3518                    m.type_name(),
3519                    d.type_name()
3520                )),
3521            }
3522        }
3523        BuiltinId::MakeMoment => {
3524            let s = args.remove(5);
3525            let mi = args.remove(4);
3526            let h = args.remove(3);
3527            let d = args.remove(2);
3528            let m = args.remove(1);
3529            let y = args.remove(0);
3530            match (&y, &m, &d, &h, &mi, &s) {
3531                (
3532                    RuntimeValue::Int(y),
3533                    RuntimeValue::Int(mo),
3534                    RuntimeValue::Int(da),
3535                    RuntimeValue::Int(hr),
3536                    RuntimeValue::Int(min),
3537                    RuntimeValue::Int(sec),
3538                ) => {
3539                    let days =
3540                        logicaffeine_base::temporal::days_from_civil(*y, *mo as u32, *da as u32);
3541                    let nanos = days * logicaffeine_base::temporal::NANOS_PER_DAY
3542                        + (*hr * 3600 + *min * 60 + *sec)
3543                            * logicaffeine_base::temporal::NANOS_PER_SECOND;
3544                    Ok(RuntimeValue::Moment(nanos))
3545                }
3546                _ => Err(
3547                    "makeMoment() requires six Ints (year, month, day, hour, minute, second)"
3548                        .to_string(),
3549                ),
3550            }
3551        }
3552        BuiltinId::SecondsBetween => {
3553            let b = args.remove(1);
3554            let a = args.remove(0);
3555            match (&a, &b) {
3556                (RuntimeValue::Moment(a), RuntimeValue::Moment(b)) => {
3557                    Ok(RuntimeValue::Int((b - a) / 1_000_000_000))
3558                }
3559                _ => Err(format!(
3560                    "seconds_between() requires two Moments, got {} and {}",
3561                    a.type_name(),
3562                    b.type_name()
3563                )),
3564            }
3565        }
3566        BuiltinId::MonthsBetween | BuiltinId::YearsBetween => {
3567            let b = args.remove(1);
3568            let a = args.remove(0);
3569            match (&a, &b) {
3570                (RuntimeValue::Moment(a), RuntimeValue::Moment(b)) => {
3571                    let n = if matches!(id, BuiltinId::MonthsBetween) {
3572                        logicaffeine_base::temporal::months_between(*a, *b)
3573                    } else {
3574                        logicaffeine_base::temporal::years_between(*a, *b)
3575                    };
3576                    Ok(RuntimeValue::Int(n))
3577                }
3578                _ => {
3579                    let name = if matches!(id, BuiltinId::MonthsBetween) {
3580                        "months_between"
3581                    } else {
3582                        "years_between"
3583                    };
3584                    Err(format!(
3585                        "{name}() requires two Moments, got {} and {}",
3586                        a.type_name(),
3587                        b.type_name()
3588                    ))
3589                }
3590            }
3591        }
3592        BuiltinId::AddSeconds => {
3593            let secs = args.remove(1);
3594            let moment = args.remove(0);
3595            match (&moment, &secs) {
3596                (RuntimeValue::Moment(nanos), RuntimeValue::Int(n)) => {
3597                    Ok(RuntimeValue::Moment(nanos + n * 1_000_000_000))
3598                }
3599                _ => Err(format!(
3600                    "add_seconds() requires a Moment and an Int, got {} and {}",
3601                    moment.type_name(),
3602                    secs.type_name()
3603                )),
3604            }
3605        }
3606        BuiltinId::InZone => {
3607            let zone = args.remove(1);
3608            let moment = args.remove(0);
3609            match (&moment, &zone) {
3610                (RuntimeValue::Moment(nanos), RuntimeValue::Text(z)) => {
3611                    logicaffeine_base::temporal::format_zoned(*nanos, z)
3612                        .map(|s| RuntimeValue::Text(Rc::new(s)))
3613                        .ok_or_else(|| logicaffeine_data::failure::unknown_time_zone(z))
3614                }
3615                _ => Err(format!(
3616                    "in_zone() requires a Moment and a zone name (Text), got {} and {}",
3617                    moment.type_name(),
3618                    zone.type_name()
3619                )),
3620            }
3621        }
3622        BuiltinId::LocalInstant => {
3623            let zone = args.remove(1);
3624            let moment = args.remove(0);
3625            match (&moment, &zone) {
3626                (RuntimeValue::Moment(nanos), RuntimeValue::Text(z)) => {
3627                    logicaffeine_base::temporal::local_instant_nanos(*nanos, z)
3628                        .map(RuntimeValue::Moment)
3629                        .ok_or_else(|| logicaffeine_data::failure::unknown_time_zone(z))
3630                }
3631                _ => Err(format!(
3632                    "local_instant() requires a Moment and a zone name (Text), got {} and {}",
3633                    moment.type_name(),
3634                    zone.type_name()
3635                )),
3636            }
3637        }
3638        BuiltinId::Copy => {
3639            let val = args.remove(0);
3640            Ok(val.deep_clone())
3641        }
3642        BuiltinId::Fail => Err(args.remove(0).to_display_string()),
3643        BuiltinId::FailReason => Err(contract_reason_text(args.remove(0))?),
3644        // G5/S20: the loud message for a non-exhaustive `Inspect` with no compile-time-known
3645        // enum — `vm/compiler.rs`'s `compile_inspect` emits this call ONLY for its own dynamic
3646        // fallback arm, passing the already-evaluated scrutinee. Reads the ACTUAL runtime
3647        // constructor the same way the tree-walker's `inspect_unhandled` does, so the two tiers
3648        // fail with byte-identical words.
3649        BuiltinId::InspectUnhandledDynamic => {
3650            let target = args.remove(0);
3651            let variant = match &target {
3652                RuntimeValue::Inductive(i) => i.constructor.as_str(),
3653                _ => "the value",
3654            };
3655            Err(inspect_unhandled_message(target.type_name(), variant))
3656        }
3657        BuiltinId::NativeKernel => {
3658            use crate::semantics::native_kernels::NativeKernel;
3659            let kernel = match args.first() {
3660                Some(RuntimeValue::Int(code)) => NativeKernel::from_code(*code)
3661                    .ok_or_else(|| format!("unknown native kernel code {code}"))?,
3662                _ => return Err("a native kernel call carries its kernel code".to_string()),
3663            };
3664            kernel.call(&args[1..])
3665        }
3666        BuiltinId::CountOnes => {
3667            let val = args.remove(0);
3668            match val {
3669                // Two's-complement faithful: count set bits over the full 64-bit
3670                // pattern (matches codegen's `(x as u64).count_ones()`).
3671                RuntimeValue::Int(n) => Ok(RuntimeValue::Int((n as u64).count_ones() as i64)),
3672                _ => Err(format!(
3673                    "count_ones() requires an Int, got {}",
3674                    val.type_name()
3675                )),
3676            }
3677        }
3678        BuiltinId::LeadingZeros => {
3679            let val = args.remove(0);
3680            match val {
3681                // High zero bits of the u64 pattern (matches codegen's
3682                // `(x as u64).leading_zeros()`; 64 for 0).
3683                RuntimeValue::Int(n) => Ok(RuntimeValue::Int((n as u64).leading_zeros() as i64)),
3684                _ => Err(format!(
3685                    "leading_zeros() requires an Int, got {}",
3686                    val.type_name()
3687                )),
3688            }
3689        }
3690        BuiltinId::TrailingZeros => {
3691            let val = args.remove(0);
3692            match val {
3693                // Low zero bits of the u64 pattern (matches codegen's
3694                // `(x as u64).trailing_zeros()`; 64 for 0).
3695                RuntimeValue::Int(n) => Ok(RuntimeValue::Int((n as u64).trailing_zeros() as i64)),
3696                _ => Err(format!(
3697                    "trailing_zeros() requires an Int, got {}",
3698                    val.type_name()
3699                )),
3700            }
3701        }
3702        BuiltinId::Word32 => {
3703            let n = args.remove(0);
3704            match n {
3705                RuntimeValue::Int(v) => Ok(RuntimeValue::Word(WordVal::W32(Word32(v as u32)))),
3706                RuntimeValue::BigInt(v) => Ok(RuntimeValue::Word(WordVal::W32(Word32(
3707                    v.wrapping_u64() as u32,
3708                )))),
3709                RuntimeValue::Word(w) => {
3710                    Ok(RuntimeValue::Word(WordVal::W32(Word32(w.to_u64() as u32))))
3711                }
3712                _ => Err(format!("word32() requires an Int, got {}", n.type_name())),
3713            }
3714        }
3715        BuiltinId::Word64 => {
3716            let n = args.remove(0);
3717            match n {
3718                RuntimeValue::Int(v) => Ok(RuntimeValue::Word(WordVal::W64(Word64(v as u64)))),
3719                RuntimeValue::BigInt(v) => Ok(RuntimeValue::Word(WordVal::W64(Word64(
3720                    v.wrapping_u64() as u64,
3721                )))),
3722                RuntimeValue::Word(w) => Ok(RuntimeValue::Word(WordVal::W64(Word64(w.to_u64())))),
3723                _ => Err(format!("word64() requires an Int, got {}", n.type_name())),
3724            }
3725        }
3726        BuiltinId::Rotl | BuiltinId::Rotr => {
3727            let w = args.remove(0);
3728            let n = args.remove(0);
3729            let count = match n {
3730                RuntimeValue::Int(c) => c as u32,
3731                RuntimeValue::Word(c) => c.to_u64() as u32,
3732                _ => {
3733                    return Err(format!(
3734                        "rotate count must be an Int, got {}",
3735                        n.type_name()
3736                    ))
3737                }
3738            };
3739            match w {
3740                RuntimeValue::Word(word) => {
3741                    let r = if matches!(id, BuiltinId::Rotl) {
3742                        word.rotl(count)
3743                    } else {
3744                        word.rotr(count)
3745                    };
3746                    Ok(RuntimeValue::Word(r))
3747                }
3748                // A SIMD lane vector rotates lane-wise (the ChaCha diffusion op). Only left rotation
3749                // is part of the lane vocabulary so far.
3750                RuntimeValue::Lanes(lanes) if matches!(id, BuiltinId::Rotl) => {
3751                    match lanes.rotl(count) {
3752                        Some(v) => Ok(RuntimeValue::Lanes(Rc::new(v))),
3753                        None => Err(format!("rotl is not defined for {}", lanes.type_name())),
3754                    }
3755                }
3756                _ => Err(format!("rotate requires a Word, got {}", w.type_name())),
3757            }
3758        }
3759        BuiltinId::Wand | BuiltinId::Wor => {
3760            let b = args.remove(1);
3761            let a = args.remove(0);
3762            match (&a, &b) {
3763                (RuntimeValue::Word(x), RuntimeValue::Word(y)) => {
3764                    let r = if id == BuiltinId::Wand {
3765                        x.bitand(*y)
3766                    } else {
3767                        x.bitor(*y)
3768                    };
3769                    match r {
3770                        Some(w) => Ok(RuntimeValue::Word(w)),
3771                        None => Err(format!(
3772                            "word_and/or width mismatch: {} vs {}",
3773                            a.type_name(),
3774                            b.type_name()
3775                        )),
3776                    }
3777                }
3778                // Lane-vector bitwise mixing (the MD5 F/G functions written over `Lanes8Word32`).
3779                (RuntimeValue::Lanes(x), RuntimeValue::Lanes(y)) => {
3780                    let r = if id == BuiltinId::Wand {
3781                        (**x).bitand(**y)
3782                    } else {
3783                        (**x).bitor(**y)
3784                    };
3785                    match r {
3786                        Some(v) => Ok(RuntimeValue::Lanes(Rc::new(v))),
3787                        None => Err(format!(
3788                            "word_and/or lane-config mismatch: {} vs {}",
3789                            a.type_name(),
3790                            b.type_name()
3791                        )),
3792                    }
3793                }
3794                _ => Err(format!(
3795                    "word_and/or requires two Words, got {} and {}",
3796                    a.type_name(),
3797                    b.type_name()
3798                )),
3799            }
3800        }
3801        BuiltinId::Wnot => {
3802            let a = args.remove(0);
3803            match &a {
3804                RuntimeValue::Word(x) => Ok(RuntimeValue::Word(x.not())),
3805                RuntimeValue::Lanes(x) => match (**x).lane_not() {
3806                    Some(v) => Ok(RuntimeValue::Lanes(Rc::new(v))),
3807                    None => Err(format!(
3808                        "word_not: lane config has no complement: {}",
3809                        a.type_name()
3810                    )),
3811                },
3812                _ => Err(format!("word_not requires a Word, got {}", a.type_name())),
3813            }
3814        }
3815        BuiltinId::Lanes4Word32Make => {
3816            // Pack a Seq of (up to) 4 Word32 into the 128-bit SHA-1 lane register.
3817            let s = args.remove(0);
3818            match s {
3819                RuntimeValue::List(items) => {
3820                    let vals = items.borrow().to_values();
3821                    let mut words = Vec::with_capacity(vals.len());
3822                    for v in &vals {
3823                        match v {
3824                            RuntimeValue::Word(WordVal::W32(w)) => words.push(*w),
3825                            RuntimeValue::Int(n) => words.push(Word32(*n as u32)),
3826                            other => {
3827                                return Err(format!(
3828                                    "lanes4Word32() needs a Seq of Word32, found {}",
3829                                    other.type_name()
3830                                ))
3831                            }
3832                        }
3833                    }
3834                    Ok(RuntimeValue::Lanes(Rc::new(LanesVal::L4W32(
3835                        logicaffeine_base::Lanes4Word32::from_words(&words),
3836                    ))))
3837                }
3838                other => Err(format!(
3839                    "lanes4Word32() requires a Seq of Word32, got {}",
3840                    other.type_name()
3841                )),
3842            }
3843        }
3844        BuiltinId::Lanes4Of => {
3845            // Pack four Word32 values straight into the lane register — no Seq, no heap. This is the
3846            // per-round constructor the Logos SHA-1 uses, so it must not allocate.
3847            let mut w = [Word32(0); 4];
3848            for slot in w.iter_mut() {
3849                *slot = match args.remove(0) {
3850                    RuntimeValue::Word(WordVal::W32(x)) => x,
3851                    RuntimeValue::Int(n) => Word32(n as u32),
3852                    other => {
3853                        return Err(format!(
3854                            "lanes4Of() needs four Word32, found {}",
3855                            other.type_name()
3856                        ))
3857                    }
3858                };
3859            }
3860            Ok(RuntimeValue::Lanes(Rc::new(LanesVal::L4W32(
3861                logicaffeine_base::Lanes4Word32::from_words(&w),
3862            ))))
3863        }
3864        BuiltinId::SeqOfLanes4W32 => {
3865            let v = args.remove(0);
3866            match v {
3867                RuntimeValue::Lanes(lanes) => match *lanes {
3868                    LanesVal::L4W32(lv) => {
3869                        let vals: Vec<RuntimeValue> = lv
3870                            .to_words()
3871                            .iter()
3872                            .map(|w| RuntimeValue::Word(WordVal::W32(*w)))
3873                            .collect();
3874                        Ok(RuntimeValue::List(Rc::new(std::cell::RefCell::new(
3875                            crate::interpreter::ListRepr::from_values(vals),
3876                        ))))
3877                    }
3878                    other => Err(format!(
3879                        "seqOfLanes4W32() requires a Lanes4Word32, got {}",
3880                        other.type_name()
3881                    )),
3882                },
3883                other => Err(format!(
3884                    "seqOfLanes4W32() requires a Lanes4Word32, got {}",
3885                    other.type_name()
3886                )),
3887            }
3888        }
3889        BuiltinId::Sha1Rnds4 => {
3890            let func = args.remove(2);
3891            let msg = args.remove(1);
3892            let abcd = args.remove(0);
3893            let f = match &func {
3894                RuntimeValue::Int(n) => *n as u32,
3895                _ => {
3896                    return Err(format!(
3897                        "sha1rnds4() func must be an Int, got {}",
3898                        func.type_name()
3899                    ))
3900                }
3901            };
3902            match (&abcd, &msg) {
3903                (RuntimeValue::Lanes(a), RuntimeValue::Lanes(b)) => (**a)
3904                    .sha1rnds4(**b, f)
3905                    .map(|r| RuntimeValue::Lanes(Rc::new(r)))
3906                    .ok_or_else(|| "sha1rnds4() requires two Lanes4Word32".to_string()),
3907                _ => Err(format!(
3908                    "sha1rnds4() requires two Lanes4Word32, got {} and {}",
3909                    abcd.type_name(),
3910                    msg.type_name()
3911                )),
3912            }
3913        }
3914        BuiltinId::Sha1Msg1 | BuiltinId::Sha1Msg2 | BuiltinId::Sha1Nexte => {
3915            let b = args.remove(1);
3916            let a = args.remove(0);
3917            match (&a, &b) {
3918                (RuntimeValue::Lanes(x), RuntimeValue::Lanes(y)) => {
3919                    let r = match id {
3920                        BuiltinId::Sha1Msg1 => (**x).sha1msg1(**y),
3921                        BuiltinId::Sha1Msg2 => (**x).sha1msg2(**y),
3922                        _ => (**x).sha1nexte(**y),
3923                    };
3924                    r.map(|v| RuntimeValue::Lanes(Rc::new(v)))
3925                        .ok_or_else(|| "sha1msg/nexte requires two Lanes4Word32".to_string())
3926                }
3927                _ => Err(format!(
3928                    "sha1 message op requires two Lanes4Word32, got {} and {}",
3929                    a.type_name(),
3930                    b.type_name()
3931                )),
3932            }
3933        }
3934        BuiltinId::Lanes16Word8Make => {
3935            // Pack a Seq of Int (bytes) into one byte-shuffle register — the SIMD hex codec loads its
3936            // 16 working bytes this way.
3937            let bytes = byte_seq(&args.remove(0))?;
3938            Ok(RuntimeValue::Lanes(Rc::new(LanesVal::L16W8(
3939                logicaffeine_base::Lanes16Word8::from_bytes(&bytes),
3940            ))))
3941        }
3942        BuiltinId::SeqOfLanes16W8 => {
3943            let v = args.remove(0);
3944            match v {
3945                RuntimeValue::Lanes(lanes) => match *lanes {
3946                    LanesVal::L16W8(lv) => Ok(bytes_to_seq(&lv.to_bytes())),
3947                    other => Err(format!(
3948                        "seqOfLanes16W8() requires a Lanes16Word8, got {}",
3949                        other.type_name()
3950                    )),
3951                },
3952                other => Err(format!(
3953                    "seqOfLanes16W8() requires a Lanes16Word8, got {}",
3954                    other.type_name()
3955                )),
3956            }
3957        }
3958        BuiltinId::Splat16Word8 => match args.remove(0) {
3959            RuntimeValue::Int(n) => Ok(RuntimeValue::Lanes(Rc::new(LanesVal::L16W8(
3960                logicaffeine_base::Lanes16Word8::splat(n as u8),
3961            )))),
3962            other => Err(format!(
3963                "splat16Word8() requires an Int, got {}",
3964                other.type_name()
3965            )),
3966        },
3967        BuiltinId::Shuffle16
3968        | BuiltinId::InterleaveLo16
3969        | BuiltinId::InterleaveHi16
3970        | BuiltinId::ByteAdd16
3971        | BuiltinId::Maddubs16
3972        | BuiltinId::Packus16 => {
3973            let b = args.remove(1);
3974            let a = args.remove(0);
3975            match (&a, &b) {
3976                (RuntimeValue::Lanes(x), RuntimeValue::Lanes(y)) => {
3977                    let r = match id {
3978                        BuiltinId::Shuffle16 => (**x).shuffle(**y),
3979                        BuiltinId::InterleaveLo16 => (**x).interleave_lo(**y),
3980                        BuiltinId::InterleaveHi16 => (**x).interleave_hi(**y),
3981                        BuiltinId::ByteAdd16 => (**x).byte_add(**y),
3982                        BuiltinId::Maddubs16 => (**x).maddubs_bytes(**y),
3983                        _ => (**x).packus_bytes(**y),
3984                    };
3985                    r.map(|v| RuntimeValue::Lanes(Rc::new(v)))
3986                        .ok_or_else(|| "byte-lane op requires two Lanes16Word8".to_string())
3987                }
3988                _ => Err(format!(
3989                    "byte-lane op requires two Lanes16Word8, got {} and {}",
3990                    a.type_name(),
3991                    b.type_name()
3992                )),
3993            }
3994        }
3995        BuiltinId::ShrBytes16 => {
3996            let n = args.remove(1);
3997            let v = args.remove(0);
3998            match (&v, &n) {
3999                (RuntimeValue::Lanes(x), RuntimeValue::Int(k)) => (**x)
4000                    .shr_bytes(*k as u32)
4001                    .map(|r| RuntimeValue::Lanes(Rc::new(r)))
4002                    .ok_or_else(|| "shrBytes16() requires a Lanes16Word8".to_string()),
4003                _ => Err(format!(
4004                    "shrBytes16() requires a Lanes16Word8 and an Int, got {} and {}",
4005                    v.type_name(),
4006                    n.type_name()
4007                )),
4008            }
4009        }
4010        BuiltinId::Lanes8Word32 => {
4011            // Pack a Seq of Word32 (or Int) into one 8-lane SIMD vector — the constructor a Logos
4012            // lane kernel uses to load its working state.
4013            let s = args.remove(0);
4014            match s {
4015                RuntimeValue::List(items) => {
4016                    let vals = items.borrow().to_values();
4017                    let mut words = Vec::with_capacity(vals.len());
4018                    for v in &vals {
4019                        match v {
4020                            RuntimeValue::Word(WordVal::W32(w)) => words.push(*w),
4021                            RuntimeValue::Int(n) => words.push(Word32(*n as u32)),
4022                            other => {
4023                                return Err(format!(
4024                                    "lanes8Word32() needs a Seq of Word32, found {}",
4025                                    other.type_name()
4026                                ))
4027                            }
4028                        }
4029                    }
4030                    Ok(RuntimeValue::Lanes(Rc::new(LanesVal::L8W32(
4031                        logicaffeine_base::Lanes8Word32::from_words(&words),
4032                    ))))
4033                }
4034                other => Err(format!(
4035                    "lanes8Word32() requires a Seq of Word32, got {}",
4036                    other.type_name()
4037                )),
4038            }
4039        }
4040        BuiltinId::IntOfWord32 => {
4041            // The unsigned value of a Word32 as an Int (0..2³²−1) — for byte serialization.
4042            let x = args.remove(0);
4043            match x {
4044                RuntimeValue::Word(w) => Ok(RuntimeValue::Int(w.to_u64() as i64)),
4045                RuntimeValue::Int(n) => Ok(RuntimeValue::Int(n)),
4046                other => Err(format!(
4047                    "intOfWord32() requires a Word32, got {}",
4048                    other.type_name()
4049                )),
4050            }
4051        }
4052        BuiltinId::IntOfWord64 => {
4053            // The value of a Word64 as an Int (Keccak byte-masked lanes).
4054            let x = args.remove(0);
4055            match x {
4056                RuntimeValue::Word(w) => Ok(RuntimeValue::Int(w.to_u64() as i64)),
4057                RuntimeValue::Int(n) => Ok(RuntimeValue::Int(n)),
4058                other => Err(format!(
4059                    "intOfWord64() requires a Word64, got {}",
4060                    other.type_name()
4061                )),
4062            }
4063        }
4064        BuiltinId::Word64Shl | BuiltinId::Word64Shr => {
4065            let is_shl = matches!(id, BuiltinId::Word64Shl);
4066            let w = args.remove(0);
4067            let n = args.remove(0);
4068            let wv = match w {
4069                RuntimeValue::Word(w) => w.to_u64(),
4070                RuntimeValue::Int(v) => v as u64,
4071                other => {
4072                    return Err(format!(
4073                        "word64 shift requires a Word64, got {}",
4074                        other.type_name()
4075                    ))
4076                }
4077            };
4078            let nv = match n {
4079                RuntimeValue::Int(v) => v as u32,
4080                other => {
4081                    return Err(format!(
4082                        "word64 shift amount requires an Int, got {}",
4083                        other.type_name()
4084                    ))
4085                }
4086            };
4087            let r = if is_shl {
4088                wv.wrapping_shl(nv)
4089            } else {
4090                wv.wrapping_shr(nv)
4091            };
4092            Ok(RuntimeValue::Word(WordVal::W64(Word64(r))))
4093        }
4094        BuiltinId::Word64And => {
4095            let a = args.remove(0);
4096            let b = args.remove(0);
4097            let av = match a {
4098                RuntimeValue::Word(w) => w.to_u64(),
4099                RuntimeValue::Int(v) => v as u64,
4100                other => {
4101                    return Err(format!(
4102                        "word64And requires a Word64, got {}",
4103                        other.type_name()
4104                    ))
4105                }
4106            };
4107            let bv = match b {
4108                RuntimeValue::Word(w) => w.to_u64(),
4109                RuntimeValue::Int(v) => v as u64,
4110                other => {
4111                    return Err(format!(
4112                        "word64And requires a Word64, got {}",
4113                        other.type_name()
4114                    ))
4115                }
4116            };
4117            Ok(RuntimeValue::Word(WordVal::W64(Word64(av & bv))))
4118        }
4119        BuiltinId::Word32Shr => {
4120            let w = args.remove(0);
4121            let n = args.remove(0);
4122            let wv = match w {
4123                RuntimeValue::Word(word) => word.to_u64() as u32,
4124                RuntimeValue::Int(v) => v as u32,
4125                other => {
4126                    return Err(format!(
4127                        "word32Shr requires a Word32, got {}",
4128                        other.type_name()
4129                    ))
4130                }
4131            };
4132            let nv = match n {
4133                RuntimeValue::Int(v) => v as u32,
4134                other => {
4135                    return Err(format!(
4136                        "word32Shr amount requires an Int, got {}",
4137                        other.type_name()
4138                    ))
4139                }
4140            };
4141            Ok(RuntimeValue::Word(WordVal::W32(Word32(
4142                wv.wrapping_shr(nv),
4143            ))))
4144        }
4145        BuiltinId::Word16Make => {
4146            // Low 16 bits of an Int as a Word16 — the ring ℤ/2¹⁶, wrapping at its own width.
4147            let n = args.remove(0);
4148            match n {
4149                RuntimeValue::Int(v) => Ok(RuntimeValue::Word(WordVal::W16(Word16(v as u16)))),
4150                RuntimeValue::BigInt(v) => Ok(RuntimeValue::Word(WordVal::W16(Word16(
4151                    v.wrapping_u64() as u16,
4152                )))),
4153                RuntimeValue::Word(w) => {
4154                    Ok(RuntimeValue::Word(WordVal::W16(Word16(w.to_u64() as u16))))
4155                }
4156                other => Err(format!(
4157                    "word16() requires an Int, got {}",
4158                    other.type_name()
4159                )),
4160            }
4161        }
4162        BuiltinId::IntOfWord16 => {
4163            // The unsigned value of a Word16 as an Int (0..2¹⁶−1).
4164            let x = args.remove(0);
4165            match x {
4166                RuntimeValue::Word(WordVal::W16(w)) => Ok(RuntimeValue::Int(w.0 as i64)),
4167                RuntimeValue::Int(n) => Ok(RuntimeValue::Int(n as u16 as i64)),
4168                other => Err(format!(
4169                    "intOfWord16() requires a Word16, got {}",
4170                    other.type_name()
4171                )),
4172            }
4173        }
4174        BuiltinId::Word8Make => {
4175            // Low 8 bits of an Int as a Word8 — the ring ℤ/2⁸, wrapping at its own width.
4176            let n = args.remove(0);
4177            match n {
4178                RuntimeValue::Int(v) => Ok(RuntimeValue::Word(WordVal::W8(Word8(v as u8)))),
4179                RuntimeValue::BigInt(v) => Ok(RuntimeValue::Word(WordVal::W8(Word8(
4180                    v.wrapping_u64() as u8,
4181                )))),
4182                RuntimeValue::Word(w) => {
4183                    Ok(RuntimeValue::Word(WordVal::W8(Word8(w.to_u64() as u8))))
4184                }
4185                other => Err(format!(
4186                    "word8() requires an Int, got {}",
4187                    other.type_name()
4188                )),
4189            }
4190        }
4191        BuiltinId::IntOfWord8 => {
4192            // The unsigned value of a Word8 as an Int (0..255).
4193            let x = args.remove(0);
4194            match x {
4195                RuntimeValue::Word(WordVal::W8(w)) => Ok(RuntimeValue::Int(w.0 as i64)),
4196                RuntimeValue::Int(n) => Ok(RuntimeValue::Int(n as u8 as i64)),
4197                other => Err(format!(
4198                    "intOfWord8() requires a Word8, got {}",
4199                    other.type_name()
4200                )),
4201            }
4202        }
4203        BuiltinId::Lanes4Word64 => {
4204            // Pack a Seq of Word64/Int into one 4-lane u64 vector (the Poly1305 limb working set).
4205            let s = args.remove(0);
4206            match s {
4207                RuntimeValue::List(items) => {
4208                    let vals = items.borrow().to_values();
4209                    let mut words = Vec::with_capacity(vals.len());
4210                    for v in &vals {
4211                        match v {
4212                            RuntimeValue::Word(WordVal::W64(w)) => words.push(*w),
4213                            RuntimeValue::Int(n) => words.push(Word64(*n as u64)),
4214                            other => {
4215                                return Err(format!(
4216                                    "lanes4Word64() needs a Seq of Word64/Int, found {}",
4217                                    other.type_name()
4218                                ))
4219                            }
4220                        }
4221                    }
4222                    Ok(RuntimeValue::Lanes(Rc::new(LanesVal::L4W64(
4223                        logicaffeine_base::Lanes4Word64::from_words(&words),
4224                    ))))
4225                }
4226                other => Err(format!(
4227                    "lanes4Word64() requires a Seq, got {}",
4228                    other.type_name()
4229                )),
4230            }
4231        }
4232        BuiltinId::SeqOfLanes4 => {
4233            // Unpack a lane vector into a Seq of its lanes as Int.
4234            let v = args.remove(0);
4235            match v {
4236                RuntimeValue::Lanes(lanes) => {
4237                    let vals: Vec<RuntimeValue> = (0..lanes.lanes())
4238                        .map(|i| RuntimeValue::Int(lanes.lane(i) as i64))
4239                        .collect();
4240                    Ok(RuntimeValue::List(Rc::new(std::cell::RefCell::new(
4241                        crate::interpreter::ListRepr::from_values(vals),
4242                    ))))
4243                }
4244                other => Err(format!(
4245                    "seqOfLanes4() requires a lane vector, got {}",
4246                    other.type_name()
4247                )),
4248            }
4249        }
4250        BuiltinId::Mul32x32To64 => {
4251            // Lane-wise widening multiply of the low 32 bits (vpmuludq) — the Poly1305 limb product.
4252            let a = args.remove(0);
4253            let b = args.remove(0);
4254            match (a, b) {
4255                (RuntimeValue::Lanes(la), RuntimeValue::Lanes(lb)) => match la.mul_lo32_wide(*lb) {
4256                    Some(v) => Ok(RuntimeValue::Lanes(Rc::new(v))),
4257                    None => Err(format!(
4258                        "mul32x32to64 requires two Lanes4Word64, got {} and {}",
4259                        la.type_name(),
4260                        lb.type_name()
4261                    )),
4262                },
4263                (a, b) => Err(format!(
4264                    "mul32x32to64 requires two lane vectors, got {} and {}",
4265                    a.type_name(),
4266                    b.type_name()
4267                )),
4268            }
4269        }
4270        BuiltinId::HsumLanes4 => {
4271            // The horizontal sum of a lane vector's lanes, as an Int.
4272            let v = args.remove(0);
4273            match v {
4274                RuntimeValue::Lanes(lanes) => Ok(RuntimeValue::Int(lanes.hsum())),
4275                other => Err(format!(
4276                    "hsumLanes4 requires a lane vector, got {}",
4277                    other.type_name()
4278                )),
4279            }
4280        }
4281        BuiltinId::Splat4Word64 => {
4282            // Broadcast a Word64 into all 4 Keccak lanes. The tree-walker/VM run the same scalar
4283            // fallback the AOT path uses when AVX2 is off, so the 4-way lane Keccak
4284            // (keccakF4Logos → keccakSponge4 → ML-DSA ExpandA) stays tw == VM == AOT bit-exact.
4285            let w = args.remove(0);
4286            match w {
4287                RuntimeValue::Word(WordVal::W64(x)) => Ok(RuntimeValue::Lanes(Rc::new(
4288                    LanesVal::L4W64(logicaffeine_base::Lanes4Word64::splat(x.0)),
4289                ))),
4290                RuntimeValue::Int(n) => Ok(RuntimeValue::Lanes(Rc::new(LanesVal::L4W64(
4291                    logicaffeine_base::Lanes4Word64::splat(n as u64),
4292                )))),
4293                other => Err(format!(
4294                    "splat4Word64() requires a Word64, got {}",
4295                    other.type_name()
4296                )),
4297            }
4298        }
4299        BuiltinId::AndNot4 => {
4300            // Keccak χ's (¬a) ∧ b per lane — the scalar mirror of the AVX2 vpandn.
4301            let a = args.remove(0);
4302            let b = args.remove(0);
4303            match (a, b) {
4304                (RuntimeValue::Lanes(la), RuntimeValue::Lanes(lb)) => match (&*la, &*lb) {
4305                    (LanesVal::L4W64(x), LanesVal::L4W64(y)) => Ok(RuntimeValue::Lanes(Rc::new(
4306                        LanesVal::L4W64((*x).andnot(*y)),
4307                    ))),
4308                    _ => Err(format!(
4309                        "andNot4 requires two Lanes4Word64, got {} and {}",
4310                        la.type_name(),
4311                        lb.type_name()
4312                    )),
4313                },
4314                (a, b) => Err(format!(
4315                    "andNot4 requires two lane vectors, got {} and {}",
4316                    a.type_name(),
4317                    b.type_name()
4318                )),
4319            }
4320        }
4321        BuiltinId::Lanes16Word16 => {
4322            // Pack a Seq of Word16/Int into one 16-lane NTT coefficient vector.
4323            let s = args.remove(0);
4324            match s {
4325                RuntimeValue::List(items) => {
4326                    let vals = items.borrow().to_values();
4327                    let mut words = Vec::with_capacity(vals.len());
4328                    for v in &vals {
4329                        match v {
4330                            RuntimeValue::Word(WordVal::W16(w)) => words.push(*w),
4331                            RuntimeValue::Int(n) => words.push(Word16(*n as u16)),
4332                            other => {
4333                                return Err(format!(
4334                                    "lanes16Word16() needs a Seq of Word16/Int, found {}",
4335                                    other.type_name()
4336                                ))
4337                            }
4338                        }
4339                    }
4340                    Ok(RuntimeValue::Lanes(Rc::new(LanesVal::L16W16(
4341                        logicaffeine_base::Lanes16Word16::from_words(&words),
4342                    ))))
4343                }
4344                other => Err(format!(
4345                    "lanes16Word16() requires a Seq, got {}",
4346                    other.type_name()
4347                )),
4348            }
4349        }
4350        BuiltinId::SeqOfLanes16 => {
4351            // Unpack a lane vector into a Seq of its lanes as Int (same as seqOfLanes4, any config).
4352            let v = args.remove(0);
4353            match v {
4354                RuntimeValue::Lanes(lanes) => {
4355                    let vals: Vec<RuntimeValue> = (0..lanes.lanes())
4356                        .map(|i| RuntimeValue::Int(lanes.lane(i) as i64))
4357                        .collect();
4358                    Ok(RuntimeValue::List(Rc::new(std::cell::RefCell::new(
4359                        crate::interpreter::ListRepr::from_values(vals),
4360                    ))))
4361                }
4362                other => Err(format!(
4363                    "seqOfLanes16() requires a lane vector, got {}",
4364                    other.type_name()
4365                )),
4366            }
4367        }
4368        BuiltinId::Splat16Word16 => {
4369            // Broadcast a Word16/Int into all 16 lanes (the NTT loads a shared zeta/constant).
4370            let x = args.remove(0);
4371            let w = match x {
4372                RuntimeValue::Word(WordVal::W16(w)) => w.0,
4373                RuntimeValue::Int(n) => n as u16,
4374                other => {
4375                    return Err(format!(
4376                        "splat16Word16() requires a Word16/Int, got {}",
4377                        other.type_name()
4378                    ))
4379                }
4380            };
4381            Ok(RuntimeValue::Lanes(Rc::new(LanesVal::L16W16(
4382                logicaffeine_base::Lanes16Word16::splat(w),
4383            ))))
4384        }
4385        BuiltinId::Mulhi16 => {
4386            // Lane-wise SIGNED high-16 multiply (vpmulhw) — the Montgomery butterfly's mulhi.
4387            let a = args.remove(0);
4388            let b = args.remove(0);
4389            match (a, b) {
4390                (RuntimeValue::Lanes(la), RuntimeValue::Lanes(lb)) => match la.mulhi(*lb) {
4391                    Some(v) => Ok(RuntimeValue::Lanes(Rc::new(v))),
4392                    None => Err(format!(
4393                        "mulhi16 requires two Lanes16Word16, got {} and {}",
4394                        la.type_name(),
4395                        lb.type_name()
4396                    )),
4397                },
4398                (a, b) => Err(format!(
4399                    "mulhi16 requires two lane vectors, got {} and {}",
4400                    a.type_name(),
4401                    b.type_name()
4402                )),
4403            }
4404        }
4405        BuiltinId::Montmul32 => {
4406            // The signed i32 Montgomery multiply (ML-DSA butterfly) — montmul32(a, b, q, qinv).
4407            let a = args.remove(0);
4408            let b = args.remove(0);
4409            let q = args.remove(0);
4410            let qi = args.remove(0);
4411            match (a, b, q, qi) {
4412                (
4413                    RuntimeValue::Lanes(la),
4414                    RuntimeValue::Lanes(lb),
4415                    RuntimeValue::Lanes(lq),
4416                    RuntimeValue::Lanes(lqi),
4417                ) => match la.montmul32(*lb, *lq, *lqi) {
4418                    Some(v) => Ok(RuntimeValue::Lanes(Rc::new(v))),
4419                    None => Err(format!(
4420                        "montmul32 requires four Lanes8Word32, got {}, {}, {}, {}",
4421                        la.type_name(),
4422                        lb.type_name(),
4423                        lq.type_name(),
4424                        lqi.type_name()
4425                    )),
4426                },
4427                (a, b, q, qi) => Err(format!(
4428                    "montmul32 requires four lane vectors, got {}, {}, {}, {}",
4429                    a.type_name(),
4430                    b.type_name(),
4431                    q.type_name(),
4432                    qi.type_name()
4433                )),
4434            }
4435        }
4436        BuiltinId::NttBcastLo | BuiltinId::NttBcastHi => {
4437            // The within-vector NTT source duplications, at stride h (vperm2i128/vpshufd).
4438            let is_low = matches!(id, BuiltinId::NttBcastLo);
4439            let name = if is_low { "nttBcastLo" } else { "nttBcastHi" };
4440            let v = args.remove(0);
4441            let h = ntt_stride(args.remove(0), name)?;
4442            match v {
4443                RuntimeValue::Lanes(lv) => {
4444                    let r = if is_low {
4445                        lv.ntt_bcast_lo(h)
4446                    } else {
4447                        lv.ntt_bcast_hi(h)
4448                    };
4449                    match r {
4450                        Some(out) => Ok(RuntimeValue::Lanes(Rc::new(out))),
4451                        None => Err(format!(
4452                            "{} requires a Lanes16Word16, got {}",
4453                            name,
4454                            lv.type_name()
4455                        )),
4456                    }
4457                }
4458                other => Err(format!(
4459                    "{} requires a lane vector, got {}",
4460                    name,
4461                    other.type_name()
4462                )),
4463            }
4464        }
4465        BuiltinId::NttBlend => {
4466            // Recombine the +/− halves of the within-vector butterfly, at stride h (vperm2i128/vpblendd).
4467            let a = args.remove(0);
4468            let b = args.remove(0);
4469            let h = ntt_stride(args.remove(0), "nttBlend")?;
4470            match (a, b) {
4471                (RuntimeValue::Lanes(la), RuntimeValue::Lanes(lb)) => match la.ntt_blend(*lb, h) {
4472                    Some(v) => Ok(RuntimeValue::Lanes(Rc::new(v))),
4473                    None => Err(format!(
4474                        "nttBlend requires two Lanes16Word16, got {} and {}",
4475                        la.type_name(),
4476                        lb.type_name()
4477                    )),
4478                },
4479                (a, b) => Err(format!(
4480                    "nttBlend requires two lane vectors, got {} and {}",
4481                    a.type_name(),
4482                    b.type_name()
4483                )),
4484            }
4485        }
4486        BuiltinId::Splat8Word32 => {
4487            // Broadcast a Word32 (or Int) into all 8 lanes.
4488            let x = args.remove(0);
4489            let w = match x {
4490                RuntimeValue::Word(WordVal::W32(w)) => w,
4491                RuntimeValue::Int(n) => Word32(n as u32),
4492                other => {
4493                    return Err(format!(
4494                        "splat8Word32() requires a Word32, got {}",
4495                        other.type_name()
4496                    ))
4497                }
4498            };
4499            Ok(RuntimeValue::Lanes(Rc::new(LanesVal::L8W32(
4500                logicaffeine_base::Lanes8Word32::splat(w.0),
4501            ))))
4502        }
4503        BuiltinId::SeqOfLanes8 => {
4504            // Unpack a lane vector back into a Seq of 8 Word32 — read its lanes out.
4505            let v = args.remove(0);
4506            match v {
4507                RuntimeValue::Lanes(lanes) => match *lanes {
4508                    LanesVal::L8W32(lv) => {
4509                        let vals: Vec<RuntimeValue> = lv
4510                            .to_words()
4511                            .iter()
4512                            .map(|w| RuntimeValue::Word(WordVal::W32(*w)))
4513                            .collect();
4514                        Ok(RuntimeValue::List(Rc::new(std::cell::RefCell::new(
4515                            crate::interpreter::ListRepr::from_values(vals),
4516                        ))))
4517                    }
4518                    other => Err(format!(
4519                        "seqOfLanes8() requires a Lanes8Word32, got {}",
4520                        other.type_name()
4521                    )),
4522                },
4523                other => Err(format!(
4524                    "seqOfLanes8() requires a Lanes8Word32, got {}",
4525                    other.type_name()
4526                )),
4527            }
4528        }
4529        BuiltinId::RunAccepted => {
4530            // run_accepted(fn, arg, lo, hi): the receiver's typed, bounded acceptance
4531            // contract for a SHIPPED computation — validate the function's shape and the
4532            // argument's range, then evaluate in the sandbox. Out-of-range is REFUSED, never
4533            // clamped; an ordinary (non-shipped) closure is refused at the signature check.
4534            let int_arg = |v: &RuntimeValue, what: &str| -> Result<i64, String> {
4535                match v {
4536                    RuntimeValue::Int(n) => Ok(*n),
4537                    other => Err(format!(
4538                        "run_accepted: {what} must be an Int, got {}",
4539                        other.type_name()
4540                    )),
4541                }
4542            };
4543            let arg = int_arg(&args[1], "the argument")?;
4544            let lo = int_arg(&args[2], "the lower bound")?;
4545            let hi = int_arg(&args[3], "the upper bound")?;
4546            let contract = crate::semantics::acceptance::AcceptanceContract::new(lo, hi);
4547            contract.apply(&args[0], arg).map(RuntimeValue::Int)
4548        }
4549        // --- DOM (the browser tier): operate on the thread-local `dom::DomRecorder`
4550        // so the tree-walker and VM agree; the wasm tier lowers the same calls to
4551        // `dom_*` host imports. Element handles are `Int`; effect ops return Nothing. ---
4552        BuiltinId::DomBody => Ok(RuntimeValue::Int(crate::semantics::dom::body())),
4553        BuiltinId::DomCreateElement => {
4554            let tag = args.remove(0);
4555            Ok(RuntimeValue::Int(crate::semantics::dom::create_element(
4556                &tag.to_display_string(),
4557            )))
4558        }
4559        BuiltinId::DomCreateTextNode => {
4560            let text = args.remove(0);
4561            Ok(RuntimeValue::Int(crate::semantics::dom::create_text_node(
4562                &text.to_display_string(),
4563            )))
4564        }
4565        BuiltinId::DomSetText => {
4566            let el = dom_handle(args.remove(0), "setText")?;
4567            let text = args.remove(0);
4568            crate::semantics::dom::set_text(el, &text.to_display_string());
4569            Ok(RuntimeValue::Nothing)
4570        }
4571        BuiltinId::DomSetHtml => {
4572            let el = dom_handle(args.remove(0), "setHtml")?;
4573            let html = args.remove(0);
4574            crate::semantics::dom::set_html(el, &html.to_display_string());
4575            Ok(RuntimeValue::Nothing)
4576        }
4577        BuiltinId::DomBeginPaint => Err(BEGIN_PAINT_RETIRED.to_string()),
4578        BuiltinId::DomClearChildren => {
4579            let el = dom_handle(args.remove(0), "clearChildren")?;
4580            crate::semantics::dom::clear_children(el);
4581            Ok(RuntimeValue::Nothing)
4582        }
4583        BuiltinId::DomMoveChildren => Err(MOVE_CHILDREN_RETIRED.to_string()),
4584        // ★ THE REFERENCE TIER SUBSCRIBES BY REGISTERING, not by calling this. A page under
4585        // `largo test` has no relay and no network: its subscriptions live in the listener table
4586        // and a `## Test` causes one with `Raise`. So this is the BROWSER's half, and here it is
4587        // the no-op that keeps the two tiers running the same program — the same treatment the
4588        // window-event registration gets.
4589        BuiltinId::DomOnMessage => Ok(RuntimeValue::Nothing),
4590        BuiltinId::DomSetAttribute => {
4591            let el = dom_handle(args.remove(0), "setAttribute")?;
4592            let name = args.remove(0);
4593            let value = args.remove(0);
4594            // Through `set_attribute_value`, so an HTML boolean attribute is a PRESENCE on this
4595            // tier exactly as it is on the reference tier — `disabled={false}` writes nothing.
4596            crate::semantics::dom::set_attribute_value(el, &name.to_display_string(), &value);
4597            Ok(RuntimeValue::Nothing)
4598        }
4599        BuiltinId::DomAppendChild => {
4600            let parent = dom_handle(args.remove(0), "appendChild")?;
4601            let child = dom_handle(args.remove(0), "appendChild")?;
4602            crate::semantics::dom::append_child(parent, child);
4603            Ok(RuntimeValue::Nothing)
4604        }
4605        BuiltinId::DomGetText => {
4606            let el = dom_handle(args.remove(0), "getText")?;
4607            Ok(RuntimeValue::Text(Rc::new(
4608                crate::semantics::dom::get_text(el),
4609            )))
4610        }
4611        BuiltinId::DomGetValue => {
4612            let el = dom_handle(args.remove(0), "getValue")?;
4613            Ok(RuntimeValue::Text(Rc::new(
4614                crate::semantics::dom::get_value(el),
4615            )))
4616        }
4617        BuiltinId::DomSetValue => {
4618            let el = dom_handle(args.remove(0), "setValue")?;
4619            let value = args.remove(0);
4620            crate::semantics::dom::set_value(el, &value.to_display_string());
4621            Ok(RuntimeValue::Nothing)
4622        }
4623        BuiltinId::DomApplyPatches => {
4624            let buffer = args.remove(0);
4625            let bytes = crate::semantics::patch::bytes_from_value(&buffer)?;
4626            // Decode the WHOLE buffer before touching the document: all-or-nothing, so a
4627            // malformed stream never leaves a half-built page behind.
4628            let ops = crate::semantics::patch::decode(&bytes)?;
4629            crate::semantics::patch::apply(&ops)?;
4630            Ok(RuntimeValue::Nothing)
4631        }
4632        BuiltinId::DomApplyWords => {
4633            let count = |v: RuntimeValue, what: &str| match v {
4634                RuntimeValue::Int(n) => Ok(n),
4635                other => Err(format!(
4636                    "applyPatchWords takes its {what} count as an Int, got {}",
4637                    other.type_name()
4638                )),
4639            };
4640            let words = args.remove(0);
4641            let word_count = count(args.remove(0), "word")?;
4642            let strings = args.remove(0);
4643            let string_count = count(args.remove(0), "string")?;
4644            let words = crate::semantics::patch::words_from_value(&words, word_count)?;
4645            let strings = crate::semantics::patch::strings_from_value(&strings, string_count)?;
4646            let ops = crate::semantics::patch::decode_words(&words, &strings)?;
4647            Ok(RuntimeValue::Int(crate::semantics::patch::apply(&ops)?))
4648        }
4649        // Text in, text out, and NOTHING IS SPECIAL: the browser API is length-delimited, so a
4650        // quote, a newline and a NUL are ordinary content with no separator to escape.
4651        BuiltinId::StorageSet => {
4652            let area = args.remove(0).to_display_string();
4653            let key = args.remove(0).to_display_string();
4654            let value = args.remove(0).to_display_string();
4655            crate::semantics::storage::set(&area, &key, &value)?;
4656            Ok(RuntimeValue::Nothing)
4657        }
4658        // `Nothing` for an absent key, the Text for a present one — a stored `""` is a value and
4659        // must not read as an absence.
4660        BuiltinId::StorageGet => {
4661            let area = args.remove(0).to_display_string();
4662            let key = args.remove(0).to_display_string();
4663            // ★ A REAL OPTION, not the payload-or-sentinel it used to be.
4664            //
4665            // This returned a bare `Text` when present and `Nothing` when absent — the transparent
4666            // encoding — and that worked only while `Inspect`'s catch-all answered a `Some` arm
4667            // with "any value that is not the sentinel". Giving `Option` a real tag removed that
4668            // catch-all, and a PRESENT stored value started taking the `None` arm
4669            // (`storage_lock::a_missing_key_is_none_and_not_an_empty_string`).
4670            //
4671            // Display is unchanged by R1 (an Option prints its payload, or `nothing`), and
4672            // `is equal to nothing` is unchanged by R2, so every existing reader sees what it saw.
4673            Ok(match crate::semantics::storage::get(&area, &key)? {
4674                Some(v) => crate::interpreter::option_some(RuntimeValue::Text(Rc::new(v))),
4675                None => crate::interpreter::option_none(),
4676            })
4677        }
4678        BuiltinId::StorageGetOr => {
4679            let area = args.remove(0).to_display_string();
4680            let key = args.remove(0).to_display_string();
4681            let fallback = args.remove(0);
4682            Ok(match crate::semantics::storage::get(&area, &key)? {
4683                Some(v) => RuntimeValue::Text(Rc::new(v)),
4684                None => fallback,
4685            })
4686        }
4687        BuiltinId::StorageRemove => {
4688            let area = args.remove(0).to_display_string();
4689            let key = args.remove(0).to_display_string();
4690            crate::semantics::storage::remove(&area, &key)?;
4691            Ok(RuntimeValue::Nothing)
4692        }
4693        BuiltinId::DomSetChecked => {
4694            let el = dom_handle(args.remove(0), "setChecked")?;
4695            let on = args.remove(0);
4696            crate::semantics::dom::set_checked(el, on.is_truthy());
4697            Ok(RuntimeValue::Nothing)
4698        }
4699        BuiltinId::DomPreventDefault => {
4700            let el = dom_handle(args.remove(0), "preventDefault")?;
4701            let event = args.remove(0).to_display_string();
4702            crate::semantics::dom::prevent_default(el, &event);
4703            Ok(RuntimeValue::Nothing)
4704        }
4705        BuiltinId::DomSetStream => {
4706            let el = dom_handle(args.remove(0), "setStream")?;
4707            let stream = match args.remove(0) {
4708                RuntimeValue::Int(n) => n,
4709                other => {
4710                    return Err(format!(
4711                        "setStream expects an Int media-stream handle, got {}",
4712                        other.type_name()
4713                    ))
4714                }
4715            };
4716            crate::semantics::dom::set_stream(el, stream);
4717            Ok(RuntimeValue::Nothing)
4718        }
4719        BuiltinId::RtcPeerConnection => Ok(RuntimeValue::Int(
4720            crate::semantics::dom::rtc_peer_connection(),
4721        )),
4722        BuiltinId::RtcDataChannel => {
4723            let pc = dom_handle(args.remove(0), "dataChannel")?;
4724            let label = args.remove(0);
4725            Ok(RuntimeValue::Int(crate::semantics::dom::rtc_data_channel(
4726                pc,
4727                &label.to_display_string(),
4728            )))
4729        }
4730        BuiltinId::RtcCreateOffer => {
4731            let pc = dom_handle(args.remove(0), "createOffer")?;
4732            Ok(RuntimeValue::Text(Rc::new(
4733                crate::semantics::dom::rtc_create_offer(pc),
4734            )))
4735        }
4736        BuiltinId::RtcCreateAnswer => {
4737            let pc = dom_handle(args.remove(0), "createAnswer")?;
4738            Ok(RuntimeValue::Text(Rc::new(
4739                crate::semantics::dom::rtc_create_answer(pc),
4740            )))
4741        }
4742        BuiltinId::RtcSetLocal => {
4743            let pc = dom_handle(args.remove(0), "setLocalDescription")?;
4744            let sdp = args.remove(0);
4745            crate::semantics::dom::rtc_set_local(pc, &sdp.to_display_string());
4746            Ok(RuntimeValue::Nothing)
4747        }
4748        BuiltinId::RtcSetRemote => {
4749            let pc = dom_handle(args.remove(0), "setRemoteDescription")?;
4750            let sdp = args.remove(0);
4751            crate::semantics::dom::rtc_set_remote(pc, &sdp.to_display_string());
4752            Ok(RuntimeValue::Nothing)
4753        }
4754        BuiltinId::RtcAddIce => {
4755            let pc = dom_handle(args.remove(0), "addIceCandidate")?;
4756            let candidate = args.remove(0);
4757            crate::semantics::dom::rtc_add_ice(pc, &candidate.to_display_string());
4758            Ok(RuntimeValue::Nothing)
4759        }
4760        BuiltinId::RtcSend => {
4761            let channel = dom_handle(args.remove(0), "channelSend")?;
4762            let data = args.remove(0);
4763            let bytes = byte_seq(&data)?.len() as u64;
4764            crate::semantics::dom::rtc_send(channel, bytes);
4765            Ok(RuntimeValue::Nothing)
4766        }
4767        BuiltinId::DomQuerySelector => {
4768            let sel = args.remove(0);
4769            Ok(RuntimeValue::Int(crate::semantics::dom::query_selector(
4770                &sel.to_display_string(),
4771            )))
4772        }
4773        BuiltinId::DomAddEventListener => {
4774            let el = dom_handle(args.remove(0), "addEventListener")?;
4775            let event = args.remove(0).to_display_string();
4776            let handler = args.remove(0); // the LOGOS closure
4777            crate::semantics::dom::add_event_listener(el, &event, handler);
4778            Ok(RuntimeValue::Nothing)
4779        }
4780        BuiltinId::DomEventValue => {
4781            let _event = args.remove(0);
4782            Ok(RuntimeValue::Text(Rc::new(
4783                crate::semantics::dom::event_value(),
4784            )))
4785        }
4786        BuiltinId::DomEventKey => {
4787            let _event = args.remove(0);
4788            Ok(RuntimeValue::Text(Rc::new(
4789                crate::semantics::dom::event_key(),
4790            )))
4791        }
4792        BuiltinId::DomEventTarget => {
4793            let _event = args.remove(0);
4794            Ok(RuntimeValue::Int(crate::semantics::dom::event_target()))
4795        }
4796        BuiltinId::DomFetchText => {
4797            let url = args.remove(0).to_display_string();
4798            let on_done = args.remove(0); // the completion closure
4799            crate::semantics::dom::fetch_start(&url, on_done);
4800            Ok(RuntimeValue::Nothing)
4801        }
4802        BuiltinId::DomResponseText => Ok(RuntimeValue::Text(Rc::new(
4803            crate::semantics::dom::response_text(),
4804        ))),
4805        BuiltinId::DomFetchSend => {
4806            let method = args.remove(0).to_display_string();
4807            let url = args.remove(0).to_display_string();
4808            let body = args.remove(0).to_display_string();
4809            let headers = fetch_header_pairs(&args.remove(0))?;
4810            let on_done = args.remove(0); // the completion closure
4811            Ok(RuntimeValue::Int(crate::semantics::dom::fetch_send(
4812                &method, &url, &body, headers, on_done,
4813            )))
4814        }
4815        BuiltinId::DomResponseStatus => {
4816            let req = dom_handle(args.remove(0), "responseStatus")?;
4817            Ok(RuntimeValue::Int(crate::semantics::dom::response_status(
4818                req,
4819            )))
4820        }
4821        BuiltinId::DomResponseBody => {
4822            let req = dom_handle(args.remove(0), "responseBody")?;
4823            Ok(RuntimeValue::Text(Rc::new(
4824                crate::semantics::dom::response_body(req),
4825            )))
4826        }
4827        BuiltinId::DomResponseHeader => {
4828            let req = dom_handle(args.remove(0), "responseHeader")?;
4829            let name = args.remove(0).to_display_string();
4830            Ok(RuntimeValue::Text(Rc::new(
4831                crate::semantics::dom::response_header(req, &name),
4832            )))
4833        }
4834        BuiltinId::DomResponseError => {
4835            let req = dom_handle(args.remove(0), "responseError")?;
4836            Ok(RuntimeValue::Text(Rc::new(
4837                crate::semantics::dom::response_error(req),
4838            )))
4839        }
4840        BuiltinId::DomFetchAbort => {
4841            let req = dom_handle(args.remove(0), "fetchAbort")?;
4842            crate::semantics::dom::fetch_abort(req);
4843            Ok(RuntimeValue::Nothing)
4844        }
4845        BuiltinId::DomFetchSetTimeout => {
4846            let req = dom_handle(args.remove(0), "fetchSetTimeout")?;
4847            let millis = dom_handle(args.remove(0), "fetchSetTimeout")?;
4848            crate::semantics::dom::fetch_set_timeout(req, millis);
4849            Ok(RuntimeValue::Nothing)
4850        }
4851        // --- The history/location router. `routePath`/`routeQuery` read the location;
4852        // `navigate`/`replaceRoute` record a navigation; `onRoute` stores the popstate
4853        // handler closure (fired on command by the recorder's `deliver_pop`). ---
4854        BuiltinId::DomRoutePath => Ok(RuntimeValue::Text(Rc::new(
4855            crate::semantics::dom::route_path(),
4856        ))),
4857        BuiltinId::DomRouteQuery => {
4858            let name = args.remove(0).to_display_string();
4859            Ok(RuntimeValue::Text(Rc::new(
4860                crate::semantics::dom::route_query(&name),
4861            )))
4862        }
4863        BuiltinId::DomClipboardWrite => {
4864            let t = args.remove(0).to_display_string();
4865            crate::semantics::dom::write_clipboard(&t);
4866            Ok(RuntimeValue::Nothing)
4867        }
4868        BuiltinId::DomDownloadFile => {
4869            let content = args.remove(0).to_display_string();
4870            let name = args.remove(0).to_display_string();
4871            crate::semantics::dom::offer_download(&name, &content);
4872            Ok(RuntimeValue::Nothing)
4873        }
4874        BuiltinId::DomNotify => {
4875            let message = args.remove(0).to_display_string();
4876            let tone = args.remove(0).to_display_string();
4877            crate::semantics::dom::notify(&message, &tone);
4878            Ok(RuntimeValue::Nothing)
4879        }
4880        BuiltinId::DomPublish => {
4881            let topic = args.remove(0).to_display_string();
4882            let message = args.remove(0).to_display_string();
4883            crate::semantics::dom::publish(&topic, &message);
4884            Ok(RuntimeValue::Nothing)
4885        }
4886        BuiltinId::DomElementCommand => {
4887            let el = dom_handle(args.remove(0), "elementCommand")?;
4888            let command = args.remove(0).to_display_string();
4889            // The in-process tiers hold the focus state the reference tier holds, so a page that
4890            // asks "who has the cursor" gets the same answer whichever tier ran it. The rest are
4891            // things only a real viewport can do; recording them is what a recorder is for.
4892            match command.as_str() {
4893                "focus" => crate::semantics::dom::element_focus(el),
4894                "blur" => crate::semantics::dom::element_blur(el),
4895                "scrollto" => crate::semantics::dom::scroll_to(el),
4896                "selecttext" => crate::semantics::dom::select_text(el),
4897                _ => {}
4898            }
4899            Ok(RuntimeValue::Nothing)
4900        }
4901        // The file the drop being delivered carries. A browser answers from the drop event itself
4902        // (`dom_event_file_*`, `runtime.js`, which reads the file's content BEFORE the turn runs);
4903        // an in-process tier answers from the file the host that delivered the drop handed over
4904        // (`semantics::dom::set_dropped_file`) — never a literal.
4905        BuiltinId::DomEventFileName => {
4906            let _ev = args.remove(0);
4907            Ok(RuntimeValue::Text(Rc::new(
4908                crate::semantics::dom::dropped_file().name,
4909            )))
4910        }
4911        BuiltinId::DomEventFileSize => {
4912            let _ev = args.remove(0);
4913            Ok(RuntimeValue::Int(
4914                crate::semantics::dom::dropped_file().size(),
4915            ))
4916        }
4917        BuiltinId::DomEventFileType => {
4918            let _ev = args.remove(0);
4919            Ok(RuntimeValue::Text(Rc::new(
4920                crate::semantics::dom::dropped_file()
4921                    .mime_type()
4922                    .to_string(),
4923            )))
4924        }
4925        BuiltinId::DomEventFileBytes => {
4926            let _ev = args.remove(0);
4927            Ok(bytes_to_seq(&crate::semantics::dom::dropped_file().bytes))
4928        }
4929        BuiltinId::DomListenFlags => {
4930            let el = dom_handle(args.remove(0), "listenFlags")?;
4931            let event = args.remove(0).to_display_string();
4932            let flags = match args.remove(0) {
4933                RuntimeValue::Int(n) if (0..32).contains(&n) => n as u8,
4934                RuntimeValue::Int(n) => {
4935                    return Err(format!(
4936                    "listenFlags takes flags from 0 to 31 (prevent 1, stop 2, once 4, capture 8, \
4937                         passive 16), got {n}"
4938                ))
4939                }
4940                other => {
4941                    return Err(format!(
4942                        "listenFlags takes its flags as an Int, got {}",
4943                        other.type_name()
4944                    ))
4945                }
4946            };
4947            crate::semantics::dom::listen(el, &event, flags);
4948            Ok(RuntimeValue::Nothing)
4949        }
4950        BuiltinId::DomAssignLocation => {
4951            let url = args.remove(0).to_display_string();
4952            crate::semantics::dom::request_load(&url);
4953            Ok(RuntimeValue::Nothing)
4954        }
4955        // Every in-process host keeps the journal (`world::journal`), so its detail is wanted.
4956        BuiltinId::DomJournalDetail => Ok(RuntimeValue::Bool(true)),
4957        // An in-process host moves the page's clock only by `Advance time by …`, which calls
4958        // `__lgx_tick` itself; there is no wall clock to wake the page from.
4959        BuiltinId::DomWakeAfter => Ok(RuntimeValue::Nothing),
4960        BuiltinId::DomEnterValue => {
4961            let verb = match args.remove(0).to_display_string().as_str() {
4962                "type" => crate::semantics::drive::Verb::Type,
4963                "choose" => crate::semantics::drive::Verb::Choose,
4964                other => {
4965                    return Err(format!(
4966                        "enterValue: `{other}` is not a verb that enters a value"
4967                    ))
4968                }
4969            };
4970            let selector = args.remove(0).to_display_string();
4971            let value = args.remove(0).to_display_string();
4972            let takes = crate::semantics::dom::answers_by_itself(verb, &selector, &value);
4973            crate::semantics::dom::enter_value(verb, &selector, &value);
4974            Ok(RuntimeValue::Bool(takes))
4975        }
4976        // An entry calls back into the program, which only the engine running it can do
4977        // (`Vm::dispatch_entry`); a table of pure builtins has no program to call.
4978        BuiltinId::DomDispatchEntry => Err(
4979            "dispatchEntry: the engine running the page takes the entry; it has no pure form"
4980                .to_string(),
4981        ),
4982        BuiltinId::DomSetInterval => {
4983            // The interval is the HOST's to fire, as a browser's timer is: recorded here with its
4984            // period, fired by whoever drives the page when its virtual clock moves
4985            // (`page_host`'s `Advance time by …`). A tier that fires nothing leaves it recorded
4986            // and unread.
4987            let ms = match args.remove(0) {
4988                RuntimeValue::Int(n) => n,
4989                other => {
4990                    return Err(format!(
4991                        "setInterval takes a period in milliseconds, got {}",
4992                        other.type_name()
4993                    ))
4994                }
4995            };
4996            let handler = args.remove(0);
4997            crate::semantics::drive::arm_interval(ms, handler);
4998            Ok(RuntimeValue::Nothing)
4999        }
5000        BuiltinId::DomScrollGap => {
5001            // A tier with no viewport has nothing below the fold: `0` says "already at the
5002            // bottom", which is the only honest answer where there is no scrolling at all.
5003            let _el = args.remove(0);
5004            Ok(RuntimeValue::Int(0))
5005        }
5006        BuiltinId::DomOnWindowEvent => {
5007            // ★ ON THE IN-PROCESS TIERS THERE IS NO WINDOW, so the handler is registered against
5008            // the page node — which is exactly where `Raise "offline".` delivers. A browser
5009            // registers the same handler on `window`, where the event really happens.
5010            let event = args.remove(0).to_display_string();
5011            let handler = args.remove(0);
5012            crate::semantics::dom::add_event_listener(
5013                crate::semantics::dom::body(),
5014                &event,
5015                handler,
5016            );
5017            Ok(RuntimeValue::Nothing)
5018        }
5019        BuiltinId::DomGetAttribute => {
5020            let el = dom_handle(args.remove(0), "getAttribute")?;
5021            let name = args.remove(0).to_display_string();
5022            // An element with no such attribute reads as EMPTY, never a trap: `Add class` asks
5023            // every element for its class list, and most elements start without one.
5024            let v = crate::semantics::dom::attribute(el, &name).unwrap_or_default();
5025            Ok(RuntimeValue::Text(Rc::new(v)))
5026        }
5027        BuiltinId::DomGoBack => {
5028            // `history.back()`: the location steps back, and the `popstate` that raises is the
5029            // host's to deliver to every route handler once this turn is done
5030            // (`semantics::dom::take_popped`), as a browser raises it.
5031            let _ = crate::semantics::dom::go_back();
5032            Ok(RuntimeValue::Nothing)
5033        }
5034        BuiltinId::DomReload => {
5035            // `location.reload()` is a request: the host loads the page again once the running
5036            // turn is done (`semantics::dom::take_reload_request`), as a browser does.
5037            crate::semantics::dom::request_reload();
5038            Ok(RuntimeValue::Nothing)
5039        }
5040        BuiltinId::NoteTurn => {
5041            let action = args.remove(0).to_display_string();
5042            let instance = args.remove(0).to_display_string();
5043            let changes = journal_changes(&args.remove(0))?;
5044            let failure = args.remove(0).to_display_string();
5045            crate::semantics::world::journal_push(crate::semantics::world::JournalEntry {
5046                instance,
5047                action,
5048                changes,
5049                failed: (!failure.is_empty()).then_some(failure),
5050            });
5051            Ok(RuntimeValue::Nothing)
5052        }
5053        BuiltinId::DomSetTitle => {
5054            let t = args.remove(0).to_display_string();
5055            crate::semantics::dom::set_title(&t);
5056            Ok(RuntimeValue::Nothing)
5057        }
5058        BuiltinId::DomSetHeadHtml => {
5059            let t = args.remove(0).to_display_string();
5060            crate::semantics::dom::set_head_html(&t);
5061            Ok(RuntimeValue::Nothing)
5062        }
5063        BuiltinId::DomNavigate => {
5064            let path = args.remove(0).to_display_string();
5065            crate::semantics::dom::navigate(&path);
5066            Ok(RuntimeValue::Nothing)
5067        }
5068        BuiltinId::DomReplaceRoute => {
5069            let path = args.remove(0).to_display_string();
5070            crate::semantics::dom::replace_route(&path);
5071            Ok(RuntimeValue::Nothing)
5072        }
5073        BuiltinId::DomOnRoute => {
5074            let handler = args.remove(0); // the LOGOS closure
5075            crate::semantics::dom::on_route(handler);
5076            Ok(RuntimeValue::Nothing)
5077        }
5078        BuiltinId::ReadBytes => {
5079            let path = args.remove(0).to_display_string();
5080            match std::fs::read(&path) {
5081                Ok(bytes) => Ok(bytes_to_seq(&bytes)),
5082                Err(e) => Err(logicaffeine_data::failure::cannot_read_bytes(&path, e)),
5083            }
5084        }
5085        // ★ THE SAME READ, ANSWERED INSTEAD OF THROWN. One `match` arm apart from `FileRead`,
5086        // which has always been total — the asymmetry is the whole bug: a program serving files
5087        // had a recoverable reader for TEXT and an aborting one for BYTES, so `static.lg` probed
5088        // with the first before calling the second and carried a race between them.
5089        BuiltinId::ReadReals => {
5090            let path = args.remove(0).to_display_string();
5091            let reals = logicaffeine_system::file::read_reals(path)?;
5092            Ok(RuntimeValue::List(Rc::new(RefCell::new(ListRepr::Floats(reals)))))
5093        }
5094        BuiltinId::TryReadBytes => {
5095            let path = args.remove(0).to_display_string();
5096            Ok(match logicaffeine_system::file::read_bytes(path) {
5097                Ok(bytes) => result_ok(bytes_to_seq(&bytes)),
5098                Err(e) => result_err(e),
5099            })
5100        }
5101        BuiltinId::FileRead => {
5102            let path = match args.remove(0) {
5103                RuntimeValue::Text(t) => t.to_string(),
5104                other => return Err(format!("read needs a Text path, got {}", other.type_name())),
5105            };
5106            Ok(match logicaffeine_system::file::read(path) {
5107                Ok(content) => result_ok(RuntimeValue::Text(Rc::new(content))),
5108                Err(e) => result_err(e),
5109            })
5110        }
5111        BuiltinId::FileWrite => {
5112            let content = match args.remove(1) {
5113                RuntimeValue::Text(t) => t.to_string(),
5114                other => {
5115                    return Err(format!(
5116                        "write needs Text content, got {}",
5117                        other.type_name()
5118                    ))
5119                }
5120            };
5121            let path = match args.remove(0) {
5122                RuntimeValue::Text(t) => t.to_string(),
5123                other => {
5124                    return Err(format!(
5125                        "write needs a Text path, got {}",
5126                        other.type_name()
5127                    ))
5128                }
5129            };
5130            Ok(match logicaffeine_system::file::write(path, content) {
5131                Ok(()) => result_ok(RuntimeValue::Nothing),
5132                Err(e) => result_err(e),
5133            })
5134        }
5135        // `Stmt::ReadFrom`'s VM compiler arm — the SAME sandboxed VFS the tree-walker's
5136        // `ReadFrom` reads through (`ui_bridge::run_treewalker`'s `Interpreter::with_vfs`), so a
5137        // program that never mounted a real filesystem sees the identical "Not found" on both
5138        // tiers. `MemVfs` has no await point, so its future is complete on its first poll — taken
5139        // with `now_or_never`, never a nested executor (the VM's own runner is already one).
5140        BuiltinId::VfsReadFile => {
5141            use logicaffeine_system::fs::Vfs as _;
5142            let path = args.remove(0).to_display_string();
5143            sandboxed(logicaffeine_system::fs::MemVfs::new().read_to_string(&path))?
5144                .map(|content| RuntimeValue::Text(Rc::new(content)))
5145                .map_err(|e| vfs_read_failure(&e))
5146        }
5147        // `Stmt::WriteFile`'s VM compiler arm — the same VFS, so a file written on the VM is what
5148        // either tier reads back. Content and path are DISPLAYED, as the tree-walker's arm
5149        // displays them: a number writes as its text.
5150        BuiltinId::VfsWriteFile => {
5151            use logicaffeine_system::fs::Vfs as _;
5152            let path = args.remove(1).to_display_string();
5153            let content = args.remove(0).to_display_string();
5154            sandboxed(logicaffeine_system::fs::MemVfs::new().write(&path, content.as_bytes()))?
5155                .map(|()| RuntimeValue::Nothing)
5156                .map_err(|e| vfs_write_failure(&e))
5157        }
5158        // `Stmt::Mount`'s VM compiler arm — the journal's text, or empty Text when the file is
5159        // not there yet, exactly as the tree-walker's `Mount` arm binds it.
5160        BuiltinId::VfsMount => {
5161            use logicaffeine_system::fs::Vfs as _;
5162            let path = args.remove(0).to_display_string();
5163            let content = sandboxed(logicaffeine_system::fs::MemVfs::new().read_to_string(&path))?
5164                .unwrap_or_default();
5165            Ok(RuntimeValue::Text(Rc::new(content)))
5166        }
5167        BuiltinId::RandomInt => {
5168            let hi = match args.remove(1) {
5169                RuntimeValue::Int(n) => n,
5170                other => {
5171                    return Err(format!(
5172                        "randomInt needs Int bounds, got {}",
5173                        other.type_name()
5174                    ))
5175                }
5176            };
5177            let lo = match args.remove(0) {
5178                RuntimeValue::Int(n) => n,
5179                other => {
5180                    return Err(format!(
5181                        "randomInt needs Int bounds, got {}",
5182                        other.type_name()
5183                    ))
5184                }
5185            };
5186            random_int(lo, hi).map(RuntimeValue::Int)
5187        }
5188        BuiltinId::RandomFloat => Ok(RuntimeValue::Float(
5189            logicaffeine_system::random::randomFloat(),
5190        )),
5191        BuiltinId::EnvGet => {
5192            let key = match args.remove(0) {
5193                RuntimeValue::Text(t) => t.to_string(),
5194                other => return Err(format!("get needs a Text name, got {}", other.type_name())),
5195            };
5196            Ok(match environment_variable(&key) {
5197                Some(v) => crate::interpreter::option_some(RuntimeValue::Text(Rc::new(v))),
5198                None => crate::interpreter::option_none(),
5199            })
5200        }
5201        BuiltinId::TimeNow => Ok(RuntimeValue::Int(logicaffeine_system::time::now() as i64)),
5202        BuiltinId::EnvHas | BuiltinId::EnvValue => {
5203            let key = match args.remove(0) {
5204                RuntimeValue::Text(t) => t.to_string(),
5205                other => return Err(format!("get needs a Text name, got {}", other.type_name())),
5206            };
5207            let value = environment_variable(&key);
5208            Ok(if id == BuiltinId::EnvHas {
5209                RuntimeValue::Bool(value.is_some())
5210            } else {
5211                RuntimeValue::Text(Rc::new(value.unwrap_or_default()))
5212            })
5213        }
5214        // The reactive-signal dialect is retired: `builtin_from_name` maps no source spelling to
5215        // any of these fifteen ids any more, so no program written today can reach this arm. The
5216        // variants themselves stay — deleting one would renumber every `BuiltinId` bincode encodes
5217        // after it (`builtin_wire_id_lock`, position-keyed) — kept wire-frozen, never a silent no-op.
5218        BuiltinId::SignalNew
5219        | BuiltinId::SignalSet
5220        | BuiltinId::SignalGetInt
5221        | BuiltinId::SignalGetText
5222        | BuiltinId::SignalBeginRender
5223        | BuiltinId::SignalNewText
5224        | BuiltinId::SignalSetText
5225        | BuiltinId::SignalEnterComponent
5226        | BuiltinId::SignalExitComponent
5227        | BuiltinId::SignalNewSeq
5228        | BuiltinId::SignalGetSeq
5229        | BuiltinId::SignalSetSeq
5230        | BuiltinId::SignalNewFloat
5231        | BuiltinId::SignalGetFloat
5232        | BuiltinId::SignalSetFloat => Err(
5233            "the reactive-signal dialect is retired; this builtin id is wire-frozen only"
5234                .to_string(),
5235        ),
5236    }
5237}
5238
5239/// Extract an Element/Event handle (an `Int`) from a DOM builtin argument.
5240fn dom_handle(v: RuntimeValue, what: &str) -> Result<i64, String> {
5241    match v {
5242        RuntimeValue::Int(h) => Ok(h),
5243        other => Err(format!(
5244            "{what} requires an Element handle, got {}",
5245            other.type_name()
5246        )),
5247    }
5248}
5249
5250#[cfg(test)]
5251#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/semantics/builtins/tests.rs"]
5252mod tests;
5253
5254/// What calling a builtin can do beyond computing its result — the fact the effect analysis
5255/// (`optimize::effects`) needs to reason about a call it cannot look inside.
5256#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5257pub enum BuiltinEffect {
5258    /// A total function of its arguments: it always returns, the same answer for the same input.
5259    Pure,
5260    /// Deterministic, but it can stop the program (bad input, a failed lookup, `Fail with`).
5261    Fallible,
5262    /// Its answer is not a function of its arguments (a random draw).
5263    Nondeterministic,
5264    /// It touches the world: files, the page, storage, the network, shared host state.
5265    Effectful,
5266}
5267
5268impl BuiltinId {
5269    /// This builtin's [`BuiltinEffect`]. Exhaustive with no wildcard: a new builtin does not compile
5270    /// until its effect is decided here. When in doubt a builtin is `Fallible` or `Effectful` — a
5271    /// builtin wrongly called `Pure` could be reordered or removed.
5272    pub fn effect(self) -> BuiltinEffect {
5273        use BuiltinId as B;
5274        match self {
5275            B::Length | B::Contains | B::Format | B::Abs | B::Sqrt | B::Min | B::Max | B::Complex
5276            | B::Conjugate | B::RealPart | B::ImagPart | B::UuidNil | B::UuidMax | B::UuidVersion
5277            | B::UuidDns | B::UuidUrl | B::UuidOid | B::UuidX500 | B::TextBytes | B::UuidBytes
5278            | B::FormatTimestamp | B::YearOf | B::MonthOf | B::DayOf | B::WeekdayOf | B::HourOf
5279            | B::MinuteOf | B::SecondOf | B::WeekOf | B::QuarterOf | B::DateOf | B::TimeOf
5280            | B::SecondsBetween | B::MonthsBetween | B::YearsBetween | B::AddSeconds | B::Copy
5281            | B::CountOnes | B::LeadingZeros | B::TrailingZeros | B::Word32 | B::Word64 | B::Rotl
5282            | B::Rotr | B::Wand | B::Wor | B::Wnot | B::Lanes4Word32Make | B::SeqOfLanes4W32
5283            | B::Sha1Rnds4 | B::Sha1Msg1 | B::Sha1Msg2 | B::Sha1Nexte | B::SeqOfLanes16W8
5284            | B::Splat16Word8 | B::Shuffle16 | B::ShrBytes16 | B::InterleaveLo16 | B::InterleaveHi16
5285            | B::ByteAdd16 | B::Maddubs16 | B::Packus16 | B::SeqOfLanes8 | B::Splat8Word32
5286            | B::IntOfWord32 | B::IntOfWord64 | B::Word64Shl | B::Word64Shr | B::Word64And
5287            | B::Word32Shr | B::Word16Make | B::IntOfWord16 | B::Word8Make | B::IntOfWord8 | B::NativeKernel | B::SeqOfLanes4 | B::Mul32x32To64
5288            | B::HsumLanes4 | B::Splat4Word64 | B::AndNot4 | B::SeqOfLanes16 | B::Splat16Word16
5289            | B::Mulhi16 | B::Montmul32 | B::NttBcastLo | B::NttBcastHi | B::NttBlend | B::MapOf
5290            | B::SetOf | B::Provisional | B::StateSize | B::ExactPi | B::ExactE | B::ExactOmega => {
5291                BuiltinEffect::Pure
5292            }
5293            B::Infinitesimal | B::OrderedInfinitesimal | B::StandardPart | B::IsInfinitesimal | B::IsLimited
5294            | B::InfinitelyClose | B::GeneratorOf | B::LimitOf | B::AtTheLimit | B::EveryNatural
5295            | B::TripCount | B::AffinePower | B::CycleAt | B::SearchCandidates | B::PolynomialFlow | B::HybridFlow
5296            | B::FirstExit
5297            | B::DefinedReal
5298            | B::ExactSqrt | B::ExactExp | B::ExactLn | B::ExactPower | B::ParseInt | B::ParseFloat | B::Chr | B::Floor | B::Ceil | B::Round | B::Pow
5299            | B::Decimal | B::Modular | B::Quantity | B::Money | B::ToCurrency | B::Convert
5300            | B::Uuid | B::TextFromBytes | B::WireBytes | B::CompressBytes | B::DecompressBytes
5301            | B::SealBytes | B::OpenBytes | B::FromWireBytes | B::SealFrame | B::OpenFrame
5302            | B::OpenBox | B::OpenValueBox | B::UuidFromBytes | B::ParseTimestamp | B::MakeDate | B::MakeMoment | B::LocalInstant
5303            | B::InZone | B::RunAccepted | B::Lanes4Of | B::Lanes16Word8Make | B::Lanes8Word32
5304            | B::Lanes4Word64 | B::Lanes16Word16 | B::RepeatSeq | B::ReedSolomonEncode
5305            | B::ReedSolomonRecover | B::FecProtect | B::FecRestore | B::Fail | B::FailReason
5306            | B::InspectUnhandledDynamic => BuiltinEffect::Fallible,
5307            B::RandomInt | B::RandomFloat | B::TimeNow | B::SealBox | B::SealValueBox => {
5308                BuiltinEffect::Nondeterministic
5309            }
5310            B::SetRate | B::SetRates | B::ReadWireProgram | B::WriteWireResidual | B::FileRead
5311            | B::FileWrite | B::EnvGet | B::EnvHas | B::EnvValue | B::VfsReadFile | B::VfsWriteFile | B::VfsMount | B::ReadBytes | B::TryReadBytes | B::ReadReals | B::StorageSet | B::StorageGet
5312            | B::StorageGetOr | B::StorageRemove | B::DomBody | B::DomCreateElement
5313            | B::DomCreateTextNode | B::DomSetText | B::DomSetHtml | B::DomClearChildren
5314            | B::DomOnMessage | B::DomMoveChildren | B::DomBeginPaint | B::DomSetAttribute
5315            | B::DomAppendChild | B::DomGetText | B::DomGetValue | B::DomSetValue
5316            | B::DomApplyPatches | B::DomApplyWords | B::DomWakeAfter | B::DomEnterValue | B::DomDispatchEntry | B::DomSetChecked | B::DomPreventDefault | B::DomSetStream
5317            | B::RtcPeerConnection | B::RtcDataChannel | B::RtcCreateOffer | B::RtcCreateAnswer
5318            | B::RtcSetLocal | B::RtcSetRemote | B::RtcAddIce | B::RtcSend | B::DomQuerySelector
5319            | B::DomAddEventListener | B::DomEventValue | B::DomEventKey | B::DomEventTarget
5320            | B::DomFetchText | B::DomResponseText
5321            | B::DomFetchSend | B::DomResponseStatus | B::DomResponseBody | B::DomResponseHeader
5322            | B::DomResponseError | B::DomFetchAbort | B::DomFetchSetTimeout | B::DomRoutePath
5323            | B::DomRouteQuery | B::DomNavigate | B::DomReplaceRoute | B::DomSetTitle | B::DomSetHeadHtml
5324            | B::DomClipboardWrite | B::DomDownloadFile | B::DomNotify | B::DomPublish
5325            | B::DomElementCommand | B::DomEventFileName | B::DomEventFileSize | B::DomEventFileType
5326            | B::DomEventFileBytes | B::DomListenFlags | B::DomAssignLocation | B::DomJournalDetail
5327            | B::DomSetInterval | B::DomScrollGap
5328            | B::DomOnWindowEvent | B::DomGetAttribute | B::DomGoBack | B::DomReload | B::DomOnRoute
5329            | B::NoteTurn
5330            // The reactive-signal dialect is retired (see `execute_builtin`); wire-frozen only.
5331            | B::SignalNew | B::SignalSet | B::SignalGetInt | B::SignalGetText | B::SignalBeginRender
5332            | B::SignalNewText | B::SignalSetText | B::SignalEnterComponent | B::SignalExitComponent
5333            | B::SignalNewSeq | B::SignalGetSeq | B::SignalSetSeq | B::SignalNewFloat
5334            | B::SignalGetFloat | B::SignalSetFloat => BuiltinEffect::Effectful,
5335        }
5336    }
5337}
5338
5339/// The text a broken contract reports: its `, otherwise` reason, which must be Text. Shared by the
5340/// tree-walker and the VM so both refuse a non-Text reason with the same words.
5341pub fn contract_reason_text(reason: RuntimeValue) -> Result<String, String> {
5342    match reason {
5343        RuntimeValue::Text(t) => Ok(t.to_string()),
5344        other => Err(format!(
5345            "The reason after `otherwise` must be Text, but it was {}.",
5346            other.type_name()
5347        )),
5348    }
5349}
5350
5351/// The loud message for a non-exhaustive `Inspect`: no `When` arm matched the scrutinee's ACTUAL
5352/// variant and there was no `Otherwise` — gauntlet finding G5. Shared by the tree-walker and the VM
5353/// so a mistyped arm (`When Err (message):` against a `JsonResult`, whose real variant is `JErr`)
5354/// fails with the identical words wherever it runs, naming the value it actually got rather than the
5355/// value-agnostic "the value" this message used to say before either tier could reach the runtime
5356/// value that trapped it (`current_site`/`Stmt::Site` already gives both tiers the sentence's own
5357/// location on top of this, through the ordinary runtime-failure path — this message is only the
5358/// "what", not the "where").
5359pub fn inspect_unhandled_message(type_name: &str, variant_name: &str) -> String {
5360    format!(
5361        "Inspect has no arm for `{variant_name}` (a `{type_name}`) and no Otherwise (matches must \
5362         be exhaustive) — add a `When {variant_name} (…):` arm, or an `Otherwise:` to cover it."
5363    )
5364}
5365
5366#[cfg(test)]
5367#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/semantics/builtins/builtin_effect_tests.rs"]
5368mod builtin_effect_tests;