Skip to main content

logicaffeine_compile/codegen/
expr.rs

1use std::collections::{HashMap, HashSet};
2
3use crate::analysis::registry::TypeRegistry;
4use crate::analysis::types::RustNames;
5use crate::ast::logic::{LogicExpr, NumberKind, Term};
6use crate::ast::stmt::{BinaryOpKind, Expr, Literal, Stmt};
7use crate::formatter::RustFormatter;
8use crate::intern::{Interner, Symbol};
9use crate::registry::SymbolRegistry;
10
11use super::context::RefinementContext;
12use super::detection::{collect_mutable_vars, expr_debug_prefix, parse_aos_tag};
13use super::i64_map::is_logos_map_type;
14use super::types::{codegen_type_expr, infer_logos_type, infer_numeric_type, rust_type_ident};
15use super::{
16    codegen_stmt, get_root_identifier, has_copy_element_type, has_copy_value_type, is_copy_type,
17};
18
19use std::sync::LazyLock;
20
21// Stable empty contexts so a sparsely-populated [`ExprCtx`] can borrow `'static`
22// placeholders instead of stack temporaries at every call site.
23static EMPTY_SYMS: LazyLock<HashSet<Symbol>> = LazyLock::new(HashSet::new);
24static EMPTY_TYPES: LazyLock<HashMap<Symbol, String>> = LazyLock::new(HashMap::new);
25static EMPTY_BOXED_FIELDS: LazyLock<HashSet<(String, String, String)>> =
26    LazyLock::new(HashSet::new);
27static EMPTY_REGISTRY: LazyLock<TypeRegistry> = LazyLock::new(TypeRegistry::new);
28
29/// All borrowed context an expression lowering threads through its recursion.
30///
31/// This bundles what were eight positional parameters passed by hand through
32/// every recursive `codegen_expr` call. It is `Copy` (every field is a shared
33/// reference), so recursion passes `ctx` unchanged and a sub-scope that needs to
34/// vary one field uses struct-update: `ExprCtx { boxed_bindings: &b, ..*ctx }`.
35/// New cross-cutting context becomes one field here instead of a parameter on
36/// hundreds of call sites.
37#[derive(Clone, Copy)]
38pub(crate) struct ExprCtx<'a> {
39    pub interner: &'a Interner,
40    pub synced_vars: &'a HashSet<Symbol>,
41    pub boxed_fields: &'a HashSet<(String, String, String)>,
42    pub registry: &'a TypeRegistry,
43    pub async_functions: &'a HashSet<Symbol>,
44    pub boxed_bindings: &'a HashSet<Symbol>,
45    pub string_vars: &'a HashSet<Symbol>,
46    pub variable_types: &'a HashMap<Symbol, String>,
47    /// Divisor symbol → precomputed `LogosDivU64` helper variable name, for the
48    /// loop-invariant libdivide rewrite of `% n` / `/ n` (empty when inactive).
49    pub fast_div: &'a HashMap<Symbol, String>,
50    /// Bounds-elision oracle: when present, an `item E of arr` read the oracle
51    /// proves in range lowers to `get_unchecked` (no bounds branch) instead of
52    /// checked indexing. `None` ⟹ every access keeps its check. Threaded only
53    /// from the statement arms that lower indexed reads (`Let`/`Set`/`If`/
54    /// `SetIndex` values), where the `RefinementContext`'s oracle is in hand.
55    pub oracle: Option<&'a crate::optimize::OracleFacts>,
56    /// Overflow ruling v2 (stage 2): when true, an unproven Int op may emit the
57    /// bare checked-exact helper (result `LogosInt` — the promoting boxed
58    /// path); when false the result NARROWS back to i64 with a loud canonical
59    /// error if it no longer fits (never a silent wrap). True under `Show` and
60    /// down the operand chains of exactable ops; false at i64 storage sinks.
61    pub int_exact_tolerant: bool,
62    /// True while codegen'ing an INDEX subexpression (`arr[<here>]`). Index
63    /// arithmetic is a `usize` computation the interpreter also requires to fit
64    /// i64 (a promoted BigInt can't index) — so it stays raw, never exact-wrapped.
65    pub int_index_context: bool,
66    /// True while codegen'ing the argument of a `wordN(...)` truncation. The
67    /// result keeps only the low N bits, so Int add/sub/mul lower to raw i64
68    /// `wrapping_*` (identical low bits to the checked-exact helper, matching the
69    /// crate's wrapping word semantics) instead of `logos_*_exact`. Propagates
70    /// through the additive chain but is RESET at a call boundary (a call's
71    /// argument is a full-width value, not truncated).
72    pub int_wrapping: bool,
73    /// True while codegen'ing a closure ARGUMENT to a scalar exact higher-order function
74    /// (`exact_hof_fns` — `apply(f, x)`). The closure's integer params are typed
75    /// `LogosInt` and registered as promoted (`__bigint`), so an overflowing body
76    /// (`(n) -> n * 2`) routes through the exact helper and yields a bignum == the VM,
77    /// rather than the raw `i64` that wraps/panics. Set ONLY on the closure arg's own
78    /// codegen and reset inside the body — see the `Expr::Closure` arm and the call-site
79    /// arg loop. `false` for every other closure (a `map`/`fold` closure stays `i64`).
80    pub exact_closure: bool,
81}
82
83impl<'a> ExprCtx<'a> {
84    /// The minimal context: just the interner and synced vars, every richer
85    /// field empty. Richer wrappers layer their fields on with struct-update.
86    pub(crate) fn bare(interner: &'a Interner, synced_vars: &'a HashSet<Symbol>) -> Self {
87        ExprCtx {
88            interner,
89            synced_vars,
90            boxed_fields: &EMPTY_BOXED_FIELDS,
91            registry: &EMPTY_REGISTRY,
92            async_functions: &EMPTY_SYMS,
93            boxed_bindings: &EMPTY_SYMS,
94            string_vars: &EMPTY_SYMS,
95            variable_types: &EMPTY_TYPES,
96            fast_div: &EMPTY_TYPES,
97            oracle: None,
98            int_exact_tolerant: false,
99            int_index_context: false,
100            int_wrapping: false,
101            exact_closure: false,
102        }
103    }
104}
105
106/// True when the bounds-elision oracle proves `index` in range for `collection`,
107/// so the access can lower to `get_unchecked`. The `LOGOS_ORACLE_UNCHECKED=0`
108/// kill switch forces the checked form (A/B against the `assert_unchecked` hint
109/// path). Soundness rests on the kernel-LIA-certified proof plus the caller's
110/// entry precondition guard; a `debug_assert!` (emitted by the statement-level
111/// hint pass) traps an unsound proof in debug builds.
112/// A compile-time Int op on two literals (overflow ruling v2, stage 2).
113thread_local! {
114    /// The whole-program set of `Int`-returning functions whose value can exceed i64, so their
115    /// return type is the promoting `LogosInt` (`bigint_promote::bigint_returning_fns`). Set once
116    /// per program at codegen entry by [`set_bigint_returning_fns`]; read by `mentions_bigint_var`
117    /// so an INLINE call to such a function (e.g. `mlkemBit(a) + mlkemBit(b)`) is recognised as a
118    /// promoted operand and routes through the exact helper. A bare `LogosInt + LogosInt` has no
119    /// operator impl and would not compile — this closes the call-operand hole the variable-only
120    /// detector left open. Codegen is single-threaded per program (nextest gives each test its own
121    /// thread), and each program overwrites the set, so no state leaks across programs or tests.
122    static BIGINT_RETURNING_FNS: std::cell::RefCell<HashSet<Symbol>> =
123        std::cell::RefCell::new(HashSet::new());
124}
125
126thread_local! {
127    /// Opt::StrengthReducePow2 — the current function body's variables proven ALWAYS `>= 0` (their
128    /// init and every assignment preserve non-negativity, e.g. a `0`-start `+1` loop counter). Set
129    /// once per function body by [`set_nonneg_vars`]; read by [`is_nonneg_expr`] at a `% 2^k`/`/ 2^k`
130    /// site so the mask/shift reduction fires only where signed and masked/shifted agree. Codegen is
131    /// single-threaded per program and each body overwrites the set, so nothing leaks across bodies.
132    static NONNEG_VARS: std::cell::RefCell<HashSet<Symbol>> = std::cell::RefCell::new(HashSet::new());
133}
134
135/// Record the current function body's always-non-negative variables (see [`NONNEG_VARS`]).
136pub(crate) fn set_nonneg_vars(vars: HashSet<Symbol>) {
137    NONNEG_VARS.with(|v| *v.borrow_mut() = vars);
138}
139
140thread_local! {
141    /// Opt::WideAccumulator — the current body's variables widened to `i128` (a bounded counting
142    /// accumulator). Set once per body; read at the `Let`/`Set`/branchless-increment/`Show` sites so
143    /// the accumulator is declared `i128`, added plainly (no checked-add branch), and narrowed `as i64`
144    /// at the `Show`. Per-body (symbols are name-keyed), single-threaded per program.
145    static WIDE_ACC: std::cell::RefCell<HashSet<Symbol>> = std::cell::RefCell::new(HashSet::new());
146}
147
148/// Record the current function body's i128-widened accumulators (see [`WIDE_ACC`]).
149pub(crate) fn set_wide_acc(vars: HashSet<Symbol>) {
150    WIDE_ACC.with(|v| *v.borrow_mut() = vars);
151}
152
153/// Is `x` an i128-widened counting accumulator in the current body?
154pub(crate) fn is_wide_acc(x: Symbol) -> bool {
155    WIDE_ACC.with(|v| v.borrow().contains(&x))
156}
157
158/// Is `e` provably `>= 0`? Syntactic over the non-negative-closed operations: non-negative literals,
159/// `length of …`, `nonneg % positive`, `nonneg + nonneg`, `nonneg * nonneg`, `nonneg / positive`, and
160/// variables the body-level analysis proved always non-negative ([`NONNEG_VARS`]).
161fn is_nonneg_expr(e: &Expr) -> bool {
162    NONNEG_VARS.with(|vars| expr_is_nonnegative(e, &vars.borrow()))
163}
164
165/// Backend-independent spelling of the non-negativity query. Rust keeps its
166/// current-body set thread-local; direct C carries the same set in `CContext`.
167pub(crate) fn expr_is_nonnegative(e: &Expr, vars: &HashSet<Symbol>) -> bool {
168    match e {
169        Expr::Literal(Literal::Number(n)) => *n >= 0,
170        Expr::Identifier(s) => vars.contains(s),
171        Expr::Length { .. } => true,
172        Expr::BinaryOp { op, left, right } => match op {
173            // A remainder keeps its dividend's sign (`-7 % 8` is `-7`), as a quotient does.
174            BinaryOpKind::Modulo | BinaryOpKind::Divide => {
175                matches!(right, Expr::Literal(Literal::Number(d)) if *d > 0)
176                    && expr_is_nonnegative(left, vars)
177            }
178            BinaryOpKind::Add | BinaryOpKind::Multiply => {
179                expr_is_nonnegative(left, vars) && expr_is_nonnegative(right, vars)
180            }
181            _ => false,
182        },
183        _ => false,
184    }
185}
186
187/// The variables provably `>= 0` throughout `stmts`: every `Let`/`Set` to the variable assigns a
188/// non-negativity-preserving expression (a fixpoint, since one such var may reference another). A
189/// `0`-start `+1` loop counter qualifies; a var ever assigned a possibly-negative value does not.
190/// Sound because it collects EVERY assignment across nested blocks before deciding.
191pub(crate) fn collect_always_nonneg(stmts: &[Stmt]) -> HashSet<Symbol> {
192    fn walk<'a>(stmts: &'a [Stmt<'a>], out: &mut Vec<(Symbol, &'a Expr<'a>)>) {
193        for s in stmts {
194            match s {
195                Stmt::Let { var, value, .. } => out.push((*var, value)),
196                Stmt::Set { target, value } => out.push((*target, value)),
197                Stmt::If {
198                    then_block,
199                    else_block,
200                    ..
201                } => {
202                    walk(then_block, out);
203                    if let Some(eb) = else_block {
204                        walk(eb, out);
205                    }
206                }
207                Stmt::While { body, .. } | Stmt::Repeat { body, .. } | Stmt::Zone { body, .. } => {
208                    walk(body, out)
209                }
210                Stmt::Inspect { arms, .. } => {
211                    for arm in arms.iter() {
212                        walk(arm.body, out);
213                    }
214                }
215                _ => {}
216            }
217        }
218    }
219    let mut assigns: Vec<(Symbol, &Expr)> = Vec::new();
220    walk(stmts, &mut assigns);
221    let mut cand: HashSet<Symbol> = assigns.iter().map(|(v, _)| *v).collect();
222    loop {
223        let remove: Vec<Symbol> = cand
224            .iter()
225            .filter(|v| {
226                assigns
227                    .iter()
228                    .any(|(t, rhs)| *t == **v && !expr_is_nonnegative(rhs, &cand))
229            })
230            .copied()
231            .collect();
232        if remove.is_empty() {
233            break;
234        }
235        for v in remove {
236            cand.remove(&v);
237        }
238    }
239    cand
240}
241
242/// Record the program's bignum-returning function set for the current codegen (see
243/// [`BIGINT_RETURNING_FNS`]). Called once at the top of `generate_rust_code`.
244/// Start a fresh program's emission: zero the bignum-temp counter.
245///
246/// ★ CODEGEN MUST NOT DEPEND ON WHAT WAS COMPILED BEFORE IT. `BIGNUM_TMP` is monotonic across a
247/// program, which is all uniqueness needs — but it was never reset, so compiling the same source
248/// TWICE IN ONE PROCESS named its temps `__lbop0` the first time and `__lbop27` the second.
249/// `phase_codegen_determinism` and `phase_opt_trace` both compile twice and compare, and both
250/// caught it the moment a program started using the bignum path at all: the output was a function
251/// of the compiler's history rather than of the source.
252pub(crate) fn begin_program_emission() {
253    BIGNUM_TMP.with(|c| c.set(0));
254    // SIMD_REDUCE_ID (codegen::simd_reduce) names emitted `__logos_simd_chunks_N` kernels, so it
255    // must reset per program for deterministic output — ResetAtEntry in the emitter-state catalogue.
256    crate::codegen::simd_reduce::reset_ids();
257    // PROBE_ID (codegen::probe) numbers the `__probeN` bindings a fused map test makes: ResetAtEntry, as above.
258    crate::codegen::probe::reset_names();
259}
260
261thread_local! {
262    /// Every `## Route` this program cannot lower, keyed by `(method, path)`, with the reason —
263    /// installed once at codegen entry, where the whole program is visible.
264    ///
265    /// A `-> View` route's lowerability depends on the COMPONENTS beside it, and the statement
266    /// emitter reaches a route with no program in hand. Asking there with an empty component list
267    /// refused every route that placed a component — which is the shape every page is built out
268    /// of — so the answer is computed where it can be right and merely read here.
269    static ROUTE_REFUSALS: std::cell::RefCell<HashMap<(Symbol, Symbol), String>> =
270        std::cell::RefCell::new(HashMap::new());
271}
272
273pub(crate) fn set_route_refusals(rs: &[(Symbol, Symbol, String)]) {
274    ROUTE_REFUSALS.with(|c| {
275        *c.borrow_mut() = rs.iter().map(|(m, p, w)| ((*m, *p), w.clone())).collect();
276    });
277}
278
279/// Why this route cannot lower, if it cannot.
280pub(crate) fn route_refusal(method: Symbol, path: Symbol) -> Option<String> {
281    ROUTE_REFUSALS.with(|c| c.borrow().get(&(method, path)).cloned())
282}
283
284pub(crate) fn set_bigint_returning_fns(fns: &HashSet<Symbol>) {
285    BIGINT_RETURNING_FNS.with(|c| *c.borrow_mut() = fns.clone());
286}
287
288fn is_bigint_returning_call(function: Symbol) -> bool {
289    BIGINT_RETURNING_FNS.with(|c| c.borrow().contains(&function))
290}
291
292/// The program's bignum fields, keyed `(struct_type or variant, field)`.
293#[derive(Default)]
294struct BignumFields {
295    /// Every field some construction feeds a bignum-promoted value
296    /// (`bigint_promote::bigint_struct_fields`) — what a read of the field is taken to hold.
297    tracked: HashSet<(Symbol, Symbol)>,
298    /// The tracked fields the emitter writes down as `LogosInt`: every one except a variant field of a
299    /// GENERIC enum. `Result<T, E>`'s `Ok { value: T }` carries whatever the call site put there — a
300    /// record, a list, an Int — so rewriting it to `LogosInt` would erase the parameter and break every
301    /// other use of the enum; the analysis may track such a payload, the emitter does not store it so.
302    stored: HashSet<(Symbol, Symbol)>,
303}
304
305thread_local! {
306    /// The program's [`BignumFields`], matching the interpreter's arbitrary-precision `Int`. Set once
307    /// per program at codegen entry by [`set_bigint_struct_fields`]; read at struct-def emission,
308    /// construction, and field access so the field's Rust type, its stored value, and every read agree.
309    static BIGINT_STRUCT_FIELDS: std::cell::RefCell<BignumFields> =
310        std::cell::RefCell::new(BignumFields::default());
311}
312
313/// Record the program's bignum fields for the current codegen (see [`BIGINT_STRUCT_FIELDS`]): all of
314/// `fields` tracked, and stored as `LogosInt` unless the key is a variant of one of `registry`'s generic
315/// enums.
316pub(crate) fn set_bigint_struct_fields(
317    fields: &HashSet<(Symbol, Symbol)>,
318    registry: &TypeRegistry,
319) {
320    let generic_variants: HashSet<Symbol> = registry
321        .iter_types()
322        .filter_map(|(_, def)| match def {
323            crate::analysis::registry::TypeDef::Enum {
324                variants, generics, ..
325            } if !generics.is_empty() => Some(variants.iter().map(|v| v.name)),
326            _ => None,
327        })
328        .flatten()
329        .collect();
330    let stored = fields
331        .iter()
332        .copied()
333        .filter(|(ty, _)| !generic_variants.contains(ty))
334        .collect();
335    BIGINT_STRUCT_FIELDS.with(|c| {
336        *c.borrow_mut() = BignumFields {
337            tracked: fields.clone(),
338            stored,
339        }
340    });
341}
342
343/// True when `(struct_type or variant, field)` is written down as `LogosInt` — the field's Rust type
344/// and every construction of it ask here.
345pub(crate) fn stores_logos_int(struct_type: Symbol, field: Symbol) -> bool {
346    BIGINT_STRUCT_FIELDS.with(|c| c.borrow().stored.contains(&(struct_type, field)))
347}
348
349/// The value a field stored as `LogosInt` is built with: the TOLERANT (un-narrowed) form of `value`
350/// — the context a promoted `Let` binding uses — widened to a `LogosInt` (`From` is the identity on
351/// one already, and promotes a machine word). A narrowed form would trap on the way in a bignum the
352/// field exists to hold, and a bare machine word is not a `LogosInt` at all.
353fn exact_field_value(value: &Expr, ecx: &ExprCtx) -> String {
354    let tolerant = codegen_expr_ctx(
355        value,
356        &ExprCtx {
357            int_exact_tolerant: true,
358            ..*ecx
359        },
360    );
361    format!("logicaffeine_data::LogosInt::from({tolerant})")
362}
363
364/// The whole promoted-field set, for an analysis that needs to ask about many fields at once
365/// (`bigint_promote::promotable_int_vars`, deciding whether a local assigned from a field read
366/// must hold a `LogosInt`). It is installed ONCE per program at codegen entry, so reading it here
367/// is reading the same answer the struct definitions were emitted from — which is precisely what
368/// used to differ.
369pub(crate) fn bigint_struct_fields_snapshot() -> HashSet<(Symbol, Symbol)> {
370    BIGINT_STRUCT_FIELDS.with(|c| c.borrow().tracked.clone())
371}
372
373/// Is a field of this NAME stored as `LogosInt`? Asked at the EMIT, through the same rule the
374/// analysis used — see `bigint_promote::field_name_is_exact`.
375pub(crate) fn is_exact_field_name(field: Symbol) -> bool {
376    BIGINT_STRUCT_FIELDS
377        .with(|c| super::bigint_promote::field_name_is_exact(&c.borrow().tracked, field))
378}
379
380/// True when `value` is an identifier of a non-Copy VALUE type — a user struct/enum or a `String` —
381/// where storing it (into a struct field, an enum variant field, or a collection slot) COPIES it under
382/// LOGOS value semantics, so the source stays usable. The default emit MOVES such an identifier (the
383/// Identifier arm bare-moves a non-bignum non-Copy value), which fails E0382 when the source is used
384/// again (json's `en`, built once and both stored and pushed). Cloning at the store is output-preserving
385/// — a currently-working move was a last-use, and clone-then-drop is equivalent. EXCLUDED: Copy
386/// primitives (a clone is pointless), references, `__bigint` (the Identifier arm already clones it), and
387/// COLLECTIONS (`LogosSeq`/`LogosMap`/`Vec`/`HashMap`) — those could be large, and an O(n) clone per
388/// store risks turning an O(n) loop into O(n²); their reuse is a separate, rarer concern.
389/// The DECLARED type of `obj's field` when the object is a variable of a known record type, OR
390/// itself another field read (`o's inner's value` — the object of the OUTER access is the INNER
391/// `FieldAccess`, resolved by the same rule one level down).
392///
393/// `infer_logos_type` cannot answer this: it builds its environment from the Rust-type strings of
394/// variables and has no type REGISTRY, so a field read comes back `Unknown`. Two AOT-Rust bugs
395/// both reduced to that one blind spot — a `Text` field moved out of a row it was only read from,
396/// and `p's left + p's right` emitted as `String + String`, which does not compile. Both need the
397/// same fact: what is this field?
398pub(crate) fn record_field_rust_type(
399    expr: &Expr,
400    interner: &Interner,
401    variable_types: &HashMap<Symbol, String>,
402    registry: &TypeRegistry,
403) -> Option<String> {
404    let Expr::FieldAccess { object, field } = expr else {
405        return None;
406    };
407    let object = match object {
408        Expr::Copy { expr } => *expr,
409        other => other,
410    };
411    let rust_ty = match object {
412        Expr::Identifier(var) => variable_types.get(var)?.clone(),
413        Expr::FieldAccess { .. } => {
414            record_field_rust_type(object, interner, variable_types, registry)?
415        }
416        _ => return None,
417    };
418    let base = rust_ty
419        .split("|__hl:")
420        .next()
421        .unwrap_or(&rust_ty)
422        .trim_start_matches('&');
423    let declared = registry.iter_types().find_map(|(sym, def)| match def {
424        crate::analysis::registry::TypeDef::Struct { fields, .. }
425            if rust_type_ident(interner.resolve(*sym)) == base =>
426        {
427            Some(fields.iter().find(|f| f.name == *field).map(|fd| {
428                super::absent::field(*sym, fd.name, super::types::codegen_field_type(&fd.ty, interner))
429            }))
430        }
431        _ => None,
432    });
433    match declared {
434        Some(found) => found,
435        None => super::types::program_record_field_type(base, *field),
436    }
437}
438
439/// The Rust type of the list a slice reads, as it is read: a binding's or a field's, and the list a value-or-nothing
440/// holds when an enclosing operation has read it in place.
441fn sliced_type(collection: &Expr, ecx: &ExprCtx) -> Option<String> {
442    let ty = match collection {
443        Expr::Identifier(sym) => ecx.variable_types.get(sym).cloned(),
444        Expr::FieldAccess { .. } => record_field_rust_type(collection, ecx.interner, ecx.variable_types, ecx.registry),
445        _ => None,
446    }?;
447    let ty = ty.split("|__hl:").next().unwrap_or(&ty).to_string();
448    match super::absent::read(collection).and(super::absent::payload(&ty)) {
449        Some(held) => Some(held.to_string()),
450        None => Some(ty),
451    }
452}
453
454/// Whether `expr` reads a counter CRDT — a `Tally` or `ConvergentCount` field or binding, held as a
455/// `PNCounter`/`GCounter`. Comparison and equality see a counter as its Int total, as the
456/// interpreter projects it (`semantics::compare::counter_as_int`), so such an operand reads
457/// `.value()`. Everywhere else — an argument, a field initializer, a `Set`, a `Merge` — the counter
458/// stays a counter.
459fn is_counter_read(expr: &Expr, ecx: &ExprCtx) -> bool {
460    let rust_ty = match expr {
461        Expr::FieldAccess { .. } => {
462            record_field_rust_type(expr, ecx.interner, ecx.variable_types, ecx.registry)
463        }
464        Expr::Identifier(sym) => ecx.variable_types.get(sym).cloned(),
465        _ => None,
466    };
467    rust_ty.is_some_and(|t| {
468        let t = t.trim_start_matches('&');
469        let name = t.rsplit("::").next().unwrap_or(t);
470        matches!(name, "PNCounter" | "GCounter")
471    })
472}
473
474/// Argument `i` of a call to `function`, lowered for the callee's parameter: a read-only borrow,
475/// an element `&mut` borrow, a value-semantics `mutable` collection, an exactified `LogosInt`, or an
476/// owned value (a copy of anything a move would consume; a Real parameter's integer converted). The
477/// one rule every call lowers its arguments with; [`call_arguments`] applies it to a whole call.
478pub(super) fn call_argument(function: Symbol, i: usize, a: &Expr, ecx: &ExprCtx) -> String {
479    call_argument_read(function, i, a, ecx, false)
480}
481
482/// Every argument of a call to `function`, lowered for the callee's parameters (see
483/// [`call_argument`]). Arguments are values taken left to right, so an argument that borrows a
484/// list an argument to its RIGHT lends to a `mutable` parameter reads a copy of its own: the lend
485/// writes the list before the callee reads the borrow. Using a list again in the very call that
486/// lends it never reaches here — the law of exclusivity refuses it.
487pub(super) fn call_arguments(function: Symbol, args: &[&Expr], ecx: &ExprCtx) -> Vec<String> {
488    let lent_later = lent_by_later_arguments(args, ecx.variable_types);
489    args.iter()
490        .enumerate()
491        .map(|(i, a)| {
492            if super::tower::param_at(function, i) {
493                return super::tower::value(a, ecx);
494            }
495            if let Some(code) = super::absent::argument(function, i, a, ecx) {
496                return code;
497            }
498            let lent_after = matches!(a, Expr::Identifier(s) if lent_later[i].contains(s));
499            call_argument_read(function, i, a, ecx, lent_after)
500        })
501        .collect()
502}
503
504/// `function(args)` as written with `rendered` arguments, sequenced so Rust can borrow-check it.
505///
506/// ★ A LEND IS A `&mut` FOR THE WHOLE CALL. When one argument lends a binding `&mut` — the program
507/// record a lifted function takes, a record lent to a `mutable` parameter — and another argument
508/// reads that binding (a field of the record, a nested call lending it too), Rust sees a shared
509/// borrow while the exclusive one is live. The author's own overlapping lends are refused before
510/// this (the law of exclusivity); these are the compiler's, made by the program-bindings lift, and
511/// are sequenced instead: every argument that is not a lend is evaluated first, left to right, into
512/// a temporary, and the call then lends. LOGOS evaluates a call's arguments before it runs the
513/// callee, so evaluating them before the lend changes nothing a program can observe.
514pub(super) fn sequenced_call(
515    path: &str,
516    function: Symbol,
517    args: &[&Expr],
518    mut rendered: Vec<String>,
519    suffix: &str,
520    variable_types: &HashMap<Symbol, String>,
521) -> String {
522    let lent = super::fn_role_indices(variable_types.get(&function), super::FnRole::ValueMutable);
523    let lends: Vec<(usize, Symbol)> = lent
524        .iter()
525        .filter(|i| rendered.get(**i).is_some_and(|r| r.starts_with("&mut ")))
526        .filter_map(|i| {
527            args.get(*i)
528                .and_then(|a| lent_place_root(a))
529                .map(|root| (*i, root))
530        })
531        .collect();
532    let overlaps = lends.iter().any(|(at, root)| {
533        args.iter()
534            .enumerate()
535            .any(|(j, a)| j != *at && mentions_binding(a, *root))
536    });
537    if !overlaps {
538        return format!("{path}({}){suffix}", rendered.join(", "));
539    }
540    let mut before = String::new();
541    for (j, arg) in rendered.iter_mut().enumerate() {
542        if lends.iter().any(|(at, _)| *at == j) {
543            continue;
544        }
545        before.push_str(&format!("let __arg{j} = {arg}; "));
546        *arg = format!("__arg{j}");
547    }
548    format!("{{ {before}{path}({}){suffix} }}", rendered.join(", "))
549}
550
551/// The binding a lent place is rooted at: the binding, or the record a field of it belongs to.
552fn lent_place_root(place: &Expr) -> Option<Symbol> {
553    match place {
554        Expr::Identifier(sym) => Some(*sym),
555        Expr::FieldAccess { object, .. } => lent_place_root(object),
556        _ => None,
557    }
558}
559
560/// Whether `expr` names `binding` anywhere — read, lent, or as the root of a place.
561fn mentions_binding(expr: &Expr, binding: Symbol) -> bool {
562    let mut ids = HashSet::new();
563    super::detection::collect_expr_identifiers(expr, &mut ids);
564    ids.contains(&binding)
565}
566
567/// Whether a call anywhere in `expr` lends `binding` to a `mutable` parameter. A statement that
568/// writes into `binding` evaluates such an expression before it touches its target — as every
569/// tier's statement order has it — rather than inside the write.
570pub(super) fn lends_binding(
571    expr: &Expr,
572    binding: Symbol,
573    variable_types: &HashMap<Symbol, String>,
574) -> bool {
575    let mut lends = false;
576    crate::analysis::callgraph::for_each_call_site_in_expr(expr, &mut |function, inner| {
577        for at in super::fn_role_indices(variable_types.get(&function), super::FnRole::ValueMutable)
578        {
579            if matches!(inner.get(at), Some(Expr::Identifier(s)) if *s == binding) {
580                lends = true;
581            }
582        }
583    });
584    lends
585}
586
587/// `format!("{fmt}", values…)` over `operands`, taken left to right. `format!` borrows every
588/// operand for the whole call, so when an operand's call lends a binding to a `mutable` parameter
589/// the text is built from values taken first, in order — a field or binding read copied out
590/// before the lend writes it, as every tier reads it.
591fn format_in_order(
592    fmt: &str,
593    operands: &[&Expr],
594    values: Vec<String>,
595    variable_types: &HashMap<Symbol, String>,
596) -> String {
597    let lends = operands.iter().any(|operand| {
598        let mut lends = false;
599        crate::analysis::callgraph::for_each_call_site_in_expr(operand, &mut |function, _| {
600            lends |=
601                !super::fn_role_indices(variable_types.get(&function), super::FnRole::ValueMutable)
602                    .is_empty();
603        });
604        lends
605    });
606    if !lends {
607        return format!("format!(\"{fmt}\", {})", values.join(", "));
608    }
609    let mut taken = String::from("{ ");
610    for (i, (operand, value)) in operands.iter().zip(&values).enumerate() {
611        let value = match operand {
612            Expr::Identifier(_) | Expr::FieldAccess { .. } => format!("({value}).clone()"),
613            _ => value.clone(),
614        };
615        taken.push_str(&format!("let __text_{i} = {value}; "));
616    }
617    let names: Vec<String> = (0..values.len()).map(|i| format!("__text_{i}")).collect();
618    taken.push_str(&format!("format!(\"{fmt}\", {}) }}", names.join(", ")));
619    taken
620}
621
622/// For each argument, the bindings that an argument to its right lends to a `mutable` parameter,
623/// in a call anywhere inside it.
624fn lent_by_later_arguments(
625    args: &[&Expr],
626    variable_types: &HashMap<Symbol, String>,
627) -> Vec<HashSet<Symbol>> {
628    let mut later = vec![HashSet::new(); args.len()];
629    let mut lent: HashSet<Symbol> = HashSet::new();
630    for (i, a) in args.iter().enumerate().rev() {
631        later[i] = lent.clone();
632        crate::analysis::callgraph::for_each_call_site_in_expr(a, &mut |function, inner| {
633            for at in
634                super::fn_role_indices(variable_types.get(&function), super::FnRole::ValueMutable)
635            {
636                if let Some(Expr::Identifier(s)) = inner.get(at) {
637                    lent.insert(*s);
638                }
639            }
640        });
641    }
642    later
643}
644
645fn call_argument_read(
646    function: Symbol,
647    i: usize,
648    a: &Expr,
649    ecx: &ExprCtx,
650    lent_after: bool,
651) -> String {
652    let variable_types = ecx.variable_types;
653    let names = RustNames::new(ecx.interner);
654    let raw_name = names.raw(function);
655    // Callee param-role indices (packed one slot per function): a readonly
656    // borrow (`&[T]`) and a value-semantics `mutable` collection param can
657    // BOTH be present, so read each role independently rather than assuming
658    // one clobbers the other.
659    let callee_slot = variable_types.get(&function);
660    let callee_borrow_indices: HashSet<usize> =
661        super::fn_role_indices(callee_slot, super::FnRole::Borrow);
662    // `mutable` collection params (value semantics): pass the caller's
663    // collection by shared reference (no clone) so the callee mutates it
664    // in place — the explicit propagation escape hatch.
665    let callee_value_mutable: HashSet<usize> =
666        super::fn_role_indices(callee_slot, super::FnRole::ValueMutable);
667    // Element `&mut` borrows: the callee writes a sequence's elements in place.
668    let callee_mut_borrow_indices: HashSet<usize> =
669        super::fn_role_indices(callee_slot, super::FnRole::MutBorrow);
670    // An integer handed to a parameter that holds rationals is the rational it equals, a list of them item by item.
671    if let Some(param) = fn_param_rust_type(function, i).filter(|t| t.contains(super::rational::RATIONAL)) {
672        if !callee_value_mutable.contains(&i) && !callee_mut_borrow_indices.contains(&i) {
673            if let Some(code) = super::rational::value_as(a, &super::rational::named(&param), ecx) {
674                return if callee_borrow_indices.contains(&i) {
675                    format!("&*({code}).borrow()")
676                } else {
677                    code
678                };
679            }
680        }
681    }
682    // Recursively codegen args with full context.
683    // Borrow params: pass &name (or pass through if already a slice).
684    // Non-borrow params: clone non-Copy identifiers to avoid move-after-use.
685    // A `wordN(...)` argument is codegen'd in `int_wrapping` mode (its Int arithmetic is mod 2^N);
686    // every OTHER call resets the flag — a callee's argument is a full-width value, not truncated,
687    // so `wordN(f(a * b))` must NOT wrap `a * b`.
688    let arg_wrapping = matches!(raw_name, "word8" | "word16" | "word32" | "word64");
689    if arg_wrapping {
690        let value = codegen_expr_ctx(
691            a,
692            &ExprCtx {
693                int_wrapping: true,
694                int_exact_tolerant: true,
695                ..*ecx
696            },
697        );
698        return format!("(logicaffeine_data::LogosInt::from({value}).wrapping_u64() as i64)");
699    }
700    // Selective higher-order-overflow analysis (call-site half): a scalar exact-HOF
701    // (`apply(f, x)`) exactifies its fn-param + int-params to `LogosInt`, and a `fn`-typed
702    // param CALLED inside a HOF body (`f(x)`) is `impl Fn(LogosInt) -> LogosInt`. So a closure
703    // argument renders exact, and an integer argument promotes to `LogosInt` — matching the VM,
704    // where an overflowing closure produces a bignum. Seq-HOFs are NOT in `EXACT_HOFS`, so
705    // `map`/`fold` closures stay `i64` (no regression).
706    let callee_is_exact_hof = is_exact_hof_call(function);
707    let callee_is_exact_fnptr = callee_slot.map_or(false, |t| t.contains(EXACT_FNPTR_MARKER));
708    let exact_closure_arg = callee_is_exact_hof
709        && fn_param_rust_type(function, i).map_or(false, |t| t.starts_with("impl Fn"));
710    let exact_int_parameter = callee_is_exact_fnptr
711        || (callee_is_exact_hof
712            && fn_param_rust_type(function, i).as_deref() == Some("logicaffeine_data::LogosInt"));
713    // A parameter declared as a machine word is a storage sink: the argument narrows into it, whatever exact chain
714    // the call sits in.
715    let word_parameter = fn_param_rust_type(function, i).as_deref() == Some("i64");
716    let s = codegen_expr_ctx(
717        a,
718        &ExprCtx {
719            int_wrapping: arg_wrapping,
720            exact_closure: exact_closure_arg,
721            int_exact_tolerant: exact_int_parameter || (ecx.int_exact_tolerant && !word_parameter),
722            ..*ecx
723        },
724    );
725    // Promote an integer argument to `LogosInt` when the callee's parameter is exactified
726    // (an exact-HOF's `LogosInt` param, or any arg of an exact `fn`-typed param). An
727    // already-promoted var passes by clone (never the `.expect_i64` narrow below); a raw
728    // `i64` value/literal wraps in `LogosInt::from` (identity for an existing `LogosInt`).
729    let promote_int = !matches!(a, Expr::Closure { .. })
730        && (callee_is_exact_fnptr
731            || (callee_is_exact_hof
732                && fn_param_rust_type(function, i).as_deref()
733                    == Some("logicaffeine_data::LogosInt")));
734    if promote_int {
735        if let Expr::Identifier(sym) = a {
736            if variable_types
737                .get(sym)
738                .map_or(false, |t| t.contains("__bigint"))
739            {
740                return format!("{}.clone()", names.ident(*sym));
741            }
742        }
743        return format!("logicaffeine_data::LogosInt::from({})", s);
744    }
745    if callee_value_mutable.contains(&i) {
746        // Pass the caller's collection by shared reference (no clone)
747        // so the callee mutates it in place. If the arg is already a
748        // reference (a `mutable` param threaded through a nested call),
749        // pass it as-is rather than re-referencing.
750        if let Expr::Identifier(sym) = a {
751            if variable_types.get(sym).is_some_and(|t| t.starts_with('&')) {
752                return s;
753            }
754            // A binding whose type this emission did not record is lent as the callee's parameter says
755            // it is: the parameter's type is the authority on what the call borrows.
756            let held = variable_types.get(sym).cloned().or_else(|| fn_param_rust_type(function, i));
757            // A record, a scalar, a `Set`: lent as `&mut` to the binding itself — or, passing on
758            // a parameter lent the same way, to the place behind it.
759            if !held.as_deref().is_some_and(lent_by_shared_reference) {
760                return format!("&mut {}", s);
761            }
762            if !variable_types.contains_key(sym) && crate::semantics::collections::value_semantics_enabled() {
763                return format!("{{ {s}.cow(); &{s} }}");
764            }
765        }
766        // The callee writes the binding's buffer in place, so it must be the binding's own: a
767        // value copied from it before the call keeps what it had.
768        if let Some(own) = cow_handle(a, variable_types, &names) {
769            return format!("{{ {own}.cow(); &{own} }}");
770        }
771        return format!("&{}", s);
772    }
773    if callee_mut_borrow_indices.contains(&i) {
774        // An element `&mut` borrow: the callee writes the caller's elements in place.
775        if let Expr::Identifier(sym) = a {
776            let held = variable_types
777                .get(sym)
778                .map(|t| t.split("|__hl:").next().unwrap_or(t).to_string());
779            return match held.as_deref() {
780                Some(t) if t.starts_with("&mut [") => s,
781                Some(t) if t.starts_with("Vec<") => format!("&mut {}", s),
782                _ => format!("&mut *{}.borrow_mut()", s),
783            };
784        }
785        return format!("&mut {}", s);
786    }
787    if callee_borrow_indices.contains(&i)
788        && fn_param_rust_type(function, i).is_some_and(|t| lent_record_type(&t))
789    {
790        // A lent enum value (`codegen::lent`): a borrow the caller already holds passes through, an owned value — a
791        // binding or a call's result — is lent for the call.
792        if let Expr::Identifier(sym) = a {
793            if variable_types.get(sym).is_some_and(|t| t.starts_with('&')) {
794                return s;
795            }
796        }
797        return format!("&({})", s);
798    }
799    if callee_borrow_indices.contains(&i) {
800        // Borrow param: pass &[T] reference instead of cloning
801        if let Expr::Identifier(sym) = a {
802            if let Some(ty) = variable_types.get(sym) {
803                let ty = ty.split("|__hl:").next().unwrap_or(ty.as_str());
804                if ty.starts_with("&[") || ty.starts_with("&mut [") {
805                    return s; // Already a slice — pass through
806                }
807                if ty.starts_with("&str") {
808                    return s; // Already a borrowed &str — pass through
809                }
810                if ty == "String" {
811                    return format!("&{}", s); // &String coerces to &str (Text borrow)
812                }
813                if ty.starts_with("Vec<") {
814                    return format!("&{}", s); // Vec<T> derefs to &[T]
815                }
816                if ty.starts_with('[') {
817                    return format!("&{}", s); // fixed array [T; N] coerces to &[T]
818                }
819                // A list a later argument lends is written before this callee reads it, so the
820                // borrow is of a copy taken now (see `call_arguments`).
821                if ty.starts_with("LogosSeq") && lent_after {
822                    return format!("&{}.to_vec()", s);
823                }
824                if ty.starts_with("LogosSeq") {
825                    return format!("&*{}.borrow()", s);
826                }
827            }
828            // Unknown type at borrow position — default to LogosSeq conversion.
829            // All LOGOS Seq variables are LogosSeq<T> unless materialized as Vec<T>
830            // (which is always tracked). Safe because borrow positions only accept Seq<T>.
831            return format!("&*{}.borrow()", s);
832        }
833        // Non-identifier at borrow position (e.g. list literal, function call).
834        // Most such expressions evaluate to LogosSeq<T> and borrow the temporary,
835        // but a Text literal is a `String` and a slice-return call is already a
836        // borrow — see `borrow_position_non_identifier`.
837        if let Some(marshalled) = borrow_position_non_identifier(a, &s) {
838            return marshalled;
839        }
840        format!("&*{}.borrow()", s)
841    } else {
842        // Regular param: clone non-Copy identifiers
843        if let Expr::Identifier(sym) = a {
844            // A `LogosInt` (promoted) var passed to a scalar `i64` param narrows to
845            // the param's declared width — a loud panic if it exceeds i64 (the
846            // i64-param contract). Functions do not yet take `LogosInt` params.
847            if variable_types
848                .get(sym)
849                .map_or(false, |t| t.contains("__bigint"))
850            {
851                return format!("{}.expect_i64(\"Int\")", names.ident(*sym));
852            }
853            if let Some(ty) = variable_types.get(sym) {
854                // A sequence this function holds BORROWED (`&[T]`, its own
855                // read-only parameter) handed to a parameter that OWNS its
856                // sequence: the callee gets the owned form it declares. A
857                // specialized clone of a recursive function borrows what the
858                // original, which it calls, owns.
859                let held = ty.split("|__hl:").next().unwrap_or(ty.as_str());
860                if held.starts_with("&[") || held.starts_with("&mut [") {
861                    return match fn_param_rust_type(function, i) {
862                        Some(p) if p.starts_with("Vec<") => format!("({}).to_vec()", s),
863                        _ => format!("LogosSeq::from_vec(({}).to_vec())", s),
864                    };
865                }
866                if !is_copy_type(ty) {
867                    return format!("{}.clone()", s);
868                }
869            } else {
870                // Unknown type (e.g. pattern-bound variable from Inspect):
871                // clone defensively to avoid move-after-use in loops
872                return format!("{}.clone()", s);
873            }
874        }
875        // ★ A FIELD READ IS A READ, NOT A HANDOVER. Only `Expr::Identifier` was
876        // considered here, so `shout(r's name)` MOVED the field and every later
877        // mention of `r` failed to build — on a program the tree-walker and the VM
878        // both run, so only a BUILD ever saw it.
879        if field_arg_needs_clone(a, fn_param_rust_type(function, i)) {
880            return format!("{}.clone()", s);
881        }
882        // An integer handed to a `Real` parameter is converted at the call, as the interpreter and
883        // the VM convert it at the call boundary (`sin(0)`, `cConj(3, 4)`).
884        if fn_param_rust_type(function, i).as_deref() == Some("f64")
885            && !produces_float(a, variable_types, ecx.interner)
886            && !mentions_bigint_var(a, variable_types)
887        {
888            return format!("(({}) as f64)", s);
889        }
890        s
891    }
892}
893
894/// Whether a parameter declared with Rust type `ty` is lent as `&ty` when it sits at a borrow position: a value of the
895/// program's own types. A sequence borrows as a slice and a text as `&str`, each with its own call-site conversion.
896pub(super) fn lent_record_type(ty: &str) -> bool {
897    let held = ty.split("|__hl:").next().unwrap_or(ty);
898    !(held.starts_with("Vec<")
899        || held.starts_with("LogosSeq<")
900        || held.starts_with('[')
901        || held.starts_with('&')
902        || held == "String")
903}
904
905/// Whether a call to `function` lends the value it is given at argument `index` — a borrowed enum parameter
906/// (`codegen::lent`), read from the function's call roles in `variable_types`.
907pub(super) fn lends_record_at(
908    function: Symbol,
909    index: usize,
910    variable_types: &HashMap<Symbol, String>,
911) -> bool {
912    super::fn_role_indices(variable_types.get(&function), super::FnRole::Borrow).contains(&index)
913        && fn_param_rust_type(function, index).is_some_and(|t| lent_record_type(&t))
914}
915
916/// Whether a binding of Rust type `ty` holds a lent record — `&T` for one of the program's own types.
917pub(super) fn is_lent_record(ty: &str) -> bool {
918    ty.strip_prefix('&')
919        .is_some_and(|t| !t.starts_with("mut ") && lent_record_type(t))
920}
921
922/// The Rust path a call to the program's function `function` names: its own name, or `crate::name`
923/// where a local value of that name is in scope. A value and a function may share a name and a call
924/// always means the function (the loader's hygiene rule), while a Rust local would shadow it. A
925/// function's calling roles live under its symbol as a `fn_roles|` slot, so any other type there is
926/// a local's.
927pub(super) fn called_function_path(
928    function: Symbol,
929    name: String,
930    variable_types: &HashMap<Symbol, String>,
931) -> String {
932    let shadowed = program_defines_function(function)
933        && variable_types
934            .get(&function)
935            .is_some_and(|t| !t.starts_with("fn_roles|"));
936    if shadowed {
937        format!("crate::{name}")
938    } else {
939        name
940    }
941}
942
943/// Whether the program declares a function named `function` itself — the one question a
944/// builtin's name-keyed emission asks before it claims a call (declarer wins).
945fn program_defines_function(function: Symbol) -> bool {
946    FN_RETURN_TYPES.with(|c| c.borrow().contains_key(&function))
947        || FN_PARAM_TYPES.with(|c| c.borrow().contains_key(&function))
948}
949
950/// True when that field's Rust type is one a MOVE would consume — a `String`, a collection, a
951/// nested record. The Copy scalars are safe to read as-is.
952fn field_read_moves(ty: &str) -> bool {
953    !matches!(
954        ty,
955        "i64"
956            | "i32"
957            | "i16"
958            | "i8"
959            | "i128"
960            | "isize"
961            | "u64"
962            | "u32"
963            | "u16"
964            | "u8"
965            | "u128"
966            | "usize"
967            | "f64"
968            | "f32"
969            | "bool"
970            | "char"
971            | "()"
972    )
973}
974
975thread_local! {
976    /// While an outermost enum-variant construction is emitted: for each variable named inside it, how many
977    /// times it is named in all and how many of those are still to be emitted (see the `NewVariant` arm). `None`
978    /// outside any construction.
979    static CONSTRUCTION_USES: std::cell::RefCell<Option<HashMap<Symbol, (usize, usize)>>> =
980        const { std::cell::RefCell::new(None) };
981}
982
983thread_local! {
984    /// The type parameters of the generic function whose body is being emitted. A value typed by
985    /// one is never `Copy` as far as the body knows; storing it copies it (the parameter is bounded
986    /// `Clone`). Installed for one function's emission by [`GenericParamsInScope`].
987    static GENERIC_PARAMS: std::cell::RefCell<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) };
988}
989
990/// The type parameters of one generic function, in scope while its signature and body are
991/// emitted; the previous set comes back when this is dropped.
992pub(crate) struct GenericParamsInScope(Vec<String>);
993
994impl GenericParamsInScope {
995    pub(crate) fn enter(params: Vec<String>) -> Self {
996        Self(GENERIC_PARAMS.with(|g| std::mem::replace(&mut *g.borrow_mut(), params)))
997    }
998}
999
1000impl Drop for GenericParamsInScope {
1001    fn drop(&mut self) {
1002        GENERIC_PARAMS.with(|g| *g.borrow_mut() = std::mem::take(&mut self.0));
1003    }
1004}
1005
1006thread_local! {
1007    /// The `mutable` collection parameters of the function whose body is being emitted. Each is
1008    /// the caller's own list or map, lent as a `&LogosSeq`/`&LogosMap`: its writes are meant to
1009    /// reach the caller, so it is never copied on write (and a `&` handle cannot give up its
1010    /// buffer). Installed for one function's emission by [`LentParamsInScope`].
1011    static LENT_PARAMS: std::cell::RefCell<HashSet<Symbol>> = std::cell::RefCell::new(HashSet::new());
1012}
1013
1014/// The `mutable` collection parameters of one function, in scope while its body is emitted; the
1015/// previous set comes back when this is dropped.
1016pub(crate) struct LentParamsInScope(HashSet<Symbol>);
1017
1018impl LentParamsInScope {
1019    pub(crate) fn enter(params: HashSet<Symbol>) -> Self {
1020        Self(LENT_PARAMS.with(|l| std::mem::replace(&mut *l.borrow_mut(), params)))
1021    }
1022}
1023
1024impl Drop for LentParamsInScope {
1025    fn drop(&mut self) {
1026        LENT_PARAMS.with(|l| *l.borrow_mut() = std::mem::take(&mut self.0));
1027    }
1028}
1029
1030/// Whether a `mutable` parameter of Rust type `rust_ty` is lent as a shared `&` reference: a
1031/// `LogosSeq`/`LogosMap` writes through its own `RefCell`, so `&` is all a callee needs, and a
1032/// shared reference can be passed on and read beside other borrows. Every other type — a record,
1033/// a scalar, a `Set` — is lent as `&mut`.
1034pub(crate) fn lent_by_shared_reference(rust_ty: &str) -> bool {
1035    rust_ty.starts_with("LogosSeq") || rust_ty.starts_with("LogosMap")
1036}
1037
1038/// Whether `expr` reads a `mutable` parameter lent as `&mut` whole, by a value that is not `Copy`:
1039/// the value handed out is a copy, since the place behind the reference stays the caller's.
1040pub(crate) fn copies_out_of_a_lend(expr: &Expr, variable_types: &HashMap<Symbol, String>) -> bool {
1041    match expr {
1042        Expr::Identifier(sym) => {
1043            lent_in_place(*sym, variable_types) && identifier_read_moves(*sym, variable_types)
1044        }
1045        Expr::FieldAccess { .. } => {
1046            lent_field_type(expr, variable_types).is_some_and(|ty| field_read_moves(&ty))
1047        }
1048        _ => false,
1049    }
1050}
1051
1052/// The Rust type of a field read out of a record lent in place (`(*b).f`, `(*b).f.g`) — what the
1053/// read would move out of the caller's record unless it copies. `None` for anything else.
1054fn lent_field_type(expr: &Expr, variable_types: &HashMap<Symbol, String>) -> Option<String> {
1055    match expr {
1056        Expr::Identifier(sym) if lent_in_place(*sym, variable_types) => {
1057            let ty = variable_types.get(sym)?;
1058            Some(ty.split("|__hl:").next().unwrap_or(ty).to_string())
1059        }
1060        Expr::FieldAccess { object, field } => {
1061            let record = lent_field_type(object, variable_types)?;
1062            super::types::program_record_field_type(&record, *field)
1063        }
1064        _ => None,
1065    }
1066}
1067
1068/// Whether `sym` is a `mutable` list or map parameter of the function being emitted, lent as the caller's own
1069/// buffer ([`lent_by_shared_reference`]): every write the body makes lands in the caller's list, so a value the body
1070/// copies out of it must own its items, never share that buffer.
1071pub(crate) fn lent_by_sharing(sym: Symbol, variable_types: &HashMap<Symbol, String>) -> bool {
1072    LENT_PARAMS.with(|l| l.borrow().contains(&sym))
1073        && variable_types.get(&sym).is_some_and(|t| lent_by_shared_reference(t.split("|__hl:").next().unwrap_or(t)))
1074}
1075
1076/// Whether `sym` is a `mutable` parameter of the function being emitted that is lent as `&mut`
1077/// ([`lent_by_shared_reference`]): the body reads and writes it as the place `(*sym)`, so it is the
1078/// caller's own value every write lands on.
1079pub(crate) fn lent_in_place(sym: Symbol, variable_types: &HashMap<Symbol, String>) -> bool {
1080    LENT_PARAMS.with(|l| l.borrow().contains(&sym))
1081        && !variable_types
1082            .get(&sym)
1083            .is_some_and(|t| lent_by_shared_reference(t))
1084}
1085
1086/// The Rust identifier of `collection` when writing it in place — or lending it to a `mutable`
1087/// parameter, which writes it in place — must first copy it on write: value semantics is on and
1088/// `collection` names an owned `LogosSeq`/`LogosMap` binding, whose shared `Rc` buffer a value
1089/// copied from it may still hold. `None` for every other handle:
1090/// - a de-Rc'd plain `Vec`/`HashMap` local, and the specialized `LogosI64Map`/`LogosI32Map`/
1091///   `LogosDense…`/set variants — none shares a buffer;
1092/// - a `mutable` parameter, the caller's own list lent as a `&LogosSeq`/`&LogosMap` (see
1093///   [`LentParamsInScope`]);
1094/// - an expression that is not a binding (a field, a temporary).
1095///
1096/// Under reference semantics (`LOGOS_VALUE_SEMANTICS=0`, or the compile-time PE reference scope) a
1097/// write is meant to reach every alias, so nothing is copied.
1098pub(crate) fn cow_handle(
1099    collection: &Expr,
1100    variable_types: &HashMap<Symbol, String>,
1101    names: &RustNames,
1102) -> Option<String> {
1103    if !crate::semantics::collections::value_semantics_enabled() {
1104        return None;
1105    }
1106    let (place, ty) = collection_place(collection, variable_types, names)?;
1107    lent_by_shared_reference(&ty).then_some(place)
1108}
1109
1110/// The Rust place `collection` names and its Rust type, when it is a binding or a field of one
1111/// (`b's tape`, `(*b).tape` for a record lent as `&mut`). A copied record shares its lists with
1112/// the original until one of them writes, so a field is copied on write exactly as a binding is.
1113/// `None` for a `mutable` collection parameter — the caller's own list, lent to be written — and
1114/// for anything that is not a place.
1115fn collection_place(
1116    collection: &Expr,
1117    variable_types: &HashMap<Symbol, String>,
1118    names: &RustNames,
1119) -> Option<(String, String)> {
1120    match collection {
1121        Expr::Identifier(sym) => {
1122            if LENT_PARAMS.with(|l| l.borrow().contains(sym))
1123                && !lent_in_place(*sym, variable_types)
1124            {
1125                return None;
1126            }
1127            let ty = variable_types.get(sym)?;
1128            let ty = ty.split("|__hl:").next().unwrap_or(ty.as_str()).to_string();
1129            let place = if lent_in_place(*sym, variable_types) {
1130                format!("(*{})", names.ident(*sym))
1131            } else {
1132                names.ident(*sym)
1133            };
1134            Some((place, ty))
1135        }
1136        Expr::FieldAccess { object, field } => {
1137            let (place, record) = collection_place(object, variable_types, names)?;
1138            let ty = super::types::program_record_field_type(&record, *field)?;
1139            Some((
1140                format!(
1141                    "{place}.{}",
1142                    crate::codegen::escape_rust_ident(names.raw(*field))
1143                ),
1144                ty,
1145            ))
1146        }
1147        _ => None,
1148    }
1149}
1150
1151/// Whether the Rust type `ty` names one of the type parameters in scope (`T`, `LogosSeq<T>`).
1152pub(crate) fn mentions_generic_param(ty: &str) -> bool {
1153    GENERIC_PARAMS.with(|g| {
1154        g.borrow().iter().any(|p| {
1155            ty.match_indices(p.as_str()).any(|(at, _)| {
1156                let before = ty[..at].chars().next_back();
1157                let after = ty[at + p.len()..].chars().next();
1158                let ident = |c: char| c.is_alphanumeric() || c == '_';
1159                !before.is_some_and(ident) && !after.is_some_and(ident)
1160            })
1161        })
1162    })
1163}
1164
1165/// Does reading variable `sym` by value consume its binding? Only a `Copy` scalar leaves the binding
1166/// usable. An overflow-promoting `LogosInt` is already cloned by the identifier arm itself, and an
1167/// untracked variable may hold a record, so it counts as moving.
1168fn identifier_read_moves(sym: Symbol, types: &HashMap<Symbol, String>) -> bool {
1169    match types.get(&sym) {
1170        Some(t) => {
1171            let base = t.split("|__hl:").next().unwrap_or(t);
1172            !base.contains("__bigint") && field_read_moves(base)
1173        }
1174        None => true,
1175    }
1176}
1177
1178/// Does passing this argument to a parameter of Rust type `param_ty` MOVE a field out of its
1179/// record? Only then is a clone owed.
1180///
1181/// ★ KEYED ON THE CALLEE'S PARAMETER, NOT THE RECORD'S FIELD — which is the whole reason this
1182/// works. `record_field_rust_type` needs `variable_types` to name the record, and that map holds
1183/// typed PARAMETERS and almost nothing else, so a rule built on it fires for `## To f (r: Row)`
1184/// and stays silent one line below for `Let r be a new Row`. A callee's signature, by contrast, is
1185/// always known: it is a declared function.
1186///
1187/// ★ AND IT STAYS NARROW, which the partial evaluator requires. `phase_futamura` ratchets on the
1188/// SIZE of a residual program, so a clone emitted where no move occurs is paid for by every
1189/// specialization. A borrowed parameter (`&…`) takes nothing; a `Copy` scalar parameter takes a
1190/// copy; only an owned non-`Copy` parameter consumes what it is given.
1191fn field_arg_needs_clone(arg: &Expr, param_ty: Option<String>) -> bool {
1192    let bare = match arg {
1193        Expr::Copy { expr } => *expr,
1194        other => other,
1195    };
1196    if !matches!(bare, Expr::FieldAccess { .. }) {
1197        return false;
1198    }
1199    param_ty.is_some_and(|t| !t.starts_with('&') && field_read_moves(&t))
1200}
1201
1202/// Whether `value` is a bare variable holding a collection (a `LogosSeq`, `LogosMap`, `Vec` or `HashMap`): storing
1203/// it anywhere but at its last use needs a copy.
1204fn holds_collection(value: &Expr, types: &HashMap<Symbol, String>) -> bool {
1205    let Expr::Identifier(s) = value else {
1206        return false;
1207    };
1208    types.get(s).is_some_and(|t| {
1209        let base = t.split("|__hl:").next().unwrap_or(t);
1210        base.starts_with("LogosSeq")
1211            || base.starts_with("LogosMap")
1212            || base.starts_with("Vec<")
1213            || base.starts_with("HashMap")
1214    })
1215}
1216
1217pub(crate) fn is_value_struct_identifier(value: &Expr, types: &HashMap<Symbol, String>) -> bool {
1218    // A value read can arrive wrapped in a `Copy` marker (`Expr::Copy { expr: Identifier(..) }`) — the
1219    // same unwrap the struct-New slice check does — so see through it to the underlying identifier.
1220    let value = match value {
1221        Expr::Copy { expr } => expr,
1222        other => other,
1223    };
1224    if let Expr::Identifier(s) = value {
1225        match types.get(s) {
1226            Some(t) => {
1227                let base = t.split("|__hl:").next().unwrap_or(t);
1228                if base == "String" {
1229                    return true;
1230                }
1231                let copy_or_collection = matches!(
1232                    base,
1233                    "i64"
1234                        | "i32"
1235                        | "i16"
1236                        | "i8"
1237                        | "i128"
1238                        | "isize"
1239                        | "u64"
1240                        | "u32"
1241                        | "u16"
1242                        | "u8"
1243                        | "u128"
1244                        | "usize"
1245                        | "f64"
1246                        | "f32"
1247                        | "bool"
1248                        | "char"
1249                        | "()"
1250                ) || base.starts_with('&')
1251                    || base.starts_with("LogosSeq")
1252                    || base.starts_with("LogosMap")
1253                    || base.starts_with("Vec<")
1254                    || base.starts_with("HashMap")
1255                    || base.contains("__bigint");
1256                return !copy_or_collection;
1257            }
1258            // Untracked type: the value may be a non-Copy struct/enum, so a value-semantics store must
1259            // copy it — clone rather than risk an E0382 move. Cloning a Copy value is a harmless no-op,
1260            // and large values are collections, which are TYPED above and excluded. (json's `en` is
1261            // untracked in the SetIndex handler's variable-type view.)
1262            None => return true,
1263        }
1264    }
1265    false
1266}
1267
1268thread_local! {
1269    /// The whole-program set of SCALAR exact higher-order functions (`bigint_promote::exact_hof_fns`
1270    /// — an `Int`/`Nat` return + a `fn`-typed param + no seq param, e.g. `apply(f, x)`). Set once per
1271    /// program at codegen entry by [`set_exact_hofs`]; read at the call emit so a closure argument is
1272    /// rendered exact (`LogosInt` params) and an integer argument is promoted to `LogosInt` — the
1273    /// call-site half of the selective higher-order-overflow analysis. Overwritten per program, so no
1274    /// state leaks (codegen is single-threaded per program).
1275    static EXACT_HOFS: std::cell::RefCell<HashSet<Symbol>> =
1276        std::cell::RefCell::new(HashSet::new());
1277}
1278
1279/// Record the program's scalar exact-HOF set for the current codegen (see [`EXACT_HOFS`]). Called
1280/// once at codegen entry.
1281pub(crate) fn set_exact_hofs(fns: &HashSet<Symbol>) {
1282    EXACT_HOFS.with(|c| *c.borrow_mut() = fns.clone());
1283}
1284
1285/// True iff `function` is a scalar exact higher-order function (its fn-param + int-params + return
1286/// are exactified to `LogosInt`, so a closure argument must render exact and an integer argument
1287/// must promote).
1288fn is_exact_hof_call(function: Symbol) -> bool {
1289    EXACT_HOFS.with(|c| c.borrow().contains(&function))
1290}
1291
1292/// The `|__exact_fnptr` sentinel a `fn`-typed parameter of an exact-HOF is registered with (its Rust
1293/// type is `impl Fn(LogosInt) -> LogosInt`). When such a param is CALLED (`f(x)` inside the HOF
1294/// body), its integer arguments promote to `LogosInt` — the callee-is-a-closure-param half of the
1295/// promotion.
1296const EXACT_FNPTR_MARKER: &str = "|__exact_fnptr";
1297
1298thread_local! {
1299    /// The range oracle of the compile in progress ([`install_range_oracle`]):
1300    /// whether an Int op stays in i64 (`oracle_proves_int_op_in_range`) and
1301    /// whether an access names an item on every run ([`range_proves_index`]),
1302    /// including what the emitted program's own guards establish
1303    /// ([`mark_index_in_range`]). Computed on the SAME statement slice codegen
1304    /// walks, so expression addresses match. It does NOT drive borrow-hoisting /
1305    /// BCE / fast-div (those read the `ExprCtx` oracle). `None` outside a compile,
1306    /// so a freed arena's reused addresses never meet it.
1307    static RANGE_ORACLE: std::cell::RefCell<Option<std::rc::Rc<crate::optimize::OracleFacts>>> =
1308        const { std::cell::RefCell::new(None) };
1309}
1310
1311/// Install the range oracle for one compile ([`RANGE_ORACLE`]); it is removed when the returned scope ends.
1312/// Every fact it holds is keyed by the addresses of that program's nodes, so nothing it proves may outlive
1313/// the compile — a later compile, or an emitter run outside one, sees no oracle at all.
1314pub(crate) fn install_range_oracle(
1315    o: Option<std::rc::Rc<crate::optimize::OracleFacts>>,
1316) -> RangeOracleScope {
1317    RANGE_ORACLE.with(|c| *c.borrow_mut() = o);
1318    RangeOracleScope(())
1319}
1320
1321/// The lifetime of one compile's range oracle ([`install_range_oracle`]).
1322pub(crate) struct RangeOracleScope(());
1323
1324impl Drop for RangeOracleScope {
1325    fn drop(&mut self) {
1326        RANGE_ORACLE.with(|c| *c.borrow_mut() = None);
1327    }
1328}
1329
1330/// Whether a range oracle is installed now.
1331pub(crate) fn range_oracle_installed() -> bool {
1332    RANGE_ORACLE.with(|c| c.borrow().is_some())
1333}
1334
1335thread_local! {
1336    /// Whole-program map: user function name → its parameters' Rust types (as `codegen_type_expr`
1337    /// spells them, e.g. `"f64"` for a `Real` parameter). Set once per program at codegen entry by
1338    /// [`set_fn_param_types`]; read at the user-call emit so an integer argument passed to an `f64`
1339    /// (`Real`) parameter is coerced with `as f64` — matching the interpreter/VM, which coerce
1340    /// int→Real at the call boundary, so `sin(0)` / `cConj(3, 4)` type-check on the AOT tier too.
1341    static FN_PARAM_TYPES: std::cell::RefCell<HashMap<Symbol, Vec<String>>> =
1342        std::cell::RefCell::new(HashMap::new());
1343}
1344
1345/// Install the whole-program function → parameter-Rust-types map for this program. Called once at
1346/// codegen entry (overwrites any prior program's map, so it never goes stale).
1347pub(crate) fn set_fn_param_types(m: &HashMap<Symbol, Vec<String>>) {
1348    FN_PARAM_TYPES.with(|c| *c.borrow_mut() = m.clone());
1349}
1350
1351/// The declared Rust type of `function`'s parameter at `index`, if that user function is known.
1352fn fn_param_rust_type(function: Symbol, index: usize) -> Option<String> {
1353    FN_PARAM_TYPES.with(|c| {
1354        c.borrow()
1355            .get(&function)
1356            .and_then(|v| v.get(index).cloned())
1357    })
1358}
1359
1360/// The argument `Show x to f` hands `f`. Showing LENDS: the caller keeps `x`. A recipient taking a
1361/// reference (the built-in `show`, or a parameter lowered to `&str`/`&[T]`) gets `&x`; one whose
1362/// parameter owns its value (`(data: Text)` lowered to `String`) gets a copy.
1363pub(super) fn lend_to(recipient: &Expr, value: &str) -> String {
1364    let owned = match recipient {
1365        Expr::Identifier(f) => fn_param_rust_type(*f, 0).is_some_and(|t| !t.starts_with('&')),
1366        _ => false,
1367    };
1368    if owned {
1369        format!("({value}).clone()")
1370    } else {
1371        format!("&{value}")
1372    }
1373}
1374
1375thread_local! {
1376    /// Whole-program map: user function name → its declared Rust RETURN type. The sibling of
1377    /// [`FN_PARAM_TYPES`], set at the same codegen entry, and read where a call's result type is
1378    /// inferred — so a program that declares its OWN function with a name math.lg also uses is typed
1379    /// by its own declaration rather than the stdlib's.
1380    static FN_RETURN_TYPES: std::cell::RefCell<HashMap<Symbol, String>> =
1381        std::cell::RefCell::new(HashMap::new());
1382}
1383
1384/// Install the whole-program function → return-Rust-type map. Called once at codegen entry.
1385pub(crate) fn set_fn_return_types(m: &HashMap<Symbol, String>) {
1386    FN_RETURN_TYPES.with(|c| *c.borrow_mut() = m.clone());
1387}
1388
1389/// `f` of the whole-program function → declared-return-Rust-type map.
1390pub(crate) fn with_declared_returns<R>(f: impl FnOnce(&HashMap<Symbol, String>) -> R) -> R {
1391    FN_RETURN_TYPES.with(|c| f(&c.borrow()))
1392}
1393
1394/// True when `function`'s declared return type is an owned `String` or a borrowed `&str` — i.e. a
1395/// call whose result is a text value for the purposes of the `+` concat fold below, exactly like a
1396/// string literal or a `Text`-typed field read. Without this, `f() + g()` where BOTH `f` and `g`
1397/// return `Text` falls through to a bare `+`, and `String + String` has no operator impl (`rustc`
1398/// wants `&str` on the right) — the shape `hexByteText`'s own body hit (`charAtText(...) +
1399/// charAtText(...)`).
1400fn fn_call_returns_text(function: Symbol) -> bool {
1401    FN_RETURN_TYPES.with(|c| {
1402        c.borrow().get(&function).is_some_and(|t| {
1403            let t = t.split("|__hl:").next().unwrap_or(t);
1404            t == "String" || t == "&str"
1405        })
1406    })
1407}
1408
1409thread_local! {
1410    /// Functions whose result is ALREADY a borrowed slice — the `Opt::TextSliceReturn` (`&'a str`)
1411    /// and `Opt::ByteSliceReturn` (`&'a [T]`) families. Kept apart from [`FN_RETURN_TYPES`] on
1412    /// purpose: this answers one question at one emit site (how to marshal the value at a borrow
1413    /// position) and must not perturb whole-program result-type inference.
1414    static BORROWED_RETURN_FNS: std::cell::RefCell<std::collections::HashSet<Symbol>> =
1415        std::cell::RefCell::new(std::collections::HashSet::new());
1416}
1417
1418/// Install the borrowed-slice-returning set. Called once at codegen entry, after the two slice
1419/// analyses have run their caller-gates.
1420pub(crate) fn set_borrowed_return_fns(m: &std::collections::HashSet<Symbol>) {
1421    BORROWED_RETURN_FNS.with(|c| *c.borrow_mut() = m.clone());
1422}
1423
1424/// How a NON-IDENTIFIER argument should reach a borrow-position parameter.
1425///
1426/// The identifier path above reads the variable's tracked Rust type and marshals accordingly; this
1427/// path had no type to read, so it assumed `LogosSeq<T>` and emitted `&*{expr}.borrow()` for
1428/// everything. Two shapes are not `LogosSeq` and the generated Rust did not compile:
1429///
1430/// * a Text literal is a `String` — `&*String::from("xx").borrow()` is
1431///   `E0599: no method named `borrow` found for struct `String``, which failed
1432///   `parity_str_trim_left_func` / `parity_str_trim_right_func`;
1433/// * a call to a slice-return fn is ALREADY `&[T]` — `&*sliceReal(..).borrow()` is
1434///   `E0599 … for reference `&[f64]``, which failed `convert_to_real_functions_compile_on_aot_rust`.
1435///
1436/// Returns the marshalled expression, or `None` to keep the `LogosSeq` default.
1437fn borrow_position_non_identifier(a: &Expr, rendered: &str) -> Option<String> {
1438    match a {
1439        // Already a borrow — hand it straight through.
1440        Expr::Call { function, .. }
1441            if BORROWED_RETURN_FNS.with(|c| c.borrow().contains(function)) =>
1442        {
1443            Some(rendered.to_string())
1444        }
1445        // `String`/`&str`-shaped values: `&String` coerces to `&str`, the same move the identifier
1446        // path makes for a `String` variable.
1447        Expr::Literal(Literal::Text(_)) | Expr::InterpolatedString(_) => {
1448            Some(format!("&{rendered}"))
1449        }
1450        Expr::Call { function, .. } => {
1451            let declared = FN_RETURN_TYPES.with(|c| c.borrow().get(function).cloned())?;
1452            let declared = declared
1453                .split("|__hl:")
1454                .next()
1455                .unwrap_or(&declared)
1456                .to_string();
1457            if declared == "String" || declared == "&str" || declared.starts_with("&[") {
1458                Some(if declared.starts_with('&') {
1459                    rendered.to_string()
1460                } else {
1461                    format!("&{rendered}")
1462                })
1463            } else if declared.starts_with("Vec<") || declared.starts_with('[') {
1464                Some(format!("&{rendered}"))
1465            } else {
1466                None
1467            }
1468        }
1469        _ => None,
1470    }
1471}
1472
1473/// Does a call to `function` produce a float? A math.lg `-> Real` name does — UNLESS this program
1474/// declares a function of its own by that name, in which case the program's declaration wins.
1475///
1476/// The name list exists because the `TypeEnv` at these sites carries no function signatures; it is a
1477/// list of NAMES, so it cannot tell `math.lg`'s `gamma (z: Real) -> Real` from a program's own
1478/// `## To gamma (n: Int) -> Int`. It typed the latter's calls as `f64` and emitted
1479/// `gamma(n - 1) + ((1) as f64)` against an `i64` — Rust that does not compile. Same family as a
1480/// stdlib name shadowing a user's: whoever declared it in THIS program owns it.
1481pub(crate) fn is_float_returning_math_call(function: Symbol, interner: &Interner) -> bool {
1482    if let Some(declared) = FN_RETURN_TYPES.with(|c| c.borrow().get(&function).cloned()) {
1483        return declared == "f64";
1484    }
1485    is_float_returning_math_fn(interner.resolve(function))
1486}
1487
1488/// The machine number a call to one of this program's functions returns, by its declaration: `i64` for an `-> Int`
1489/// lowered to a word, `f64` for a `-> Real`. A call typed `unknown` took a raw `+` beside an Int, which a word
1490/// overflows silently where every other tier answers exactly.
1491pub(crate) fn declared_numeric_return(function: Symbol) -> Option<&'static str> {
1492    FN_RETURN_TYPES.with(|c| {
1493        c.borrow()
1494            .get(&function)
1495            .and_then(|t| match t.split("|__hl:").next().unwrap_or(t) {
1496                "i64" => Some("i64"),
1497                "f64" => Some("f64"),
1498                _ => None,
1499            })
1500    })
1501}
1502
1503thread_local! {
1504    /// A transient hint for the ONE promoted-`LogosInt` accumulator read that is a
1505    /// dead last-use: the accumulator in `Set p to <expr mentioning p exactly once>`,
1506    /// or the bare `Return p` of a bignum function. While set, the first value-position
1507    /// read of that symbol is emitted as a MOVE instead of `.clone()` — the read is
1508    /// immediately followed by a reassignment (or a return), so the old binding is
1509    /// dead. Set around a single statement's RHS codegen and consumed on the matching
1510    /// read (both the emitter and the read clear it), so exactly one move is ever
1511    /// licensed and no hint leaks to another statement. Codegen is single-threaded per
1512    /// program, so this never races.
1513    static MOVABLE_LAST_USE: std::cell::RefCell<Option<Symbol>> =
1514        const { std::cell::RefCell::new(None) };
1515}
1516
1517/// Mark `sym` as movable at its next value-position read (see [`MOVABLE_LAST_USE`]);
1518/// `None` clears the mark. The caller sets this only when it has proven the read is a
1519/// dead last-use (the accumulator appears exactly once in the RHS it is reassigned by).
1520pub(crate) fn set_movable_last_use(sym: Option<Symbol>) {
1521    MOVABLE_LAST_USE.with(|c| *c.borrow_mut() = sym);
1522}
1523
1524/// Whether `sym` is currently marked movable (a peek — the mark is cleared by the
1525/// emitter that set it, once the whole RHS is rendered). Peeking rather than
1526/// consuming is deliberate: the `BinaryOp` arm may render an operand more than once
1527/// (an early `left_str` the promoted-exact path then discards), and the mark is only
1528/// ever set when `sym` occurs exactly once in the AST — so at most one rendered read
1529/// reaches the emitted output, and every read of it is a safe move.
1530fn is_movable_last_use(sym: Symbol) -> bool {
1531    MOVABLE_LAST_USE.with(|c| *c.borrow() == Some(sym))
1532}
1533
1534/// Does `e` PRODUCE a value stored as the overflow-promoting `LogosInt`? — a variable typed with
1535/// the `|__bigint` sentinel, or an inline call to a bignum-returning function. Such an operand
1536/// forces the exact-helper path so the result stays `LogosInt` rather than a raw `i64` operator
1537/// (or `as u64` cast) that `LogosInt` has no impl for.
1538fn mentions_bigint_var(e: &Expr, variable_types: &HashMap<Symbol, String>) -> bool {
1539    match e {
1540        Expr::Identifier(s) => variable_types
1541            .get(s)
1542            .map_or(false, |t| t.contains("__bigint")),
1543        // ★ A FIELD STORED AS `LogosInt` IS A BIGNUM OPERAND. `c's v * 2` emitted a plain `*`
1544        // between a `LogosInt` and an integer literal — "cannot multiply `LogosInt` by
1545        // `{integer}`" — because only a promoted VARIABLE counted. Reading a promoted field is the
1546        // same fact arriving by a different route.
1547        Expr::FieldAccess { field, .. } => is_exact_field_name(*field),
1548        Expr::Call { function, .. } => is_bigint_returning_call(*function),
1549        Expr::BinaryOp { left, right, .. } => {
1550            mentions_bigint_var(left, variable_types) || mentions_bigint_var(right, variable_types)
1551        }
1552        Expr::Not { operand } => mentions_bigint_var(operand, variable_types),
1553        _ => false,
1554    }
1555}
1556
1557thread_local! {
1558    /// Fresh-temp counter for the by-ref bignum operand bindings (see
1559    /// [`bignum_operand_place`]). Monotonic across a program — each `let __lbop{n}`
1560    /// lands in its own nested block, so uniqueness only needs to avoid a same-name
1561    /// collision between two temps that share a scope; a global counter suffices.
1562    static BIGNUM_TMP: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1563}
1564
1565/// A borrowable `LogosInt` place for one operand of a by-reference bignum `+`/`-`/`*`
1566/// (the clone-eliding lowering at the exact-op emit). A promoted (`__bigint`) VARIABLE is
1567/// returned as its bare place (`acc`, or `(*x)` when boxed) so the enclosing method BORROWS it
1568/// — the entire point, since `logos_*_exact(a, b)` takes its operands by value and thus
1569/// `.clone()`s a reused bignum's heap buffer. Anything else — an i64 leaf, a numeric literal, a
1570/// nested arithmetic op, a bignum-returning call — is codegen'd in the exact-tolerant context and
1571/// bound once to a fresh `LogosInt` temp via `.into()` (a no-op move for a value already
1572/// `LogosInt`; a cheap `Small` wrap for an i64), whose name is returned. The result is usable
1573/// both as a receiver (`place.mul(..)`, which auto-borrows) and, prefixed with `&`, as the by-ref
1574/// argument (`&place`).
1575fn bignum_operand_place(
1576    operand: &Expr,
1577    ecx: &ExprCtx,
1578    names: &RustNames,
1579    prelude: &mut String,
1580) -> String {
1581    if let Expr::Identifier(sym) = operand {
1582        if ecx
1583            .variable_types
1584            .get(sym)
1585            .map_or(false, |t| t.contains("__bigint"))
1586        {
1587            let name = names.ident(*sym);
1588            return if ecx.boxed_bindings.contains(sym) {
1589                format!("(*{})", name)
1590            } else {
1591                name
1592            };
1593        }
1594    }
1595    let tol = ExprCtx {
1596        int_exact_tolerant: true,
1597        ..*ecx
1598    };
1599    let emitted = codegen_expr_ctx(operand, &tol);
1600    let n = BIGNUM_TMP.with(|c| {
1601        let v = c.get();
1602        c.set(v + 1);
1603        v
1604    });
1605    let tmp = format!("__lbop{}", n);
1606    prelude.push_str(&format!(
1607        "let {}: logicaffeine_data::LogosInt = ({}).into(); ",
1608        tmp, emitted
1609    ));
1610    tmp
1611}
1612
1613enum ConstExact {
1614    /// The exact result fits i64 — emit today's raw text, byte-identical.
1615    InRange,
1616    /// The exact result escapes i64 — the promoted `LogosInt` literal.
1617    Promoted(String),
1618}
1619
1620/// Evaluate `a op b` exactly at compile time (i128 covers any single i64 op).
1621/// `None` = not decidable here (a zero divisor falls to the runtime helper,
1622/// which raises the canonical catchable error).
1623fn const_exact_int(op: BinaryOpKind, a: i64, b: i64) -> Option<ConstExact> {
1624    let exact: i128 = match op {
1625        BinaryOpKind::Add => a as i128 + b as i128,
1626        BinaryOpKind::Subtract => a as i128 - b as i128,
1627        BinaryOpKind::Multiply => a as i128 * b as i128,
1628        BinaryOpKind::Divide => {
1629            if b == 0 {
1630                return None;
1631            }
1632            a as i128 / b as i128
1633        }
1634        BinaryOpKind::Modulo => {
1635            if b == 0 {
1636                return None;
1637            }
1638            a as i128 % b as i128
1639        }
1640        _ => return None,
1641    };
1642    Some(if i64::try_from(exact).is_ok() {
1643        ConstExact::InRange
1644    } else {
1645        ConstExact::Promoted(format!("LogosInt::from_literal(\"{}\")", exact))
1646    })
1647}
1648
1649/// True when the range-analysis Oracle bounds BOTH operands such that the
1650/// exact result provably fits i64 — the license for raw (unchecked) i64
1651/// emission. Add/Sub are monotone in each operand; Mul takes the corner
1652/// products. Div/Mod never qualify here (their rims are divisor-shaped,
1653/// not range-shaped) — they go through the checked helper when non-const.
1654fn oracle_proves_int_op_in_range(
1655    ecx: &ExprCtx,
1656    whole: &Expr,
1657    op: BinaryOpKind,
1658    left: &Expr,
1659    right: &Expr,
1660) -> bool {
1661    // A constructing pass (e.g. `try_defer_modulus`) may have PROVEN this very
1662    // node in-range when it built it — its version guard is the proof the
1663    // interval fixpoint cannot re-derive (accumulators widen to ±∞ by design).
1664    if crate::optimize::facts::holds_expr(crate::optimize::facts::Fact::RawIntOp, whole) {
1665        return true;
1666    }
1667    // Prefer the `ExprCtx` oracle (present on the borrow-hoisting path); else the
1668    // codegen-wide range oracle, computed for arithmetic guard-elimination even
1669    // when borrow-hoisting is off (the default, since `Scalarize` preempts
1670    // `HoistBorrows`). Same range analysis — only the availability differs.
1671    if let Some(o) = ecx.oracle {
1672        return oracle_facts_prove_int_op(o, whole, op, left, right);
1673    }
1674    RANGE_ORACLE.with(|r| match r.borrow().as_deref() {
1675        Some(o) => oracle_facts_prove_int_op(o, whole, op, left, right),
1676        None => false,
1677    })
1678}
1679
1680/// The range check over a specific [`OracleFacts`]: is the exact result of
1681/// `left op right` provably inside i64? Add/Sub are monotone in each operand;
1682/// Mul takes the corner products. Div/Mod never qualify here (their rims are
1683/// divisor-shaped, not range-shaped).
1684fn oracle_facts_prove_int_op(
1685    o: &crate::optimize::OracleFacts,
1686    whole: &Expr,
1687    op: BinaryOpKind,
1688    left: &Expr,
1689    right: &Expr,
1690) -> bool {
1691    // If the oracle bounds the WHOLE expression to an i64 range (the affine
1692    // index proof `prev[w - wi]` gives `w - wi ∈ [0, len)`), it cannot overflow.
1693    if o.expr_int_range(whole).is_some() {
1694        return true;
1695    }
1696    let (Some((la, lb)), Some((ra, rb))) = (o.expr_int_range(left), o.expr_int_range(right)) else {
1697        return false;
1698    };
1699    let (la, lb, ra, rb) = (la as i128, lb as i128, ra as i128, rb as i128);
1700    let (lo, hi) = match op {
1701        BinaryOpKind::Add => (la + ra, lb + rb),
1702        BinaryOpKind::Subtract => (la - rb, lb - ra),
1703        BinaryOpKind::Multiply => {
1704            let c = [la * ra, la * rb, lb * ra, lb * rb];
1705            (*c.iter().min().unwrap(), *c.iter().max().unwrap())
1706        }
1707        _ => return false,
1708    };
1709    lo >= i64::MIN as i128 && hi <= i64::MAX as i128
1710}
1711
1712/// If `index` is a **coefficient-1 affine** expression in a `__zero_based_i64`
1713/// loop counter — `j`, `j + k`, `k + j`, or `j - k` (literal `k`) — return
1714/// `(counter_sym, delta)`. The 0-based array index is then `counter + delta`
1715/// with **no** 1-based `- 1` (the counter's rebase already absorbed it): original
1716/// `item (j + k) of arr` = `arr[(j₁ + k) - 1]` and with `j₀ = j₁ - 1` that is
1717/// `arr[j₀ + k]`. Only coefficient 1 is a clean `-1` cancellation (a `2*j` index
1718/// is not), so `2*j` etc. return `None` — and the loop-rebase eligibility gate
1719/// (`counter_only_used_for_indexing`) never zero-based-registers a counter used
1720/// in a non-coeff-1 index, so this stays sound.
1721pub(crate) fn zero_based_affine_index(
1722    index: &Expr,
1723    variable_types: &HashMap<Symbol, String>,
1724) -> Option<(Symbol, i64)> {
1725    let is_zb = |s: Symbol| {
1726        variable_types
1727            .get(&s)
1728            .map_or(false, |t| t == "__zero_based_i64")
1729    };
1730    match index {
1731        Expr::Identifier(s) if is_zb(*s) => Some((*s, 0)),
1732        Expr::BinaryOp {
1733            op: BinaryOpKind::Add,
1734            left,
1735            right,
1736        } => {
1737            if let (Expr::Identifier(s), Expr::Literal(Literal::Number(n))) = (left, right) {
1738                if is_zb(*s) {
1739                    return Some((*s, *n));
1740                }
1741            }
1742            if let (Expr::Literal(Literal::Number(n)), Expr::Identifier(s)) = (left, right) {
1743                if is_zb(*s) {
1744                    return Some((*s, *n));
1745                }
1746            }
1747            None
1748        }
1749        Expr::BinaryOp {
1750            op: BinaryOpKind::Subtract,
1751            left,
1752            right,
1753        } => {
1754            if let (Expr::Identifier(s), Expr::Literal(Literal::Number(n))) = (left, right) {
1755                if is_zb(*s) {
1756                    return Some((*s, -*n));
1757                }
1758            }
1759            None
1760        }
1761        _ => None,
1762    }
1763}
1764
1765/// The 0-based **i64** index string for a coeff-1 affine zero-based index (`j`,
1766/// `(j + k)`, `(j - k)`), or `None` if `index` is not one. Shared by every indexed
1767/// read/write site; callers append `as usize` for indexing, or use it as-is (i64)
1768/// for the BCE `debug_assert!` bound.
1769pub(crate) fn zero_based_index_str(
1770    index: &Expr,
1771    variable_types: &HashMap<Symbol, String>,
1772    interner: &Interner,
1773) -> Option<String> {
1774    let (sym, delta) = zero_based_affine_index(index, variable_types)?;
1775    let name = RustNames::new(interner).ident(sym);
1776    Some(if delta == 0 {
1777        name.to_string()
1778    } else if delta > 0 {
1779        format!("({} + {})", name, delta)
1780    } else {
1781        format!("({} - {})", name, -delta)
1782    })
1783}
1784
1785/// The 1-based index `index` names, as an i64 expression for `LogosItems::logos_item`: a loop counter the
1786/// codegen rebased to 0 gets its 1 back, and anything else is the index as written. The item accessor holds
1787/// the whole rule, so no index is folded here: `(i - 1) as usize` means something else once `i` is negative.
1788pub(crate) fn logos_index_str(
1789    index: &Expr,
1790    ecx: &ExprCtx,
1791    variable_types: &HashMap<Symbol, String>,
1792    interner: &Interner,
1793) -> String {
1794    rebased_logos_index(index, variable_types, interner).unwrap_or_else(|| {
1795        codegen_expr_ctx(
1796            index,
1797            &ExprCtx {
1798                int_index_context: true,
1799                ..*ecx
1800            },
1801        )
1802    })
1803}
1804
1805/// The 1-based index a coefficient-1 affine index in a rebased loop counter names (`j`, `j + k`,
1806/// `j - k`, the counter 0-based): the counter with its 1 given back. `None` for any other index.
1807pub(crate) fn rebased_logos_index(
1808    index: &Expr,
1809    variable_types: &HashMap<Symbol, String>,
1810    interner: &Interner,
1811) -> Option<String> {
1812    let (sym, delta) = zero_based_affine_index(index, variable_types)?;
1813    let name = RustNames::new(interner).ident(sym);
1814    let k = delta + 1;
1815    Some(if k == 0 {
1816        name.to_string()
1817    } else if k > 0 {
1818        format!("({} + {})", name, k)
1819    } else {
1820        format!("({} - {})", name, -k)
1821    })
1822}
1823
1824/// The 0-based offset of an index the oracle proved names an item (so it is at least 1), for an unchecked
1825/// access: a rebased loop counter as it is, and `X + K` with its `- 1` folded into `K`.
1826pub(crate) fn proven_offset_str(
1827    index: &Expr,
1828    ecx: &ExprCtx,
1829    variable_types: &HashMap<Symbol, String>,
1830    interner: &Interner,
1831) -> String {
1832    let i = |e: &Expr| {
1833        codegen_expr_ctx(
1834            e,
1835            &ExprCtx {
1836                int_index_context: true,
1837                ..*ecx
1838            },
1839        )
1840    };
1841    if let Some(zb) = zero_based_index_str(index, variable_types, interner) {
1842        return format!("{} as usize", zb);
1843    }
1844    match index {
1845        Expr::Literal(Literal::Number(n)) => format!("{}", n - 1),
1846        Expr::BinaryOp {
1847            op: BinaryOpKind::Add,
1848            left,
1849            right,
1850        } => match (left, right) {
1851            (_, Expr::Literal(Literal::Number(1))) => match left {
1852                Expr::Identifier(_) => format!("{} as usize", i(left)),
1853                _ => format!("({}) as usize", i(left)),
1854            },
1855            (Expr::Literal(Literal::Number(1)), _) => match right {
1856                Expr::Identifier(_) => format!("{} as usize", i(right)),
1857                _ => format!("({}) as usize", i(right)),
1858            },
1859            (_, Expr::Literal(Literal::Number(k))) if *k > 1 => {
1860                format!("({} + {}) as usize", i(left), k - 1)
1861            }
1862            (Expr::Literal(Literal::Number(k)), _) if *k > 1 => {
1863                format!("({} + {}) as usize", i(right), k - 1)
1864            }
1865            _ => format!("({} - 1) as usize", i(index)),
1866        },
1867        _ => format!("({} - 1) as usize", i(index)),
1868    }
1869}
1870
1871/// Is `e` an Int-exactable arithmetic interior node — the shape the tolerant
1872/// `LogosInt` chain would own?
1873fn is_exact_arith_node(e: &Expr) -> bool {
1874    matches!(
1875        e,
1876        Expr::BinaryOp {
1877            op: BinaryOpKind::Add
1878                | BinaryOpKind::Subtract
1879                | BinaryOpKind::Multiply
1880                | BinaryOpKind::Divide
1881                | BinaryOpKind::Modulo,
1882            ..
1883        }
1884    )
1885}
1886
1887/// Predicts whether `codegen_expr_ctx(e, ecx)` yields a pure-`i64` Rust expression rather than a
1888/// promoted `LogosInt`. An exactable Int `BinaryOp` promotes to `logos_*_exact` (→ `LogosInt`) UNLESS
1889/// it const-folds in range, is a safe literal `/`/`%`, or the Oracle proves it in i64 range — and it
1890/// is pure-i64 only when EVERY exactable descendant is too. A raw `left op right` composed with a
1891/// promoted operand is a type error (`LogosInt + i64`, E0369): the Oracle can prove an OUTER sum in
1892/// range while an INNER sub-sum promotes (its operand ranges unknown), so the raw fast-paths gate on
1893/// this and fall through to the Into-coercing exact helper when a child would promote. Conservative:
1894/// a node whose rawness it can't confirm (e.g. an i128/dual narrowed chain) reads as promoting, which
1895/// only over-routes to the exact helper — never emits the type-broken mix.
1896fn emits_pure_i64(e: &Expr, ecx: &ExprCtx) -> bool {
1897    let Expr::BinaryOp { left, right, .. } = e else {
1898        return true;
1899    };
1900    if !is_exact_arith_node(e) {
1901        return true;
1902    }
1903    int_op_stays_raw(e, ecx) && emits_pure_i64(left, ecx) && emits_pure_i64(right, ecx)
1904}
1905
1906/// Whether the exactable Int node `e` ITSELF emits raw i64, whatever its operands emit: it const-folds within i64,
1907/// is a `/` or `%` by a safe literal, or the Oracle proves it within i64 — so its exact value is its i64 value.
1908fn int_op_stays_raw(e: &Expr, ecx: &ExprCtx) -> bool {
1909    let Expr::BinaryOp { op, left, right } = e else {
1910        return false;
1911    };
1912    if mentions_bigint_var(e, ecx.variable_types) {
1913        return false;
1914    }
1915    if let (Expr::Literal(Literal::Number(a)), Expr::Literal(Literal::Number(b))) = (left, right) {
1916        matches!(const_exact_int(*op, *a, *b), Some(ConstExact::InRange))
1917    } else {
1918        let safe_lit_div_mod = matches!(right, Expr::Literal(Literal::Number(d))
1919            if (matches!(op, BinaryOpKind::Divide) && *d != 0 && *d != -1)
1920                || (matches!(op, BinaryOpKind::Modulo) && *d != 0));
1921        safe_lit_div_mod || oracle_proves_int_op_in_range(ecx, e, *op, left, right)
1922    }
1923}
1924
1925/// What the Rust emitter proves about the integers of one expression context, for [`super::lowbits`].
1926struct RustWords<'c, 'a> {
1927    ecx: &'c ExprCtx<'a>,
1928}
1929
1930impl super::lowbits::WordProof for RustWords<'_, '_> {
1931    fn stays_in_word(&self, node: &Expr) -> bool {
1932        int_op_stays_raw(node, self.ecx)
1933    }
1934    fn is_word(&self, operand: &Expr) -> bool {
1935        // An item of a sequence held at a narrower integer width (`Vec<i32>`, a byte view) is that width's value,
1936        // and a cast to `u32` reads its low bits as well as an `i64`'s.
1937        let narrow_item = matches!(operand, Expr::Index { collection, .. }
1938            if seq_element_rust_type(collection, self.ecx.variable_types)
1939                .is_some_and(|t| matches!(t, "i8" | "i16" | "i32" | "i64" | "u8" | "u16" | "u32")));
1940        !mentions_bigint_var(operand, self.ecx.variable_types)
1941            && !is_counter_read(operand, self.ecx)
1942            && (narrow_item
1943                || numeric_type_through_arith(operand, self.ecx.interner, self.ecx.variable_types)
1944                    == "i64")
1945            && emits_pure_i64(operand, self.ecx)
1946    }
1947    fn is_nonnegative(&self, value: &Expr) -> bool {
1948        is_nonneg_expr(value)
1949    }
1950}
1951
1952/// The range the oracle proves for `e`: the `ExprCtx` oracle where the borrow-hoisting path carries one, else the
1953/// codegen-wide range oracle.
1954fn oracle_int_range(ecx: &ExprCtx, e: &Expr) -> Option<(i64, i64)> {
1955    if let Some(o) = ecx.oracle {
1956        return o.expr_int_range(e);
1957    }
1958    RANGE_ORACLE.with(|r| r.borrow().as_deref().and_then(|o| o.expr_int_range(e)))
1959}
1960
1961/// Opt::ModWrap: `x % m` for a literal `m > 0` and an `x` the range oracle bounds to `[0, 2m)`, as one conditional
1962/// subtraction, or as `x` itself below `m` ([`crate::optimize::modwrap`]). The oracle's bound on `x` is the same proof that
1963/// emits it as a raw machine word.
1964fn try_mod_wrap(expr: &Expr, ecx: &ExprCtx) -> Option<String> {
1965    let Expr::BinaryOp {
1966        op: BinaryOpKind::Modulo,
1967        left,
1968        right,
1969    } = expr
1970    else {
1971        return None;
1972    };
1973    let Expr::Literal(Literal::Number(m)) = right else {
1974        return None;
1975    };
1976    if !crate::optimize::active_config().is_on(crate::optimization::Opt::ModWrap)
1977        || mentions_bigint_var(left, ecx.variable_types)
1978        || infer_numeric_type(left, ecx.interner, ecx.variable_types) != "i64"
1979    {
1980        return None;
1981    }
1982    let range = oracle_int_range(ecx, left).map(|(lo, hi)| (i128::from(lo), i128::from(hi)));
1983    let wrap = crate::optimize::modwrap::mod_wrap(*m, range)?;
1984    crate::optimize::mark_fired(crate::optimization::Opt::ModWrap);
1985    let word = ExprCtx {
1986        int_exact_tolerant: false,
1987        ..*ecx
1988    };
1989    let x = codegen_expr_ctx(left, &word);
1990    Some(spell_mod_wrap(wrap, &x, &m.to_string(), "i64"))
1991}
1992
1993/// The Rust a [`crate::optimize::modwrap::ModWrap`] reduction of `l % r` reads as, on words of Rust type `ty`.
1994fn spell_mod_wrap(wrap: crate::optimize::modwrap::ModWrap, l: &str, r: &str, ty: &str) -> String {
1995    match wrap {
1996        crate::optimize::modwrap::ModWrap::Identity => format!("({l})"),
1997        crate::optimize::modwrap::ModWrap::Once => format!(
1998            "{{ let __wrap: {ty} = {l}; if __wrap >= {r} {{ __wrap - {r} }} else {{ __wrap }} }}"
1999        ),
2000    }
2001}
2002
2003/// The range the codegen-wide range oracle proves for `e`, for an emitter that carries no `ExprCtx`.
2004fn codegen_oracle_range(e: &Expr) -> Option<(i64, i64)> {
2005    RANGE_ORACLE.with(|r| r.borrow().as_deref().and_then(|o| o.expr_int_range(e)))
2006}
2007
2008/// `l % r` on raw words of Rust type `ty` (`i64` or `i128`), where `r` is the nonzero literal `divisor` and `l` the
2009/// emitted `dividend`: under Opt::ModWrap, one conditional subtraction, or `l` itself, where `range` (the oracle's
2010/// bound on `dividend`) allows it ([`crate::optimize::modwrap`]); the machine remainder otherwise. Every raw emitter spells
2011/// its literal remainder through this one function.
2012fn raw_literal_rem(divisor: i64, range: Option<(i64, i64)>, l: &str, r: &str, ty: &str) -> String {
2013    if crate::optimize::active_config().is_on(crate::optimization::Opt::ModWrap) {
2014        let range = range.map(|(lo, hi)| (i128::from(lo), i128::from(hi)));
2015        if let Some(wrap) = crate::optimize::modwrap::mod_wrap(divisor, range) {
2016            crate::optimize::mark_fired(crate::optimization::Opt::ModWrap);
2017            return spell_mod_wrap(wrap, l, r, ty);
2018        }
2019    }
2020    format!("({l} % {r})")
2021}
2022
2023/// Opt::MaskNarrow: `expr` computed in `u32` wrapping arithmetic under its low mask, when it is an integer chain
2024/// under one (see [`super::lowbits`]). Every operand is emitted as the i64 it is (never a tolerant `LogosInt`) and
2025/// read as its low 32 bits.
2026fn try_mask_narrow(expr: &Expr, ecx: &ExprCtx) -> Option<String> {
2027    if !crate::optimize::active_config().is_on(crate::optimization::Opt::MaskNarrow) {
2028        return None;
2029    }
2030    let masked = super::lowbits::masked_chain(expr, &RustWords { ecx })?;
2031    crate::optimize::mark_fired(crate::optimization::Opt::MaskNarrow);
2032    let operands = ExprCtx {
2033        int_exact_tolerant: false,
2034        ..*ecx
2035    };
2036    Some(format!(
2037        "((({}) & {}u32) as i64)",
2038        rust_low_bits(&masked.chain, &operands),
2039        masked.mask
2040    ))
2041}
2042
2043fn rust_low_bits(chain: &super::lowbits::LowBits, ecx: &ExprCtx) -> String {
2044    use super::lowbits::{LowBits, LowOp};
2045    match chain {
2046        LowBits::Word(e) => format!("(({}) as u32)", codegen_expr_ctx(e, ecx)),
2047        LowBits::Const(c) => format!("{c}u32"),
2048        LowBits::Shl(c, s) => format!("({} << {s})", rust_low_bits(c, ecx)),
2049        LowBits::Op(op, l, r) => {
2050            let (l, r) = (rust_low_bits(l, ecx), rust_low_bits(r, ecx));
2051            match op {
2052                LowOp::Add => format!("{l}.wrapping_add({r})"),
2053                LowOp::Sub => format!("{l}.wrapping_sub({r})"),
2054                LowOp::Mul => format!("{l}.wrapping_mul({r})"),
2055                LowOp::And => format!("({l} & {r})"),
2056                LowOp::Or => format!("({l} | {r})"),
2057                LowOp::Xor => format!("({l} ^ {r})"),
2058            }
2059        }
2060    }
2061}
2062
2063/// `infer_numeric_type` resolved THROUGH exactable arithmetic. `infer_numeric_type` reads a direct
2064/// `item k of arr` as its scalar element type (its Index special-case), but its TypeEnv can't peel a
2065/// scalarized `[i64; N]` element back out through an arithmetic node, so `(item i of arr) + (item j of
2066/// arr)` reports `unknown`. That inconsistency made a leaf index-pair enter the exact-int block (and
2067/// promote to `logos_*_exact` → `LogosInt`) while the enclosing add — seeing an `unknown` operand —
2068/// skipped the block and emitted a raw `i64 +`, composing `LogosInt + i64` (E0369). Resolving arith
2069/// nodes by their operands (float dominates) makes the whole chain enter the block as one consistent
2070/// unit. Only the BinaryOp handler's `left_type`/`right_type` use this — the blast radius is this one
2071/// lowering, not the global `infer_numeric_type`.
2072fn numeric_type_through_arith(
2073    e: &Expr,
2074    interner: &Interner,
2075    variable_types: &HashMap<Symbol, String>,
2076) -> &'static str {
2077    if is_exact_arith_node(e) {
2078        if let Expr::BinaryOp { left, right, .. } = e {
2079            let lt = numeric_type_through_arith(left, interner, variable_types);
2080            let rt = numeric_type_through_arith(right, interner, variable_types);
2081            if lt == "f64" || rt == "f64" {
2082                return "f64";
2083            }
2084            if lt == "i64" && rt == "i64" {
2085                return "i64";
2086            }
2087        }
2088    }
2089    infer_numeric_type(e, interner, variable_types)
2090}
2091
2092/// Worst-case MAGNITUDE of an exact Int chain — the i128-lowering gate. A
2093/// literal costs its own magnitude, every other PROVEN-i64 leaf costs the
2094/// full `2^63` (covers `i64::MIN`); add/sub sum magnitudes, mul multiplies
2095/// them, div keeps the dividend's, rem is bounded by both. Exact tracking
2096/// (not bit-widths, which compound over-estimates: `(i·n + j) + 1` is
2097/// `2^126 + 2^63 + 1`, comfortably inside i128, where width arithmetic
2098/// rounds every step up). `None` = some node is not provably an i64-valued
2099/// Int-chain member, or the bound escapes u128 — only the promoting
2100/// `LogosInt` chain is exact there.
2101fn exact_chain_max_magnitude(e: &Expr, ecx: &ExprCtx) -> Option<u128> {
2102    if mentions_bigint_var(e, ecx.variable_types) {
2103        return None;
2104    }
2105    match e {
2106        Expr::Literal(Literal::Number(n)) => Some(n.unsigned_abs() as u128),
2107        Expr::BinaryOp { op, left, right } if is_exact_arith_node(e) => {
2108            let l = exact_chain_max_magnitude(left, ecx)?;
2109            let r = exact_chain_max_magnitude(right, ecx)?;
2110            match op {
2111                BinaryOpKind::Add | BinaryOpKind::Subtract => l.checked_add(r),
2112                BinaryOpKind::Multiply => l.checked_mul(r),
2113                BinaryOpKind::Divide => Some(l),
2114                BinaryOpKind::Modulo => Some(r.min(l)),
2115                _ => unreachable!("is_exact_arith_node covers exactly these five"),
2116            }
2117        }
2118        _ => (infer_numeric_type(e, ecx.interner, ecx.variable_types) == "i64")
2119            .then_some(1u128 << 63),
2120    }
2121}
2122
2123/// Emit the i128 form of a width-bounded exact chain: leaves cast to i128,
2124/// interiors native (`/`/`%` keep the canonical zero-divisor error via the
2125/// guarded helpers unless the divisor is a nonzero literal).
2126fn emit_exact_chain_i128(e: &Expr, ecx: &ExprCtx) -> String {
2127    match e {
2128        Expr::Literal(Literal::Number(n)) => format!("{}i128", n),
2129        Expr::BinaryOp { op, left, right } if is_exact_arith_node(e) => {
2130            let l = emit_exact_chain_i128(left, ecx);
2131            let r = emit_exact_chain_i128(right, ecx);
2132            let nonzero_lit = matches!(&**right, Expr::Literal(Literal::Number(d)) if *d != 0);
2133            match op {
2134                BinaryOpKind::Add => format!("({} + {})", l, r),
2135                BinaryOpKind::Subtract => format!("({} - {})", l, r),
2136                BinaryOpKind::Multiply => format!("({} * {})", l, r),
2137                BinaryOpKind::Divide if nonzero_lit => format!("({} / {})", l, r),
2138                BinaryOpKind::Divide => format!("logos_div_i128({}, {})", l, r),
2139                BinaryOpKind::Modulo if nonzero_lit => {
2140                    let Expr::Literal(Literal::Number(m)) = &**right else { unreachable!() };
2141                    raw_literal_rem(*m, oracle_int_range(ecx, left), &l, &r, "i128")
2142                }
2143                BinaryOpKind::Modulo => format!("logos_rem_i128({}, {})", l, r),
2144                _ => unreachable!("is_exact_arith_node covers exactly these five"),
2145            }
2146        }
2147        _ => {
2148            let plain = ExprCtx {
2149                int_exact_tolerant: false,
2150                ..*ecx
2151            };
2152            format!("(({}) as i128)", codegen_expr_ctx(e, &plain))
2153        }
2154    }
2155}
2156
2157/// The register-shaped lowerings for a root-NARROWED exact Int op. Both
2158/// tiers preserve the interpreter's semantics bit for bit — same values,
2159/// same canonical error text:
2160///
2161///  - **depth-1** (no exact-chain interior): one fused checked machine op
2162///    (`logos_add_i64` …), overflow to the cold canonical panic;
2163///  - **width-bounded chain**: native i128 with a single root narrow — every
2164///    intermediate is exact by construction, so an oversized intermediate
2165///    that returns to range still succeeds, exactly like the `LogosInt`
2166///    chain it replaces.
2167///
2168/// `None`: the chain's worst case may exceed 127 bits — the promoting
2169/// `LogosInt` chain is the only exact lowering.
2170fn try_fuse_narrowed_int_op(
2171    op: BinaryOpKind,
2172    left: &Expr,
2173    right: &Expr,
2174    ecx: &ExprCtx,
2175) -> Option<String> {
2176    let plain = ExprCtx {
2177        int_exact_tolerant: false,
2178        ..*ecx
2179    };
2180    if !is_exact_arith_node(left) && !is_exact_arith_node(right) {
2181        // Division/modulo by a non-zero constant literal never traps — no div-by-zero, and no
2182        // `i64::MIN / -1` overflow when the divisor is not `-1` — so the checked `logos_div_i64`/
2183        // `logos_rem_i64` helper is dead weight. Emit the raw op (LLVM turns `/ C` into a
2184        // multiply-shift). Mirrors the i128 chain's `safe_lit_div_mod`.
2185        let safe_lit_div_mod = matches!(right, Expr::Literal(Literal::Number(d))
2186            if (matches!(op, BinaryOpKind::Divide) && *d != 0 && *d != -1)
2187                || (matches!(op, BinaryOpKind::Modulo) && *d != 0));
2188        if safe_lit_div_mod {
2189            let l = codegen_expr_ctx(left, &plain);
2190            let r = codegen_expr_ctx(right, &plain);
2191            let sym = if matches!(op, BinaryOpKind::Divide) {
2192                "/"
2193            } else {
2194                "%"
2195            };
2196            return Some(format!("({} {} {})", l, sym, r));
2197        }
2198        let helper = match op {
2199            BinaryOpKind::Add => "logos_add_i64",
2200            BinaryOpKind::Subtract => "logos_sub_i64",
2201            BinaryOpKind::Multiply => "logos_mul_i64",
2202            BinaryOpKind::Divide => "logos_div_i64",
2203            BinaryOpKind::Modulo => "logos_rem_i64",
2204            _ => return None,
2205        };
2206        let l = codegen_expr_ctx(left, &plain);
2207        let r = codegen_expr_ctx(right, &plain);
2208        return Some(format!("{}({}, {})", helper, l, r));
2209    }
2210    None
2211}
2212
2213/// Tier 3 — the width-bounded i128 chain (see [`try_fuse_narrowed_int_op`]
2214/// for tier 1, [`try_guarded_dual_chain`] for the preferred tier 2 on deeper
2215/// chains: raw i64 behind one predictable leaf guard beats branchless i128
2216/// wherever it applies, so this runs LAST).
2217fn try_i128_chain(op: BinaryOpKind, left: &Expr, right: &Expr, ecx: &ExprCtx) -> Option<String> {
2218    let l = exact_chain_max_magnitude(left, ecx)?;
2219    let r = exact_chain_max_magnitude(right, ecx)?;
2220    let root_magnitude = match op {
2221        BinaryOpKind::Add | BinaryOpKind::Subtract => l.checked_add(r)?,
2222        BinaryOpKind::Multiply => l.checked_mul(r)?,
2223        BinaryOpKind::Divide => l,
2224        BinaryOpKind::Modulo => r.min(l),
2225        _ => return None,
2226    };
2227    if root_magnitude > (i128::MAX as u128) {
2228        return None;
2229    }
2230    let le = emit_exact_chain_i128(left, ecx);
2231    let re = emit_exact_chain_i128(right, ecx);
2232    let nonzero_lit = matches!(right, Expr::Literal(Literal::Number(d)) if *d != 0);
2233    let chain = match op {
2234        BinaryOpKind::Add => format!("({} + {})", le, re),
2235        BinaryOpKind::Subtract => format!("({} - {})", le, re),
2236        BinaryOpKind::Multiply => format!("({} * {})", le, re),
2237        BinaryOpKind::Divide if nonzero_lit => format!("({} / {})", le, re),
2238        BinaryOpKind::Divide => format!("logos_div_i128({}, {})", le, re),
2239        BinaryOpKind::Modulo if nonzero_lit => {
2240            let Expr::Literal(Literal::Number(m)) = right else { unreachable!() };
2241            raw_literal_rem(*m, oracle_int_range(ecx, left), &le, &re, "i128")
2242        }
2243        BinaryOpKind::Modulo => format!("logos_rem_i128({}, {})", le, re),
2244        _ => unreachable!("root op matched above"),
2245    };
2246    Some(format!("logos_narrow_i128({})", chain))
2247}
2248
2249/// The key a guarded dual knows a leaf by: a name's symbol (every occurrence in one expression holds the one value
2250/// the guard tests), any other leaf its node.
2251fn dual_leaf_key(e: &Expr) -> usize {
2252    match e {
2253        Expr::Identifier(s) => usize::MAX - s.index(),
2254        _ => e as *const Expr as usize,
2255    }
2256}
2257
2258/// Chain magnitude with every non-literal leaf capped at `bound`, or at its own magnitude when the Oracle proves its
2259/// range (`proven`, by [`dual_leaf_key`]) — the solver's evaluation function for the guarded-dual tier.
2260fn chain_magnitude_with_leaf_bound(
2261    e: &Expr,
2262    bound: u128,
2263    proven: &HashMap<usize, u128>,
2264) -> Option<u128> {
2265    match e {
2266        Expr::Literal(Literal::Number(n)) => Some(n.unsigned_abs() as u128),
2267        Expr::BinaryOp { op, left, right } if is_exact_arith_node(e) => {
2268            let l = chain_magnitude_with_leaf_bound(left, bound, proven)?;
2269            let r = chain_magnitude_with_leaf_bound(right, bound, proven)?;
2270            match op {
2271                BinaryOpKind::Add | BinaryOpKind::Subtract => l.checked_add(r),
2272                BinaryOpKind::Multiply => l.checked_mul(r),
2273                BinaryOpKind::Divide => Some(l),
2274                BinaryOpKind::Modulo => Some(r.min(l)),
2275                _ => unreachable!("is_exact_arith_node covers exactly these five"),
2276            }
2277        }
2278        _ => Some(proven.get(&dual_leaf_key(e)).copied().unwrap_or(bound)),
2279    }
2280}
2281
2282/// Emit a chain over PRE-BOUND leaf names. `raw` picks plain i64 ops (the
2283/// guarded fast branch — proven in range by the leaf-bound guard); otherwise
2284/// the promoting `LogosInt` helpers (the exact slow branch). `/`/`%` keep
2285/// their canonical zero-divisor errors in both forms.
2286fn emit_chain_with_bound_leaves(e: &Expr, names: &HashMap<usize, String>, raw: bool) -> String {
2287    match e {
2288        Expr::Literal(Literal::Number(n)) => format!("{}i64", n),
2289        Expr::BinaryOp { op, left, right } if is_exact_arith_node(e) => {
2290            let l = emit_chain_with_bound_leaves(left, names, raw);
2291            let r = emit_chain_with_bound_leaves(right, names, raw);
2292            let nonzero_lit = matches!(&**right, Expr::Literal(Literal::Number(d)) if *d != 0);
2293            if raw {
2294                match op {
2295                    BinaryOpKind::Add => format!("({} + {})", l, r),
2296                    BinaryOpKind::Subtract => format!("({} - {})", l, r),
2297                    BinaryOpKind::Multiply => format!("({} * {})", l, r),
2298                    BinaryOpKind::Divide if nonzero_lit => format!("({} / {})", l, r),
2299                    BinaryOpKind::Divide => format!("logos_div_i64({}, {})", l, r),
2300                    BinaryOpKind::Modulo if nonzero_lit => {
2301                        let Expr::Literal(Literal::Number(m)) = &**right else { unreachable!() };
2302                        raw_literal_rem(*m, codegen_oracle_range(left), &l, &r, "i64")
2303                    }
2304                    BinaryOpKind::Modulo => format!("logos_rem_i64({}, {})", l, r),
2305                    _ => unreachable!("is_exact_arith_node covers exactly these five"),
2306                }
2307            } else {
2308                let helper = match op {
2309                    BinaryOpKind::Add => "logos_add_exact",
2310                    BinaryOpKind::Subtract => "logos_sub_exact",
2311                    BinaryOpKind::Multiply => "logos_mul_exact",
2312                    BinaryOpKind::Divide => "logos_div_exact",
2313                    BinaryOpKind::Modulo => "logos_rem_exact",
2314                    _ => unreachable!("is_exact_arith_node covers exactly these five"),
2315                };
2316                format!("{}({}, {})", helper, l, r)
2317            }
2318        }
2319        Expr::Identifier(s) => names[&(usize::MAX - s.index())].clone(),
2320        _ => names[&(e as *const Expr as usize)].clone(),
2321    }
2322}
2323
2324/// Tier 3.5 — the GUARDED DUAL for a narrowed chain the i128 gate refused:
2325/// bind every leaf once (evaluation order preserved), test them against the
2326/// largest bound `B` under which the whole chain provably fits i64, and run
2327/// the RAW i64 chain under the guard — the exact `LogosInt` chain otherwise.
2328/// Value- and error-identical to the exact chain (the raw branch is proven
2329/// overflow-free; the slow branch IS the exact chain); what it buys is a
2330/// register-shaped, vectorizable hot path behind one predictable branch. The
2331/// slow branch runs out of line (`logos_cold_path`): inlined, its big-integer
2332/// code crowds the loop it guards. Its closure takes its machine words by
2333/// value: one borrowing a loop counter into an out-of-line call would pin the
2334/// counter to memory for the whole loop.
2335fn try_guarded_dual_chain<'e>(
2336    op: BinaryOpKind,
2337    left: &'e Expr<'e>,
2338    right: &'e Expr<'e>,
2339    whole_ecx: &ExprCtx,
2340) -> Option<String> {
2341    let dual = guarded_dual_parts(op, left, right, whole_ecx, "__chain_l")?;
2342    Some(match dual.guard {
2343        Some(guard) => format!(
2344            "{{ {}if {guard} {{ {} }} else {{ logos_cold_path(move || {}.expect_i64(\"Int\")) }} }}",
2345            dual.binds, dual.fast, dual.slow
2346        ),
2347        None => format!("{{ {}{} }}", dual.binds, dual.fast),
2348    })
2349}
2350
2351/// An exact Int chain as checked machine-word arithmetic: its leaves bound once (`binds`), `checked` — an
2352/// `Option<i64>` that is the chain's value when every step fits a word and `None` the moment one does not (a `/` or
2353/// `%` by zero included) — and `exact`, the chain's exact `LogosInt` over the same names, for the branch `None` takes.
2354pub(crate) struct CheckedChain {
2355    pub(crate) binds: String,
2356    pub(crate) checked: String,
2357    pub(crate) exact: String,
2358}
2359
2360fn checked_chain_parts<'e>(e: &'e Expr<'e>, ecx: &ExprCtx, prefix: &str) -> Option<CheckedChain> {
2361    fn emit(e: &Expr, names: &HashMap<usize, String>) -> String {
2362        match e {
2363            Expr::Literal(Literal::Number(n)) => format!("({n}i64)"),
2364            Expr::BinaryOp { op, left, right } if is_exact_arith_node(e) => {
2365                let step = match op {
2366                    BinaryOpKind::Add => "checked_add",
2367                    BinaryOpKind::Subtract => "checked_sub",
2368                    BinaryOpKind::Multiply => "checked_mul",
2369                    BinaryOpKind::Divide => "checked_div",
2370                    _ => "checked_rem",
2371                };
2372                format!("{}.{step}({})?", emit(left, names), emit(right, names))
2373            }
2374            _ => names[&dual_leaf_key(e)].clone(),
2375        }
2376    }
2377    if !is_exact_arith_node(e) {
2378        return None;
2379    }
2380    let (leaves, exprs) = chain_leaves(&[e], ecx)?;
2381    if leaves.len() > 6 {
2382        return None;
2383    }
2384    let (binds, names) = bind_chain_leaves(&leaves, &exprs, ecx, prefix);
2385    Some(CheckedChain {
2386        binds,
2387        checked: format!("(|| -> Option<i64> {{ Some({}) }})()", emit(e, &names)),
2388        exact: emit_chain_with_bound_leaves(e, &names, false),
2389    })
2390}
2391
2392/// A bit operation (`&`, `|`, `^`, `<<`, `>>`) over an Int operand the Oracle cannot keep within a machine word — an
2393/// exactable chain like `0 - available` — on machine words: each such operand computed as a [`CheckedChain`], the raw
2394/// operation when every step fit a word, and otherwise the exact form (`logos_band_exact` with the operand's exact
2395/// value, or `logos_word_operand`'s refusal of a big integer), out of line in `logos_cold_path` so its big-integer code
2396/// stays out of the hot function. One overflow check per step, exact at the very edge of the word. A plain operand
2397/// evaluated anywhere but first is bound before the chains' leaves, so evaluation stays left to right. Value- and
2398/// refusal-identical to the exact form; `None` when an operand that may promote is not such a chain (a promoted
2399/// binding, a call returning a big integer), which keeps the exact form.
2400fn try_guarded_bitwise<'e>(
2401    op: BinaryOpKind,
2402    op_str: &str,
2403    left: &'e Expr<'e>,
2404    right: &'e Expr<'e>,
2405    ecx: &ExprCtx,
2406    promotes: impl Fn(&Expr) -> bool,
2407) -> Option<String> {
2408    let plain = ExprCtx {
2409        int_exact_tolerant: false,
2410        ..*ecx
2411    };
2412    let mut binds = String::new();
2413    let mut checked = Vec::new();
2414    let mut words = Vec::new();
2415    let mut slow = Vec::new();
2416    for (side, e) in [("l", left), ("r", right)] {
2417        if promotes(e) {
2418            if mentions_bigint_var(e, ecx.variable_types) {
2419                return None;
2420            }
2421            let chain = checked_chain_parts(e, ecx, &format!("__bw{side}"))?;
2422            binds.push_str(&chain.binds);
2423            let word = format!("__bw{side}v");
2424            checked.push((word.clone(), chain.checked));
2425            words.push(word);
2426            slow.push(Some(chain.exact));
2427        } else {
2428            let code = codegen_expr_ctx(e, &plain);
2429            if let Expr::Literal(Literal::Number(n)) = e {
2430                words.push(format!("{n}i64"));
2431            } else if matches!(e, Expr::Identifier(_)) {
2432                words.push(code);
2433            } else {
2434                let name = format!("__bw{side}");
2435                binds.push_str(&format!("let {name}: i64 = {code}; "));
2436                words.push(name);
2437            }
2438            slow.push(None);
2439        }
2440    }
2441    let operand = |k: usize| -> String {
2442        match &slow[k] {
2443            Some(exact) if matches!(op, BinaryOpKind::BitAnd) => exact.clone(),
2444            Some(exact) => {
2445                let refusal = match op {
2446                    BinaryOpKind::BitOr => "BITOR_OPERANDS",
2447                    BinaryOpKind::BitXor => "BITXOR_OPERANDS",
2448                    BinaryOpKind::Shl => "SHL_OPERANDS",
2449                    _ => "SHR_OPERANDS",
2450                };
2451                format!("logos_word_operand({exact}, logicaffeine_data::failure::{refusal})")
2452            }
2453            None => words[k].clone(),
2454        }
2455    };
2456    let exact = if matches!(op, BinaryOpKind::BitAnd) {
2457        format!("logos_band_exact({}, {})", operand(0), operand(1))
2458    } else {
2459        format!("({} {op_str} {})", operand(0), operand(1))
2460    };
2461    let (scrutinee, pattern) = match checked.as_slice() {
2462        [(word, value)] => (value.clone(), format!("Some({word})")),
2463        _ => (
2464            format!("({})", checked.iter().map(|(_, v)| v.as_str()).collect::<Vec<_>>().join(", ")),
2465            format!(
2466                "({})",
2467                checked.iter().map(|(w, _)| format!("Some({w})")).collect::<Vec<_>>().join(", ")
2468            ),
2469        ),
2470    };
2471    Some(format!(
2472        "{{ {binds}match {scrutinee} {{ {pattern} => ({} {op_str} {}), _ => logos_cold_path(move || {exact}) }} }}",
2473        words[0], words[1]
2474    ))
2475}
2476
2477/// The guarded dual of [`try_guarded_dual_chain`], in its parts: the leaf bindings (named `prefix` and the leaf's
2478/// number, so two duals in one block keep their own), the guard over the leaves the Oracle does not bound (`None` when
2479/// it bounds them all, so the raw chain always holds), the raw chain the guard proves within a machine word, and the
2480/// exact chain (a `LogosInt`, not narrowed) that runs otherwise.
2481pub(crate) struct GuardedDual {
2482    pub(crate) binds: String,
2483    pub(crate) guard: Option<String>,
2484    pub(crate) fast: String,
2485    pub(crate) slow: String,
2486}
2487
2488/// The leaves of an exact Int chain over `roots`, in evaluation order and once each (a name by its symbol, any other
2489/// leaf by its node — [`dual_leaf_key`]): `None` when the chain mentions a promoted binding or a leaf that is not a
2490/// machine-word Int.
2491fn chain_leaves<'e>(
2492    roots: &[&'e Expr<'e>],
2493    ecx: &ExprCtx,
2494) -> Option<(Vec<usize>, Vec<&'e Expr<'e>>)> {
2495    fn walk<'e>(
2496        e: &'e Expr<'e>,
2497        ecx: &ExprCtx,
2498        addrs: &mut Vec<usize>,
2499        exprs: &mut Vec<&'e Expr<'e>>,
2500        seen: &mut std::collections::HashSet<usize>,
2501    ) -> Option<()> {
2502        if mentions_bigint_var(e, ecx.variable_types) {
2503            return None;
2504        }
2505        match e {
2506            Expr::Literal(Literal::Number(_)) => Some(()),
2507            Expr::BinaryOp { left, right, .. } if is_exact_arith_node(e) => {
2508                walk(left, ecx, addrs, exprs, seen)?;
2509                walk(right, ecx, addrs, exprs, seen)
2510            }
2511            _ => {
2512                if infer_numeric_type(e, ecx.interner, ecx.variable_types) != "i64" {
2513                    return None;
2514                }
2515                // A bare identifier is pure — no binding needed, and every
2516                // occurrence shares one guard term (dedupe by symbol via the
2517                // seen-key). Anything else binds once per node.
2518                let addr = dual_leaf_key(e);
2519                if seen.insert(addr) {
2520                    addrs.push(addr);
2521                    exprs.push(e);
2522                }
2523                Some(())
2524            }
2525        }
2526    }
2527    let mut leaves = Vec::new();
2528    let mut seen = std::collections::HashSet::new();
2529    let mut exprs = Vec::new();
2530    for root in roots {
2531        walk(root, ecx, &mut leaves, &mut exprs, &mut seen)?;
2532    }
2533    Some((leaves, exprs))
2534}
2535
2536/// Bind each leaf of a chain that is not a bare name once, as `prefix` and its number, in evaluation order and typed
2537/// as the machine word every leaf is (a `1 << k` leaf is otherwise an `{integer}` no checked method can be called
2538/// on): the bindings, and the name every leaf is emitted by.
2539fn bind_chain_leaves(
2540    leaves: &[usize],
2541    exprs: &[&Expr],
2542    ecx: &ExprCtx,
2543    prefix: &str,
2544) -> (String, HashMap<usize, String>) {
2545    let plain = ExprCtx {
2546        int_exact_tolerant: false,
2547        ..*ecx
2548    };
2549    let mut names: HashMap<usize, String> = HashMap::new();
2550    let mut binds = String::new();
2551    for (k, (addr, le)) in leaves.iter().zip(exprs.iter()).enumerate() {
2552        // A bare identifier needs no binding — its emitted name is pure and
2553        // the guard/chain reference it directly (one guard term per SYMBOL).
2554        if matches!(le, Expr::Identifier(_)) {
2555            names.insert(*addr, codegen_expr_ctx(le, &plain));
2556            continue;
2557        }
2558        let name = format!("{prefix}{k}");
2559        binds.push_str(&format!(
2560            "let {}: i64 = {}; ",
2561            name,
2562            codegen_expr_ctx(le, &plain)
2563        ));
2564        names.insert(*addr, name);
2565    }
2566    (binds, names)
2567}
2568
2569fn guarded_dual_parts<'e>(
2570    op: BinaryOpKind,
2571    left: &'e Expr<'e>,
2572    right: &'e Expr<'e>,
2573    whole_ecx: &ExprCtx,
2574    prefix: &str,
2575) -> Option<GuardedDual> {
2576    let (leaves, leaf_exprs) = chain_leaves(&[left, right], whole_ecx)?;
2577    if leaves.is_empty() || leaves.len() > 6 {
2578        return None;
2579    }
2580    // A leaf the Oracle bounds costs its own magnitude and needs no guard term.
2581    let proven: HashMap<usize, u128> = leaves
2582        .iter()
2583        .zip(leaf_exprs.iter())
2584        .filter_map(|(addr, le)| {
2585            let (lo, hi) = whole_ecx.oracle?.expr_int_range(le)?;
2586            Some((*addr, lo.unsigned_abs().max(hi.unsigned_abs()) as u128))
2587        })
2588        .collect();
2589    // Solve for the largest power-of-two leaf bound that keeps the chain in
2590    // i64 (descending scan; the chain magnitude is monotone in the bound).
2591    let root_mag = |b: u128| -> Option<u128> {
2592        let l = chain_magnitude_with_leaf_bound(left, b, &proven)?;
2593        let r = chain_magnitude_with_leaf_bound(right, b, &proven)?;
2594        match op {
2595            BinaryOpKind::Add | BinaryOpKind::Subtract => l.checked_add(r),
2596            BinaryOpKind::Multiply => l.checked_mul(r),
2597            BinaryOpKind::Divide => Some(l),
2598            BinaryOpKind::Modulo => Some(r.min(l)),
2599            _ => None,
2600        }
2601    };
2602    let mut bound: u128 = 0;
2603    for exp in (16..=62).rev() {
2604        let b = 1u128 << exp;
2605        if root_mag(b).is_some_and(|m| m <= i64::MAX as u128) {
2606            bound = b;
2607            break;
2608        }
2609    }
2610    if bound == 0 {
2611        return None;
2612    }
2613    let (binds, names) = bind_chain_leaves(&leaves, &leaf_exprs, whole_ecx, prefix);
2614    // Guard terms in LEAF ORDER (the deduped evaluation order) — HashMap
2615    // iteration would make the emitted text nondeterministic across compiles.
2616    // A leaf the oracle proves non-negative (whatever its ceiling) needs only
2617    // the UPPER bound: its `>= -bound` term is vacuous, so we drop it. This halves the per-iteration
2618    // guard on hot multiply chains whose operand is an inductive `>= 0` (e.g.
2619    // collatz's `3*k+1`, where `k`'s loop range fixes to `[0, ∞)`).
2620    let terms = leaves
2621        .iter()
2622        .zip(leaf_exprs.iter())
2623        .filter(|(addr, _)| !proven.contains_key(addr))
2624        .map(|(addr, le)| {
2625            let n = &names[addr];
2626            let b = bound as i64;
2627            let nonneg = whole_ecx.oracle.is_some_and(|o| o.expr_proven_nonneg(le));
2628            if nonneg {
2629                format!("({n} <= {b}i64)")
2630            } else {
2631                format!("({n} >= -{b}i64 && {n} <= {b}i64)")
2632            }
2633        })
2634        .collect::<Vec<_>>();
2635    let guard = (!terms.is_empty()).then(|| terms.join(" && "));
2636    let root = |raw: bool| -> String {
2637        let l = emit_chain_with_bound_leaves(left, &names, raw);
2638        let r = emit_chain_with_bound_leaves(right, &names, raw);
2639        let nonzero_lit = matches!(right, Expr::Literal(Literal::Number(d)) if *d != 0);
2640        if raw {
2641            match op {
2642                BinaryOpKind::Add => format!("({} + {})", l, r),
2643                BinaryOpKind::Subtract => format!("({} - {})", l, r),
2644                BinaryOpKind::Multiply => format!("({} * {})", l, r),
2645                BinaryOpKind::Divide if nonzero_lit => format!("({} / {})", l, r),
2646                BinaryOpKind::Divide => format!("logos_div_i64({}, {})", l, r),
2647                BinaryOpKind::Modulo if nonzero_lit => {
2648                    let Expr::Literal(Literal::Number(m)) = right else { unreachable!() };
2649                    raw_literal_rem(*m, codegen_oracle_range(left), &l, &r, "i64")
2650                }
2651                BinaryOpKind::Modulo => format!("logos_rem_i64({}, {})", l, r),
2652                _ => unreachable!(),
2653            }
2654        } else {
2655            let helper = match op {
2656                BinaryOpKind::Add => "logos_add_exact",
2657                BinaryOpKind::Subtract => "logos_sub_exact",
2658                BinaryOpKind::Multiply => "logos_mul_exact",
2659                BinaryOpKind::Divide => "logos_div_exact",
2660                BinaryOpKind::Modulo => "logos_rem_exact",
2661                _ => unreachable!(),
2662            };
2663            format!("{}({}, {})", helper, l, r)
2664        }
2665    };
2666    Some(GuardedDual {
2667        fast: root(true),
2668        slow: root(false),
2669        binds,
2670        guard,
2671    })
2672}
2673
2674/// One arm of a two-armed assignment (`If c: Set x to a. Otherwise: Set x to b.`) as a machine word computed ahead
2675/// of the choice: the guard under which `fast` is the arm's exact value, `None` when it always is.
2676pub(crate) struct SelectArm {
2677    pub(crate) guard: Option<String>,
2678    pub(crate) fast: String,
2679}
2680
2681/// `value` as a [`SelectArm`] (`Opt::BranchlessSelect`), when computing it on a pass that does not choose it is
2682/// harmless: its syntax cannot trap (integer names and literals under `+ - * & | ^`, and `/` or `%` by a literal that
2683/// neither divides by zero nor overflows), and its machine-word form is either raw ([`emits_pure_i64`]) or the fast
2684/// side of a [`GuardedDual`] whose leaves are names, so nothing is evaluated but the arithmetic.
2685pub(crate) fn select_arm<'a, 'e>(
2686    value: &'e Expr<'e>,
2687    interner: &'a Interner,
2688    synced_vars: &'a HashSet<Symbol>,
2689    async_functions: &'a HashSet<Symbol>,
2690    variable_types: &'a HashMap<Symbol, String>,
2691    oracle: Option<&'a crate::optimize::OracleFacts>,
2692) -> Option<SelectArm> {
2693    let ecx = ExprCtx {
2694        async_functions,
2695        variable_types,
2696        oracle,
2697        int_exact_tolerant: false,
2698        ..ExprCtx::bare(interner, synced_vars)
2699    };
2700    fn speculable(e: &Expr, ecx: &ExprCtx) -> bool {
2701        match e {
2702            Expr::Literal(Literal::Number(_)) => true,
2703            Expr::Identifier(_) => {
2704                !mentions_bigint_var(e, ecx.variable_types)
2705                    && infer_numeric_type(e, ecx.interner, ecx.variable_types) == "i64"
2706            }
2707            Expr::BinaryOp { op, left, right } => match op {
2708                BinaryOpKind::Add
2709                | BinaryOpKind::Subtract
2710                | BinaryOpKind::Multiply
2711                | BinaryOpKind::BitAnd
2712                | BinaryOpKind::BitOr
2713                | BinaryOpKind::BitXor => speculable(left, ecx) && speculable(right, ecx),
2714                BinaryOpKind::Divide => {
2715                    matches!(&**right, Expr::Literal(Literal::Number(d)) if *d != 0 && *d != -1)
2716                        && speculable(left, ecx)
2717                }
2718                BinaryOpKind::Modulo => {
2719                    matches!(&**right, Expr::Literal(Literal::Number(d)) if *d != 0)
2720                        && speculable(left, ecx)
2721                }
2722                _ => false,
2723            },
2724            _ => false,
2725        }
2726    }
2727    if !speculable(value, &ecx) {
2728        return None;
2729    }
2730    if emits_pure_i64(value, &ecx) {
2731        return Some(SelectArm {
2732            guard: None,
2733            fast: codegen_expr_ctx(value, &ecx),
2734        });
2735    }
2736    let Expr::BinaryOp { op, left, right } = value else {
2737        return None;
2738    };
2739    if !is_exact_arith_node(value) {
2740        return None;
2741    }
2742    let dual = guarded_dual_parts(*op, left, right, &ecx, "__chain_l")?;
2743    if !dual.binds.is_empty() {
2744        return None;
2745    }
2746    Some(SelectArm {
2747        guard: dual.guard,
2748        fast: dual.fast,
2749    })
2750}
2751
2752fn oracle_proves_index(ecx: &ExprCtx, collection: &Expr, index: &Expr) -> bool {
2753    if !crate::optimize::active_config().is_on(crate::optimization::Opt::Unchecked) {
2754        return false;
2755    }
2756    let proven = ecx
2757        .oracle
2758        .map_or(false, |o| o.index_provably_in_bounds(collection, index));
2759    if proven {
2760        crate::optimize::mark_fired(crate::optimization::Opt::Unchecked);
2761    }
2762    proven
2763}
2764
2765/// The emitted bounds of `start to end`. Two type-silent bounds leave the counter's width to rustc's `i32`
2766/// default, so the end states `i64`.
2767pub(crate) fn range_bound_strs(
2768    start: &Expr,
2769    end: &Expr,
2770    emit: impl Fn(&Expr) -> String,
2771) -> (String, String) {
2772    let start_str = emit(start);
2773    let end_str = match super::types::type_silent_int(start) {
2774        Some(_) => super::types::type_silent_int_i64(end).unwrap_or_else(|| emit(end)),
2775        None => emit(end),
2776    };
2777    (start_str, end_str)
2778}
2779
2780/// The Rust range a counted `Repeat for c from start to end` walks. The half-open `start..end + 1` is the
2781/// form LLVM optimizes (an inclusive `RangeInclusive` carries its exhausted flag through every iteration),
2782/// and it is exact wherever `end + 1` exists: a constant `end` below `i64::MAX`, or an `end` the range oracle
2783/// bounds below it. Any other `end` keeps the inclusive range, which reaches `i64::MAX` itself.
2784pub(crate) fn counted_loop_range(
2785    start: &Expr,
2786    end: &Expr,
2787    start_str: &str,
2788    end_str: &str,
2789    oracle: Option<&crate::optimize::OracleFacts>,
2790) -> String {
2791    if let Some(last) = super::types::type_silent_int(end) {
2792        return match last.checked_add(1) {
2793            Some(past) if super::types::type_silent_int(start).is_some() => {
2794                format!("({start_str}..{past}_i64)")
2795            }
2796            Some(past) => format!("({start_str}..{past})"),
2797            None => format!("({start_str}..={end_str})"),
2798        };
2799    }
2800    if oracle
2801        .and_then(|o| o.expr_int_range(end))
2802        .is_some_and(|(_, hi)| hi < i64::MAX)
2803    {
2804        return format!("({start_str}..({end_str} + 1))");
2805    }
2806    format!("({start_str}..={end_str})")
2807}
2808
2809/// Record, in this compile's facts ([`crate::optimize::facts`]), that the access whose index is `index` names
2810/// an item wherever it is evaluated; the construct calling this is what proves it. Outside a compile's facts
2811/// scope nothing is recorded and the access stays checked.
2812pub(crate) fn mark_index_in_range(index: &Expr) {
2813    crate::optimize::facts::mark_expr(crate::optimize::facts::Fact::InBounds, index);
2814}
2815
2816/// Whether `item index of collection` names an item on every run, by this compile's range oracle
2817/// ([`crate::optimize::OracleFacts::index_always_in_bounds`]). A plain indexed access there never meets its
2818/// own bounds check.
2819pub(crate) fn range_proves_index(collection: &Expr, index: &Expr) -> bool {
2820    RANGE_ORACLE.with(|r| {
2821        r.borrow()
2822            .as_deref()
2823            .is_some_and(|o| o.index_always_in_bounds(collection, index))
2824    })
2825}
2826
2827/// Whether the 1-based `index` is at least 1 wherever it is evaluated, so the item it names, if any, counts from the
2828/// front and [`LogosItems::logos_item_front`](logicaffeine_data::LogosItems::logos_item_front) holds the whole
2829/// index rule: a literal of at least 1, a non-negative value plus a literal of at least 1, or an index the range
2830/// oracle bounds below by 1. The plain accessor's path for an index counted from the back is a second way to an
2831/// item, which keeps a proven-in-range loop from compiling to plain loads.
2832pub(crate) fn counts_from_the_front(
2833    index: &Expr,
2834    oracle: Option<&crate::optimize::OracleFacts>,
2835) -> bool {
2836    let at_least_one = |e: &Expr| matches!(e, Expr::Literal(Literal::Number(n)) if *n >= 1);
2837    match index {
2838        Expr::Literal(Literal::Number(n)) => return *n >= 1,
2839        Expr::BinaryOp {
2840            op: BinaryOpKind::Add,
2841            left,
2842            right,
2843        } if (at_least_one(right) && is_nonneg_expr(left))
2844            || (at_least_one(left) && is_nonneg_expr(right)) =>
2845        {
2846            return true
2847        }
2848        _ => {}
2849    }
2850    let proven = |o: &crate::optimize::OracleFacts| o.expr_proven_at_least(index, 1);
2851    oracle.is_some_and(proven) || RANGE_ORACLE.with(|r| r.borrow().as_deref().is_some_and(proven))
2852}
2853
2854/// The accessor an emitted `item index of …` goes through: [`counts_from_the_front`]'s, or the whole index rule.
2855pub(crate) fn item_accessor(
2856    index: &Expr,
2857    oracle: Option<&crate::optimize::OracleFacts>,
2858    write: bool,
2859) -> &'static str {
2860    match (counts_from_the_front(index, oracle), write) {
2861        (true, false) => "logos_item_front",
2862        (true, true) => "logos_item_front_mut",
2863        (false, false) => "logos_item",
2864        (false, true) => "logos_item_mut",
2865    }
2866}
2867
2868/// The read of `item index of collection` from `owner` (the collection's Rust place): unchecked where the
2869/// statement licensed the oracle and it proves the index in range, a plain indexed load where the range oracle
2870/// proves it (the load's own check never fires), and through the one index rule otherwise. `copy` reads the
2871/// element by value; any other element is cloned.
2872fn indexed_read(owner: &str, collection: &Expr, index: &Expr, copy: bool, ecx: &ExprCtx) -> String {
2873    let (variable_types, interner) = (ecx.variable_types, ecx.interner);
2874    let (place, by_ref) = if oracle_proves_index(ecx, collection, index) {
2875        let offset = proven_offset_str(index, ecx, variable_types, interner);
2876        return if copy {
2877            format!("unsafe {{ *{}.get_unchecked({}) }}", owner, offset)
2878        } else {
2879            format!("unsafe {{ {}.get_unchecked({}).clone() }}", owner, offset)
2880        };
2881    } else if range_proves_index(collection, index) {
2882        (
2883            format!(
2884                "{}[{}]",
2885                owner,
2886                proven_offset_str(index, ecx, variable_types, interner)
2887            ),
2888            false,
2889        )
2890    } else {
2891        (
2892            format!(
2893                "{}.{}({})",
2894                owner,
2895                item_accessor(index, ecx.oracle, false),
2896                logos_index_str(index, ecx, variable_types, interner)
2897            ),
2898            true,
2899        )
2900    };
2901    match (copy, by_ref) {
2902        (true, true) => format!("(*{})", place),
2903        (true, false) => place,
2904        (false, _) => format!("{}.clone()", place),
2905    }
2906}
2907
2908/// [`codegen_expr_with_async`] plus the bounds-elision oracle, so proven indexed
2909/// reads in the lowered expression become `get_unchecked`. Used by the `If`-cond
2910/// statement arm.
2911pub(crate) fn codegen_expr_with_async_oracle<'a>(
2912    expr: &Expr,
2913    interner: &'a Interner,
2914    synced_vars: &'a HashSet<Symbol>,
2915    async_functions: &'a HashSet<Symbol>,
2916    variable_types: &'a HashMap<Symbol, String>,
2917    oracle: Option<&'a crate::optimize::OracleFacts>,
2918) -> String {
2919    codegen_expr_ctx(
2920        expr,
2921        &ExprCtx {
2922            async_functions,
2923            variable_types,
2924            oracle,
2925            ..ExprCtx::bare(interner, synced_vars)
2926        },
2927    )
2928}
2929
2930/// [`codegen_expr_boxed_with_types`] plus the bounds-elision oracle, so proven
2931/// indexed reads in the lowered expression become `get_unchecked`. Used by the
2932/// `Let`/`Set`/`SetIndex` value statement arms.
2933#[allow(clippy::too_many_arguments)]
2934pub(crate) fn codegen_expr_boxed_with_types_oracle<'a>(
2935    expr: &Expr,
2936    interner: &'a Interner,
2937    synced_vars: &'a HashSet<Symbol>,
2938    boxed_fields: &'a HashSet<(String, String, String)>,
2939    registry: &'a TypeRegistry,
2940    async_functions: &'a HashSet<Symbol>,
2941    string_vars: &'a HashSet<Symbol>,
2942    variable_types: &'a HashMap<Symbol, String>,
2943    fast_div: &'a HashMap<Symbol, String>,
2944    oracle: Option<&'a crate::optimize::OracleFacts>,
2945) -> String {
2946    codegen_expr_ctx(
2947        expr,
2948        &ExprCtx {
2949            boxed_fields,
2950            registry,
2951            async_functions,
2952            string_vars,
2953            variable_types,
2954            fast_div,
2955            oracle,
2956            ..ExprCtx::bare(interner, synced_vars)
2957        },
2958    )
2959}
2960
2961/// Like [`codegen_expr_boxed_with_types_oracle`] but TOLERANT of overflow: the
2962/// root exact-arithmetic result stays a `LogosInt` (no `.expect_i64` narrow).
2963/// Used for the RHS of a binding whose target is stored as `LogosInt`.
2964#[allow(clippy::too_many_arguments)]
2965pub(crate) fn codegen_expr_boxed_with_types_oracle_tolerant<'a>(
2966    expr: &Expr,
2967    interner: &'a Interner,
2968    synced_vars: &'a HashSet<Symbol>,
2969    boxed_fields: &'a HashSet<(String, String, String)>,
2970    registry: &'a TypeRegistry,
2971    async_functions: &'a HashSet<Symbol>,
2972    string_vars: &'a HashSet<Symbol>,
2973    variable_types: &'a HashMap<Symbol, String>,
2974    fast_div: &'a HashMap<Symbol, String>,
2975    oracle: Option<&'a crate::optimize::OracleFacts>,
2976) -> String {
2977    codegen_expr_ctx(
2978        expr,
2979        &ExprCtx {
2980            boxed_fields,
2981            registry,
2982            async_functions,
2983            string_vars,
2984            variable_types,
2985            fast_div,
2986            oracle,
2987            int_exact_tolerant: true,
2988            ..ExprCtx::bare(interner, synced_vars)
2989        },
2990    )
2991}
2992
2993pub fn codegen_expr(expr: &Expr, interner: &Interner, synced_vars: &HashSet<Symbol>) -> String {
2994    codegen_expr_ctx(expr, &ExprCtx::bare(interner, synced_vars))
2995}
2996
2997/// Phase 54+: Codegen expression with async function tracking.
2998/// Adds .await to async function calls at the expression level, handling nested calls.
2999pub(crate) fn codegen_expr_with_async(
3000    expr: &Expr,
3001    interner: &Interner,
3002    synced_vars: &HashSet<Symbol>,
3003    async_functions: &HashSet<Symbol>,
3004    variable_types: &HashMap<Symbol, String>,
3005) -> String {
3006    codegen_expr_ctx(
3007        expr,
3008        &ExprCtx {
3009            async_functions,
3010            variable_types,
3011            ..ExprCtx::bare(interner, synced_vars)
3012        },
3013    )
3014}
3015
3016/// Codegen expression with async support, string variable tracking, the loop-invariant libdivide
3017/// map (`fast_div`), and the type REGISTRY. Every caller is a `Show`/`Observe` sink whose object
3018/// may concatenate a struct FIELD read (`p's label + p's label`): the concat-fold decision
3019/// (`is_string_concat`, above) recognises a Text-typed field only through `record_field_rust_type`,
3020/// which needs the registry to resolve the field's owning struct — `ExprCtx::bare`'s empty
3021/// registry made every such field invisible to it, so a field-only concat fell through to a raw
3022/// `+`, and `String: Add<String>` wants `&str` on the right, so it did not build.
3023pub(crate) fn codegen_expr_with_async_and_strings(
3024    expr: &Expr,
3025    interner: &Interner,
3026    synced_vars: &HashSet<Symbol>,
3027    async_functions: &HashSet<Symbol>,
3028    string_vars: &HashSet<Symbol>,
3029    variable_types: &HashMap<Symbol, String>,
3030    fast_div: &HashMap<Symbol, String>,
3031    registry: &TypeRegistry,
3032) -> String {
3033    codegen_expr_ctx(
3034        expr,
3035        &ExprCtx {
3036            async_functions,
3037            string_vars,
3038            variable_types,
3039            fast_div,
3040            registry,
3041            // Every caller is a `Show` sink (plain object or an interpolated
3042            // part): a display accepts the promoting `LogosInt`, so overflow
3043            // prints the EXACT value instead of narrowing.
3044            int_exact_tolerant: true,
3045            ..ExprCtx::bare(interner, synced_vars)
3046        },
3047    )
3048}
3049
3050/// Check if an expression is definitely a string (needs format! for concatenation).
3051/// Takes a set of known string variable symbols for identifier lookup.
3052pub(crate) fn is_definitely_string_expr_with_vars(
3053    expr: &Expr,
3054    string_vars: &HashSet<Symbol>,
3055) -> bool {
3056    match expr {
3057        // String literals are definitely strings
3058        Expr::Literal(Literal::Text(_)) => true,
3059        // Variables known to be strings
3060        Expr::Identifier(sym) => string_vars.contains(sym),
3061        // Concat always produces strings
3062        Expr::BinaryOp {
3063            op: BinaryOpKind::Concat,
3064            ..
3065        } => true,
3066        // Add with a string operand produces a string
3067        Expr::BinaryOp {
3068            op: BinaryOpKind::Add,
3069            left,
3070            right,
3071        } => {
3072            is_definitely_string_expr_with_vars(left, string_vars)
3073                || is_definitely_string_expr_with_vars(right, string_vars)
3074        }
3075        // WithCapacity wrapping a string value is a string
3076        Expr::WithCapacity { value, .. } => is_definitely_string_expr_with_vars(value, string_vars),
3077        // Interpolated strings always produce strings
3078        Expr::InterpolatedString(_) => true,
3079        // A call to a Text-returning function is a string operand, exactly like a Text-typed
3080        // field read (below) — the callee's OWN declared return type, not the argument shapes.
3081        Expr::Call { function, .. } => fn_call_returns_text(*function),
3082        _ => false,
3083    }
3084}
3085
3086/// True when the expression is definitely a SEQUENCE — a list literal, a
3087/// Seq-typed variable, a slice, a concat/repeat result, or a fill. Drives the
3088/// `+` (concat) and `*` (repeat) operator overloads onto the sequence
3089/// emissions instead of the numeric ones.
3090fn is_definitely_seq_expr(
3091    expr: &Expr,
3092    variable_types: &HashMap<Symbol, String>,
3093    interner: &Interner,
3094) -> bool {
3095    match expr {
3096        Expr::List(_) | Expr::Slice { .. } => true,
3097        Expr::Identifier(sym) => variable_types
3098            .get(sym)
3099            .map(|t| {
3100                let t = t.split("|__hl:").next().unwrap_or(t.as_str());
3101                t.starts_with("LogosSeq") || t.starts_with("Vec<") || t.starts_with("&[")
3102            })
3103            .unwrap_or(false),
3104        Expr::BinaryOp {
3105            op: BinaryOpKind::SeqConcat,
3106            ..
3107        } => true,
3108        Expr::BinaryOp {
3109            op: BinaryOpKind::Add | BinaryOpKind::Multiply,
3110            left,
3111            right,
3112        } => {
3113            is_definitely_seq_expr(left, variable_types, interner)
3114                || is_definitely_seq_expr(right, variable_types, interner)
3115        }
3116        Expr::Call { function, .. } => interner.resolve(*function) == "repeatSeq",
3117        Expr::New { type_name, .. } => interner.resolve(*type_name) == "Seq",
3118        _ => false,
3119    }
3120}
3121
3122/// Collect leaf operands from a chain of string Add/Concat operations.
3123///
3124/// Walks left-leaning trees of `+` (on strings) and `Concat` operations,
3125/// collecting all leaf expressions into a flat Vec. This enables emitting
3126/// a single `format!("{}{}{}", a, b, c)` instead of nested
3127/// `format!("{}{}", format!("{}{}", a, b), c)`, avoiding O(n^2) allocation.
3128/// [`collect_string_concat_operands`] with the "is this a string operand?" test supplied by the
3129/// caller, so the DECISION to fold into a `format!` and the FLATTENING of its operands ask exactly
3130/// the same question. When they disagreed, a chain whose stringness was only visible to the
3131/// decision was pushed back through the ordinary `+` emission it was folded to avoid.
3132pub(crate) fn collect_string_concat_operands_with<'a, 'b>(
3133    expr: &'b Expr<'a>,
3134    is_string: &dyn Fn(&Expr<'a>) -> bool,
3135    operands: &mut Vec<&'b Expr<'a>>,
3136) {
3137    match expr {
3138        Expr::BinaryOp {
3139            op: BinaryOpKind::Concat,
3140            left,
3141            right,
3142        } => {
3143            collect_string_concat_operands_with(left, is_string, operands);
3144            collect_string_concat_operands_with(right, is_string, operands);
3145        }
3146        Expr::BinaryOp {
3147            op: BinaryOpKind::Add,
3148            left,
3149            right,
3150        } if is_string(left) || is_string(right) => {
3151            collect_string_concat_operands_with(left, is_string, operands);
3152            collect_string_concat_operands_with(right, is_string, operands);
3153        }
3154        _ => operands.push(expr),
3155    }
3156}
3157
3158pub(crate) fn collect_string_concat_operands<'a, 'b>(
3159    expr: &'b Expr<'a>,
3160    string_vars: &HashSet<Symbol>,
3161    operands: &mut Vec<&'b Expr<'a>>,
3162) {
3163    match expr {
3164        Expr::BinaryOp {
3165            op: BinaryOpKind::Concat,
3166            left,
3167            right,
3168        } => {
3169            collect_string_concat_operands(left, string_vars, operands);
3170            collect_string_concat_operands(right, string_vars, operands);
3171        }
3172        Expr::BinaryOp {
3173            op: BinaryOpKind::Add,
3174            left,
3175            right,
3176        } => {
3177            let has_string = is_definitely_string_expr_with_vars(left, string_vars)
3178                || is_definitely_string_expr_with_vars(right, string_vars);
3179            if has_string {
3180                collect_string_concat_operands(left, string_vars, operands);
3181                collect_string_concat_operands(right, string_vars, operands);
3182            } else {
3183                operands.push(expr);
3184            }
3185        }
3186        _ => {
3187            operands.push(expr);
3188        }
3189    }
3190}
3191
3192/// Codegen with variable type tracking for direct collection indexing
3193/// optimization, plus the loop-invariant libdivide map (`fast_div`) so `% n` /
3194/// `/ n` sites can lower to a precomputed magic multiply.
3195pub(crate) fn codegen_expr_boxed_with_types(
3196    expr: &Expr,
3197    interner: &Interner,
3198    synced_vars: &HashSet<Symbol>,
3199    boxed_fields: &HashSet<(String, String, String)>,
3200    registry: &TypeRegistry,
3201    async_functions: &HashSet<Symbol>,
3202    string_vars: &HashSet<Symbol>,
3203    variable_types: &HashMap<Symbol, String>,
3204    fast_div: &HashMap<Symbol, String>,
3205) -> String {
3206    codegen_expr_ctx(
3207        expr,
3208        &ExprCtx {
3209            boxed_fields,
3210            registry,
3211            async_functions,
3212            string_vars,
3213            variable_types,
3214            fast_div,
3215            ..ExprCtx::bare(interner, synced_vars)
3216        },
3217    )
3218}
3219
3220/// The expression-lowering workhorse. Takes the whole [`ExprCtx`] and unpacks it
3221/// into the locals the match arms use, so the body reads exactly as it did when
3222/// these were eight positional parameters; recursion just forwards `ctx`.
3223/// Parse an `__affine_array:coeff:offset:trip` type tag into `(coeff, offset)`,
3224/// the constants of the deleted CSR array's closed form `A[p] = coeff*p+offset`.
3225fn affine_array_coeff_offset(ty: Option<&String>) -> Option<(i64, i64)> {
3226    let rest = ty?.strip_prefix("__affine_array:")?;
3227    let mut parts = rest.splitn(3, ':');
3228    let coeff: i64 = parts.next()?.parse().ok()?;
3229    let offset: i64 = parts.next()?.parse().ok()?;
3230    Some((coeff, offset))
3231}
3232
3233/// The trip-count Rust expression (the value of `length of A`) from the tag.
3234fn affine_array_trip(ty: Option<&String>) -> Option<String> {
3235    let rest = ty?.strip_prefix("__affine_array:")?;
3236    let mut parts = rest.splitn(3, ':');
3237    parts.next()?; // coeff
3238    parts.next()?; // offset
3239    Some(parts.next()?.to_string())
3240}
3241
3242/// Does `expr` evaluate to a `LogosRational` at runtime? True for an `ExactDivide`, for
3243/// `+ − ×` over a Rational operand, and for an identifier bound to a `LogosRational`.
3244/// Mirrors `resolve_division::Cx::is_rat_expr` at the codegen level so operand coercion
3245/// matches the resolve pass that produced the `ExactDivide` in the first place.
3246pub(super) fn is_rational_expr(expr: &Expr, variable_types: &HashMap<Symbol, String>) -> bool {
3247    match expr {
3248        Expr::BinaryOp {
3249            op: BinaryOpKind::ExactDivide,
3250            ..
3251        } => true,
3252        Expr::BinaryOp {
3253            op: BinaryOpKind::Add | BinaryOpKind::Subtract | BinaryOpKind::Multiply,
3254            left,
3255            right,
3256        } => is_rational_expr(left, variable_types) || is_rational_expr(right, variable_types),
3257        Expr::Identifier(sym) => variable_types
3258            .get(sym)
3259            .map_or(false, |t| t == "LogosRational"),
3260        _ => false,
3261    }
3262}
3263
3264/// A `LogosRational`-producing Rust string for an operand of exact arithmetic: a value
3265/// that is already Rational is used verbatim; an integer operand is wrapped as
3266/// `LogosRational::from_i64(..)` so the exact methods type-check.
3267fn rational_operand(expr: &Expr, code: &str, variable_types: &HashMap<Symbol, String>) -> String {
3268    if is_rational_expr(expr, variable_types) {
3269        code.to_string()
3270    } else {
3271        format!("LogosRational::from_i64(({}) as i64)", code)
3272    }
3273}
3274
3275/// The exact value type `expr` produces, if it produces one — most specific first: a float
3276/// complex, an exact complex, a decimal, a modular, a quantity, a money. The ONE answer a binding's
3277/// type and a sequence literal's element type both take, so neither can drift from the other.
3278pub(super) fn exact_value_type_of(
3279    expr: &Expr,
3280    variable_types: &HashMap<Symbol, String>,
3281    interner: &Interner,
3282) -> Option<&'static str> {
3283    if is_complexf_expr(expr, variable_types, interner) {
3284        Some("LogosComplexF")
3285    } else if is_complex_expr(expr, variable_types, interner) {
3286        Some("LogosComplex")
3287    } else if is_decimal_expr(expr, variable_types, interner) {
3288        Some("LogosDecimal")
3289    } else if is_modular_expr(expr, variable_types, interner) {
3290        Some("LogosModular")
3291    } else if is_quantity_expr(expr, variable_types, interner) {
3292        Some("LogosQuantity")
3293    } else if is_money_expr(expr, variable_types, interner) {
3294        Some("LogosMoney")
3295    } else {
3296        None
3297    }
3298}
3299
3300/// The Rust type a value expression evidently produces, read from its shape: an exact value, a
3301/// literal, a variable of a plain registered type, a record or variant of the program's being built,
3302/// a record field, a call to a program function, a list of such, or a tuple of such. `None` when the
3303/// shape does not say, or when the registered type is not the value's plain Rust type (a borrow, an
3304/// owned `Vec`, a hoisting or bignum annotation, a placeholder). The element type a tuple or list
3305/// literal records for its binding.
3306pub(super) fn value_rust_type(
3307    expr: &Expr,
3308    variable_types: &HashMap<Symbol, String>,
3309    registry: &TypeRegistry,
3310    interner: &Interner,
3311) -> Option<String> {
3312    if let Some(exact) = exact_value_type_of(expr, variable_types, interner) {
3313        return Some(exact.to_string());
3314    }
3315    let plain = |t: String| -> Option<String> {
3316        let placeholder = t
3317            .split(|c: char| matches!(c, '<' | '>' | ',' | ' '))
3318            .any(|p| p == "_");
3319        let annotated = t.contains('|') || t.starts_with('&') || t.starts_with("Vec<");
3320        (!t.is_empty() && !placeholder && !annotated).then_some(t)
3321    };
3322    let declared = |name: Symbol| -> Option<String> {
3323        let generic = match registry.get(name)? {
3324            crate::analysis::registry::TypeDef::Struct { generics, .. }
3325            | crate::analysis::registry::TypeDef::Enum { generics, .. } => !generics.is_empty(),
3326            _ => return None,
3327        };
3328        (!generic).then(|| rust_type_ident(interner.resolve(name)))
3329    };
3330    match expr {
3331        Expr::Literal(lit) => {
3332            plain(crate::analysis::types::LogosType::from_literal(lit).to_rust_type())
3333        }
3334        Expr::Identifier(sym) => plain(variable_types.get(sym)?.clone()),
3335        Expr::New {
3336            type_name,
3337            type_args,
3338            ..
3339        } if type_args.is_empty() => declared(*type_name),
3340        Expr::NewVariant { enum_name, .. } => declared(*enum_name),
3341        Expr::FieldAccess { .. } => plain(record_field_rust_type(
3342            expr,
3343            interner,
3344            variable_types,
3345            registry,
3346        )?),
3347        Expr::Call { function, .. } => {
3348            plain(FN_RETURN_TYPES.with(|c| c.borrow().get(function).cloned())?)
3349        }
3350        Expr::List(items) => {
3351            let held = super::rational::type_of(expr, super::rational::Typing { interner, variable_types, registry });
3352            if held.holds_rational() {
3353                return Some(held.to_rust_type());
3354            }
3355            Some(format!(
3356                "LogosSeq<{}>",
3357                value_rust_type(items.first()?, variable_types, registry, interner)?
3358            ))
3359        }
3360        Expr::Tuple(items) => {
3361            let elems = items
3362                .iter()
3363                .map(|i| value_rust_type(i, variable_types, registry, interner))
3364                .collect::<Option<Vec<_>>>()?;
3365            Some(super::types::tuple_rust_type(&elems))
3366        }
3367        _ => None,
3368    }
3369}
3370
3371/// One interpolation hole — the `format!` piece and the argument it formats — shared by the `Show`
3372/// statement and an interpolated-string expression, so a spec means one thing in both. A currency
3373/// (`$`) or precision (`.N`) hole renders through the runtime's `format_currency`/`format_fixed`,
3374/// which format each value type exactly as the interpreter's `apply_format_spec` does (an exact
3375/// decimal keeps its own digits rather than taking a lossy `f64` round trip). A plain hole renders
3376/// through `Showable`, like `Show`; an alignment or width spec is Rust's own.
3377pub(super) fn interpolation_hole(spec: Option<&str>, arg: &str) -> (String, String) {
3378    match spec {
3379        None => (
3380            "{}".to_string(),
3381            format!("logicaffeine_system::io::show_string(&({arg}))"),
3382        ),
3383        Some("$") => (
3384            "{}".to_string(),
3385            format!("logicaffeine_system::io::format_currency(&({arg}))"),
3386        ),
3387        Some(s) => match s.strip_prefix('.').and_then(|p| p.parse::<usize>().ok()) {
3388            Some(precision) => (
3389                "{}".to_string(),
3390                format!("logicaffeine_system::io::format_fixed(&({arg}), {precision})"),
3391            ),
3392            None => (format!("{{:{s}}}"), arg.to_string()),
3393        },
3394    }
3395}
3396
3397/// Does `expr` evaluate to a `LogosDecimal` at runtime? True for a `decimal(..)` call, for
3398/// `+ − ×` over a Decimal operand, and for an identifier bound to a `LogosDecimal`. Mirrors
3399/// `is_rational_expr` so operand coercion lines up with the inferred `Decimal` type.
3400pub(super) fn is_decimal_expr(
3401    expr: &Expr,
3402    variable_types: &HashMap<Symbol, String>,
3403    interner: &Interner,
3404) -> bool {
3405    match expr {
3406        Expr::Call { function, .. } => interner.resolve(*function) == "decimal",
3407        Expr::BinaryOp {
3408            op: BinaryOpKind::Add | BinaryOpKind::Subtract | BinaryOpKind::Multiply,
3409            left,
3410            right,
3411        } => {
3412            is_decimal_expr(left, variable_types, interner)
3413                || is_decimal_expr(right, variable_types, interner)
3414        }
3415        Expr::Identifier(sym) => variable_types
3416            .get(sym)
3417            .map_or(false, |t| t == "LogosDecimal"),
3418        _ => false,
3419    }
3420}
3421
3422/// A `LogosDecimal`-producing Rust string for an operand of exact decimal arithmetic: a
3423/// value that is already a Decimal is used verbatim; an integer operand is widened with
3424/// `LogosDecimal::from_i64(..)` so the exact methods type-check (`price * 3`).
3425fn decimal_operand(
3426    expr: &Expr,
3427    code: &str,
3428    variable_types: &HashMap<Symbol, String>,
3429    interner: &Interner,
3430) -> String {
3431    if is_decimal_expr(expr, variable_types, interner) {
3432        code.to_string()
3433    } else {
3434        format!("LogosDecimal::from_i64(({}) as i64)", code)
3435    }
3436}
3437
3438/// The Rust element type of `collection` when it is an identifier bound to a sequence — a
3439/// `LogosSeq<T>`, an owned `Vec<T>`, or a borrowed `&[T]` / `&mut [T]` / fixed `&[T; N]` param.
3440/// `&[LogosComplexF]` yields `Some("LogosComplexF")`. Used to type `item i of xs` so a
3441/// `Seq of ComplexF` element's `+ − × ÷` take the ComplexF method path (also across borrow params).
3442/// Whether an item read from a collection of Rust type `t` is emitted widened to `i64` (`(x as i64)`): a narrowed
3443/// `Vec<i32>`, an `i32` slice or fixed array, and a text's byte view. Such a read is an Int word wherever it appears.
3444pub(super) fn item_read_widens(t: &str) -> bool {
3445    let t = t.split("|__hl:").next().unwrap_or(t);
3446    if t == "TextBytes" || t == "Vec<i32>" {
3447        return true;
3448    }
3449    let body = t.strip_prefix("&mut ").or_else(|| t.strip_prefix('&')).unwrap_or(t);
3450    body.strip_prefix('[')
3451        .and_then(|s| s.strip_suffix(']'))
3452        .is_some_and(|inner| inner.split(';').next().unwrap_or(inner).trim() == "i32")
3453}
3454
3455pub(super) fn seq_element_rust_type<'a>(
3456    collection: &Expr,
3457    variable_types: &'a HashMap<Symbol, String>,
3458) -> Option<&'a str> {
3459    let Expr::Identifier(sym) = collection else {
3460        return None;
3461    };
3462    let t = variable_types.get(sym)?.as_str();
3463    if let Some(inner) = t
3464        .strip_prefix("LogosSeq<")
3465        .and_then(|s| s.strip_suffix('>'))
3466    {
3467        return Some(inner);
3468    }
3469    if let Some(inner) = t.strip_prefix("Vec<").and_then(|s| s.strip_suffix('>')) {
3470        return Some(inner);
3471    }
3472    // Borrowed slices: `&[T]`, `&mut [T]`, or a fixed `&[T; N]` (element is the part before `;`).
3473    let body = t
3474        .strip_prefix("&mut ")
3475        .or_else(|| t.strip_prefix('&'))
3476        .unwrap_or(t);
3477    if let Some(inner) = body.strip_prefix('[').and_then(|s| s.strip_suffix(']')) {
3478        return Some(inner.split(';').next().unwrap_or(inner).trim());
3479    }
3480    None
3481}
3482
3483/// The Rust VALUE type of `collection` when it is an identifier bound to a `LogosMap<K, V>` —
3484/// splits on the top-level comma (bracket-depth tracked) so a generic value type
3485/// (`LogosMap<String, LogosSeq<Int>>`) is not cut at an inner comma.
3486fn logos_map_value_rust_type<'a>(
3487    collection: &Expr,
3488    variable_types: &'a HashMap<Symbol, String>,
3489) -> Option<&'a str> {
3490    let Expr::Identifier(sym) = collection else {
3491        return None;
3492    };
3493    let t = variable_types.get(sym)?.as_str();
3494    let inner = t.strip_prefix("LogosMap<")?.strip_suffix('>')?;
3495    let mut depth = 0i32;
3496    for (i, ch) in inner.char_indices() {
3497        match ch {
3498            '<' => depth += 1,
3499            '>' => depth -= 1,
3500            ',' if depth == 0 => return Some(inner[i + 1..].trim()),
3501            _ => {}
3502        }
3503    }
3504    None
3505}
3506
3507/// True when `e` is a bare identifier whose DECLARED Rust type is `String` — a Text-typed
3508/// function PARAMETER is never entered into `string_vars` (only a `Let`-bound local is, at its
3509/// own binding site in `codegen_let_stmt`), so `is_definitely_string_expr_with_vars`'s
3510/// `string_vars`-only lookup cannot see one. `variable_types` is the parameter's own source of
3511/// truth: every parameter is registered there by name at codegen entry, `Text` mapping to
3512/// `"String"` the same way every other Text-typed binding does.
3513fn is_text_typed_identifier(e: &Expr, variable_types: &HashMap<Symbol, String>) -> bool {
3514    matches!(e, Expr::Identifier(sym)
3515        if variable_types.get(sym)
3516            .map(|t| t.split("|__hl:").next().unwrap_or(t))
3517            == Some("String"))
3518}
3519
3520/// True when `e` reads a `Seq of Text` or a `Map of _ to Text` by index (`item i of xs`, `item k
3521/// of m`) — a Text-typed element or value is a string operand exactly like a Text-typed field,
3522/// and for the same reason: only the DECLARED type tells an Int-valued index apart from a
3523/// Text-valued one, and `is_definitely_string_expr_with_vars` has no `Expr::Index` arm at all.
3524fn is_text_typed_index(e: &Expr, variable_types: &HashMap<Symbol, String>) -> bool {
3525    let Expr::Index { collection, .. } = e else {
3526        return false;
3527    };
3528    seq_element_rust_type(collection, variable_types) == Some("String")
3529        || logos_map_value_rust_type(collection, variable_types) == Some("String")
3530}
3531
3532/// Does `expr` evaluate to a `LogosComplex`? True for a `complex(..)` call, for `+ − × ÷`
3533/// over a Complex operand, and for an identifier bound to a `LogosComplex`.
3534pub(super) fn is_complex_expr(
3535    expr: &Expr,
3536    variable_types: &HashMap<Symbol, String>,
3537    interner: &Interner,
3538) -> bool {
3539    match expr {
3540        // `complex(a, b)` builds one; `conjugate(z)` of an exact complex stays exact.
3541        Expr::Call { function, args } => {
3542            let name = interner.resolve(*function);
3543            name == "complex"
3544                || (name == "conjugate"
3545                    && args.len() == 1
3546                    && is_complex_expr(args[0], variable_types, interner))
3547        }
3548        Expr::BinaryOp {
3549            op:
3550                BinaryOpKind::Add
3551                | BinaryOpKind::Subtract
3552                | BinaryOpKind::Multiply
3553                | BinaryOpKind::Divide,
3554            left,
3555            right,
3556        } => {
3557            is_complex_expr(left, variable_types, interner)
3558                || is_complex_expr(right, variable_types, interner)
3559        }
3560        // `item i of xs` where `xs : Seq of ComplexF-exact` (`LogosSeq<LogosComplex>`).
3561        Expr::Index { collection, .. } => {
3562            seq_element_rust_type(collection, variable_types) == Some("LogosComplex")
3563        }
3564        Expr::Identifier(sym) => variable_types
3565            .get(sym)
3566            .map_or(false, |t| t == "LogosComplex"),
3567        _ => false,
3568    }
3569}
3570
3571/// A `LogosComplex`-producing operand: a value already Complex is used verbatim; an integer
3572/// is embedded as `LogosComplex::from_i64(..)` (a real `re + 0i`).
3573fn complex_operand(
3574    expr: &Expr,
3575    code: &str,
3576    variable_types: &HashMap<Symbol, String>,
3577    interner: &Interner,
3578) -> String {
3579    if is_complex_expr(expr, variable_types, interner) {
3580        code.to_string()
3581    } else {
3582        format!("LogosComplex::from_i64(({}) as i64)", code)
3583    }
3584}
3585
3586/// Does `expr` statically produce an `f64`? A float literal, a float-typed binding, float `+ − × ÷`,
3587/// or a real `sqrt`. Used to route `complex(re, im)` to the FLOATING-POINT complex when a part is a
3588/// float (mirroring the interpreter's `complex()` dispatch).
3589pub(super) fn produces_float(
3590    expr: &Expr,
3591    variable_types: &HashMap<Symbol, String>,
3592    interner: &Interner,
3593) -> bool {
3594    match expr {
3595        Expr::Literal(Literal::Float(_)) => true,
3596        Expr::Identifier(sym) => variable_types.get(sym).map_or(false, |t| t == "f64"),
3597        Expr::BinaryOp {
3598            op:
3599                BinaryOpKind::Add
3600                | BinaryOpKind::Subtract
3601                | BinaryOpKind::Multiply
3602                | BinaryOpKind::Divide,
3603            left,
3604            right,
3605        } => {
3606            produces_float(left, variable_types, interner)
3607                || produces_float(right, variable_types, interner)
3608        }
3609        // `abs` always yields an f64 magnitude; `sqrt` yields an f64 UNLESS its argument is a
3610        // float-complex (in which case it is a `ComplexF`, not a float). A call to one of the
3611        // math.lg `-> Real` transcendentals (`sin`/`cos`/`exp`/`ln`/`hypot`/…) likewise yields an
3612        // f64 — WITHOUT this, `complex(sin(x), cos(y))` mis-selects the exact `LogosComplex`
3613        // representation and lossily truncates each float part through `as i64`.
3614        Expr::Call { function, args } => {
3615            let name = interner.resolve(*function);
3616            name == "abs"
3617                || name == "re"
3618                || name == "im"
3619                || is_float_returning_math_call(*function, interner)
3620                || (name == "sqrt"
3621                    && !args.is_empty()
3622                    && !is_complexf_expr(args[0], variable_types, interner))
3623        }
3624        // `item i of xs` over a `Seq of Float` (a local, a literal, or a borrow `&[f64]` param).
3625        Expr::Index { collection, .. } => {
3626            seq_element_rust_type(collection, variable_types) == Some("f64")
3627        }
3628        _ => false,
3629    }
3630}
3631
3632/// The math.lg functions whose declared return type is `Real` (compiles to `f64`). MUST mirror the
3633/// `-> Real` surface of `assets/std/math.lg` exactly — `float_returning_list_mirrors_math_lg`
3634/// (below) parses the module and fails the build if the two drift, so a newly-added transcendental
3635/// cannot silently fall off this list.
3636const FLOAT_RETURNING_MATH_FNS: &[&str] = &[
3637    "absR",
3638    "absReal",
3639    "acos",
3640    "acosh",
3641    "asin",
3642    "asinh",
3643    "atan",
3644    "atan2",
3645    "atanOffset",
3646    "atanPos",
3647    "atanReduce",
3648    "atanSign",
3649    "atanh",
3650    "cAsinhIm",
3651    "cAsinhRe",
3652    "cAtanhIm",
3653    "cAtanhRe",
3654    "cbrt",
3655    "copysign",
3656    "cos",
3657    "cosCore",
3658    "cosCoreP",
3659    "cosh",
3660    "cosP",
3661    "cPhase",
3662    "cSqrtIm",
3663    "cSqrtRe",
3664    "degrees",
3665    "dimReal",
3666    "distReal",
3667    "divEuclid",
3668    "eReal",
3669    "erf",
3670    "erfc",
3671    "erfcinv",
3672    "erfinv",
3673    "exp",
3674    "exp2",
3675    "expm1",
3676    "expP",
3677    "floorR",
3678    "fma",
3679    "fmax",
3680    "fmin",
3681    "fmodReal",
3682    "fract",
3683    "frexpFrac",
3684    "gamma",
3685    "hypot",
3686    "ldexp",
3687    "lgamma",
3688    "ln",
3689    "lnP",
3690    "log10",
3691    "log1p",
3692    "log2",
3693    "logb",
3694    "logBase",
3695    "mathInf",
3696    "mathNan",
3697    "maxReal",
3698    "modfFrac",
3699    "modfInt",
3700    "piReal",
3701    "pow2int",
3702    "powi",
3703    "radians",
3704    "ratAtan",
3705    "recip",
3706    "remainderReal",
3707    "remEuclid",
3708    "rint",
3709    "roundEvenReal",
3710    "roundR",
3711    "sin",
3712    "sinCore",
3713    "sinCoreP",
3714    "sinh",
3715    "sinP",
3716    "tan",
3717    "tanh",
3718    "tauReal",
3719    "nextafter",
3720    "ulp",
3721];
3722
3723/// True when a call to `name` produces a float — needed so `complex(sin(x), cos(y))` and friends
3724/// select the floating-point `LogosComplexF` representation instead of the exact `LogosComplex`
3725/// (which would mismatch a `-> ComplexF` return type and truncate the float parts through `as i64`).
3726pub(crate) fn is_float_returning_math_fn(name: &str) -> bool {
3727    FLOAT_RETURNING_MATH_FNS.contains(&name)
3728}
3729
3730/// The math.lg functions whose declared return type is `ComplexF` (compiles to `LogosComplexF`).
3731/// MUST mirror the `-> ComplexF` surface of `assets/std/math.lg` exactly — a call to one of these
3732/// IS a floating-point complex, so `re`/`im` extraction, complex arithmetic, and a `-> ComplexF`
3733/// return must take the `LogosComplexF` path, not cast the value through `as f64`. The
3734/// `complexf_returning_list_mirrors_math_lg` test fails the build if the two drift.
3735const COMPLEXF_RETURNING_MATH_FNS: &[&str] = &[
3736    "cAcos", "cAcosh", "cAsin", "cAsinh", "cAtan", "cAtanh", "cConj", "cCos", "cCosh", "cCot",
3737    "cExp", "cInf", "cInfj", "cLog", "cLog10", "cNan", "cNanj", "cPow", "cRect", "cSin", "cSinh",
3738    "cSqrt", "cTan", "cTanh",
3739];
3740
3741/// True when `name` is a math.lg function whose return type is `ComplexF`.
3742pub(crate) fn is_complexf_returning_math_fn(name: &str) -> bool {
3743    COMPLEXF_RETURNING_MATH_FNS.contains(&name)
3744}
3745
3746/// True when a CALL to `function` yields a `ComplexF` — the declarer-wins analogue of
3747/// [`is_float_returning_math_call`]. A `## To cExp …` in THIS program shadows math.lg's `cExp`:
3748/// the `COMPLEXF_RETURNING_MATH_FNS` list keys on bare NAMES, so without this a user's own
3749/// `## To cExp (n: Int) -> Int` would be typed `ComplexF` and mis-lowered (re/im/arith on a plain
3750/// Int). Whoever declared the name in this program owns its return type; the name list is only the
3751/// fallback for a name the program does not declare.
3752pub(crate) fn is_complexf_returning_math_call(function: Symbol, interner: &Interner) -> bool {
3753    if let Some(declared) = FN_RETURN_TYPES.with(|c| c.borrow().get(&function).cloned()) {
3754        return declared == "LogosComplexF";
3755    }
3756    is_complexf_returning_math_fn(interner.resolve(function))
3757}
3758
3759#[cfg(test)]
3760#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/codegen/expr/float_returning_math_fn_tests.rs"]
3761mod float_returning_math_fn_tests;
3762
3763/// True when `complex(a, b)` should build a floating-point complex — a part is an `f64`.
3764pub(super) fn complex_call_is_float(
3765    args: &[&Expr],
3766    variable_types: &HashMap<Symbol, String>,
3767    interner: &Interner,
3768) -> bool {
3769    args.len() == 2
3770        && args
3771            .iter()
3772            .any(|&a| produces_float(a, variable_types, interner))
3773}
3774
3775/// Does `expr` evaluate to a `LogosComplexF` (floating-point complex)? A float-argument `complex(..)`,
3776/// `+ − × ÷` where a side is `ComplexF`, or an identifier bound to `LogosComplexF`.
3777pub(super) fn is_complexf_expr(
3778    expr: &Expr,
3779    variable_types: &HashMap<Symbol, String>,
3780    interner: &Interner,
3781) -> bool {
3782    match expr {
3783        // A float-argument `complex(..)`, `sqrt` of a float-complex (`√z` is a `ComplexF`), or
3784        // `conjugate` of a float-complex (conjugation preserves the `ComplexF` type).
3785        Expr::Call { function, args } => {
3786            let name = interner.resolve(*function);
3787            is_complexf_returning_math_call(*function, interner)
3788                || (name == "complex" && complex_call_is_float(args, variable_types, interner))
3789                || (name == "sqrt"
3790                    && args.len() == 1
3791                    && is_complexf_expr(args[0], variable_types, interner))
3792                || (name == "conjugate"
3793                    && args.len() == 1
3794                    && is_complexf_expr(args[0], variable_types, interner))
3795        }
3796        Expr::BinaryOp {
3797            op:
3798                BinaryOpKind::Add
3799                | BinaryOpKind::Subtract
3800                | BinaryOpKind::Multiply
3801                | BinaryOpKind::Divide,
3802            left,
3803            right,
3804        } => {
3805            is_complexf_expr(left, variable_types, interner)
3806                || is_complexf_expr(right, variable_types, interner)
3807        }
3808        // `item i of xs` where `xs : Seq of ComplexF` (`LogosSeq<LogosComplexF>`).
3809        Expr::Index { collection, .. } => {
3810            seq_element_rust_type(collection, variable_types) == Some("LogosComplexF")
3811        }
3812        Expr::Identifier(sym) => variable_types
3813            .get(sym)
3814            .map_or(false, |t| t == "LogosComplexF"),
3815        _ => false,
3816    }
3817}
3818
3819/// A `LogosComplexF`-producing operand: an already-`ComplexF` value is used verbatim; anything else
3820/// (an int, a float, or an exact `Complex`) embeds as `LogosComplexF::from_f64((..) as f64)`.
3821fn complexf_operand(
3822    expr: &Expr,
3823    code: &str,
3824    variable_types: &HashMap<Symbol, String>,
3825    interner: &Interner,
3826) -> String {
3827    if is_complexf_expr(expr, variable_types, interner) {
3828        code.to_string()
3829    } else {
3830        format!("LogosComplexF::from_f64(({}) as f64)", code)
3831    }
3832}
3833
3834/// Does `expr` evaluate to a `LogosModular`? True for a `modular(..)` call, for `+ − × ÷` over
3835/// two Modular operands, and for an identifier bound to a `LogosModular`. (No auto-lift: a bare
3836/// integer has no modulus, so modular arithmetic fires only when BOTH operands are modular.)
3837pub(super) fn is_modular_expr(
3838    expr: &Expr,
3839    variable_types: &HashMap<Symbol, String>,
3840    interner: &Interner,
3841) -> bool {
3842    match expr {
3843        Expr::Call { function, .. } => interner.resolve(*function) == "modular",
3844        Expr::BinaryOp {
3845            op:
3846                BinaryOpKind::Add
3847                | BinaryOpKind::Subtract
3848                | BinaryOpKind::Multiply
3849                | BinaryOpKind::Divide,
3850            left,
3851            right,
3852        } => {
3853            is_modular_expr(left, variable_types, interner)
3854                && is_modular_expr(right, variable_types, interner)
3855        }
3856        Expr::Identifier(sym) => variable_types
3857            .get(sym)
3858            .map_or(false, |t| t == "LogosModular"),
3859        _ => false,
3860    }
3861}
3862
3863/// Does `expr` evaluate to a `LogosQuantity`? True for a `quantity(..)`/`convert(..)` call, an
3864/// identifier bound to a `LogosQuantity`, `+ −` over two quantities, and `× ÷` where AT LEAST one
3865/// operand is a quantity (the other scales it). Mirrors the interpreter's quantity dispatch.
3866pub(super) fn is_quantity_expr(
3867    expr: &Expr,
3868    variable_types: &HashMap<Symbol, String>,
3869    interner: &Interner,
3870) -> bool {
3871    match expr {
3872        Expr::Call { function, .. } => {
3873            matches!(interner.resolve(*function), "quantity" | "convert")
3874        }
3875        Expr::BinaryOp {
3876            op: BinaryOpKind::Add | BinaryOpKind::Subtract,
3877            left,
3878            right,
3879        } => {
3880            is_quantity_expr(left, variable_types, interner)
3881                && is_quantity_expr(right, variable_types, interner)
3882        }
3883        Expr::BinaryOp {
3884            op: BinaryOpKind::Multiply | BinaryOpKind::Divide,
3885            left,
3886            right,
3887        } => {
3888            is_quantity_expr(left, variable_types, interner)
3889                || is_quantity_expr(right, variable_types, interner)
3890        }
3891        Expr::Identifier(sym) => variable_types
3892            .get(sym)
3893            .map_or(false, |t| t == "LogosQuantity"),
3894        _ => false,
3895    }
3896}
3897
3898/// Does `expr` evaluate to a `LogosMoney`? True for a `money(..)` call, an identifier bound to a
3899/// `LogosMoney`, `+ −` over two monies, and `× ÷` where AT LEAST one operand is money (the other
3900/// scales it). Mirrors the interpreter's money dispatch.
3901pub(super) fn is_money_expr(
3902    expr: &Expr,
3903    variable_types: &HashMap<Symbol, String>,
3904    interner: &Interner,
3905) -> bool {
3906    match expr {
3907        Expr::Call { function, .. } => interner.resolve(*function) == "money",
3908        Expr::BinaryOp {
3909            op: BinaryOpKind::Add | BinaryOpKind::Subtract,
3910            left,
3911            right,
3912        } => {
3913            is_money_expr(left, variable_types, interner)
3914                && is_money_expr(right, variable_types, interner)
3915        }
3916        Expr::BinaryOp {
3917            op: BinaryOpKind::Multiply | BinaryOpKind::Divide,
3918            left,
3919            right,
3920        } => {
3921            is_money_expr(left, variable_types, interner)
3922                || is_money_expr(right, variable_types, interner)
3923        }
3924        Expr::Identifier(sym) => variable_types.get(sym).map_or(false, |t| t == "LogosMoney"),
3925        _ => false,
3926    }
3927}
3928
3929/// The native word width whose all-ones mask is `m` (`2^w - 1`), or `None`. Width 64 is
3930/// excluded — its mask exceeds `i64` so it never appears as a positive literal here.
3931fn native_width_of_mask(m: i64) -> Option<i64> {
3932    match m {
3933        255 => Some(8),
3934        65535 => Some(16),
3935        4294967295 => Some(32),
3936        _ => None,
3937    }
3938}
3939
3940fn as_num_lit(e: &Expr) -> Option<i64> {
3941    if let Expr::Literal(Literal::Number(n)) = e {
3942        Some(*n)
3943    } else {
3944        None
3945    }
3946}
3947
3948/// Match the low half of a rotate idiom, `(x << s) & M` (either `&` ordering), returning the
3949/// rotated value, the shift `s`, and the mask `M`. `x` may be any expression.
3950fn match_rotate_low<'a>(e: &'a Expr<'a>) -> Option<(&'a Expr<'a>, i64, i64)> {
3951    let Expr::BinaryOp {
3952        op: BinaryOpKind::BitAnd,
3953        left,
3954        right,
3955    } = e
3956    else {
3957        return None;
3958    };
3959    let (left, right): (&'a Expr<'a>, &'a Expr<'a>) = (*left, *right);
3960    for (shl, mask) in [(left, right), (right, left)] {
3961        if let Expr::BinaryOp {
3962            op: BinaryOpKind::Shl,
3963            left: x,
3964            right: s,
3965        } = shl
3966        {
3967            let (x, s): (&'a Expr<'a>, &'a Expr<'a>) = (*x, *s);
3968            if let (Some(s), Some(m)) = (as_num_lit(s), as_num_lit(mask)) {
3969                return Some((x, s, m));
3970            }
3971        }
3972    }
3973    None
3974}
3975
3976/// Match the high half of a rotate idiom, `(x & M) >> t` (either `&` ordering), returning the
3977/// rotated value, the shift `t`, and the mask `M`.
3978fn match_rotate_high<'a>(e: &'a Expr<'a>) -> Option<(&'a Expr<'a>, i64, i64)> {
3979    let Expr::BinaryOp {
3980        op: BinaryOpKind::Shr,
3981        left,
3982        right,
3983    } = e
3984    else {
3985        return None;
3986    };
3987    let (left, right): (&'a Expr<'a>, &'a Expr<'a>) = (*left, *right);
3988    let t = as_num_lit(right)?;
3989    let Expr::BinaryOp {
3990        op: BinaryOpKind::BitAnd,
3991        left: a,
3992        right: b,
3993    } = left
3994    else {
3995        return None;
3996    };
3997    let (a, b): (&'a Expr<'a>, &'a Expr<'a>) = (*a, *b);
3998    if let Some(m) = as_num_lit(b) {
3999        return Some((a, t, m));
4000    }
4001    if let Some(m) = as_num_lit(a) {
4002        return Some((b, t, m));
4003    }
4004    None
4005}
4006
4007/// Recognize the rotate idiom `((x << s) & M) | ((x & M) >> t)` — the shape a const-specialized
4008/// `rotateLeft(x, s, w)` folds to — with `M = 2^w - 1` (w a native width) and `s + t = w` over
4009/// the SAME value `x`, and emit the single-instruction intrinsic `(x as uW).rotate_left(s) as
4010/// i64`. Sound: complementary shifts summing to a native mask width admit no meaning but a
4011/// w-bit rotate (a rotate-right by `t` is the same idiom with the halves swapped).
4012fn try_rotate_intrinsic<'a>(
4013    left: &'a Expr<'a>,
4014    right: &'a Expr<'a>,
4015    codegen: &dyn Fn(&Expr) -> String,
4016) -> Option<String> {
4017    let go = |lo: &'a Expr<'a>, hi: &'a Expr<'a>| -> Option<String> {
4018        let (xl, s, m1) = match_rotate_low(lo)?;
4019        let (xh, t, m2) = match_rotate_high(hi)?;
4020        if m1 != m2 || !super::peephole::exprs_equal(xl, xh) {
4021            return None;
4022        }
4023        let w = native_width_of_mask(m1)?;
4024        if s >= 1 && t >= 1 && s + t == w {
4025            return Some(format!(
4026                "(({} as u{w}).rotate_left({}u32) as i64)",
4027                codegen(xl),
4028                s
4029            ));
4030        }
4031        None
4032    };
4033    go(left, right).or_else(|| go(right, left))
4034}
4035
4036pub(crate) fn codegen_expr_ctx(expr: &Expr, ecx: &ExprCtx) -> String {
4037    // An operand an enclosing operation has read already, and an expression reading a value-or-nothing.
4038    if let Some(code) = super::absent::read(expr) {
4039        return code;
4040    }
4041    if let Some(code) = super::absent::emit(expr, ecx) {
4042        return code;
4043    }
4044    // The exact extension's values are `LogosValue`s, emitted on that model ahead of every
4045    // representation choice the rest of this function makes for standard numbers.
4046    if super::tower::active() {
4047        if let Some(code) = super::tower::emit_logic(expr, ecx) {
4048            return code;
4049        }
4050        if let Some(code) = super::tower::emit_collection(expr, ecx) {
4051            return code;
4052        }
4053        if super::tower::is_tower_expr(expr, ecx.variable_types, ecx.interner) {
4054            if let Some(code) = super::tower::emit(expr, ecx) {
4055                return code;
4056            }
4057        }
4058    }
4059    // A rational takes the rules of the exact number it is, ahead of every rewrite this function makes for
4060    // machine integers.
4061    if let Some(code) = super::rational::emit(expr, ecx) {
4062        return code;
4063    }
4064    // A versioner-marked node is emitted inside `std::hint::black_box(...)` — an identity
4065    // that hides a value's proven range from LLVM's over-unroller. Lift the mark while
4066    // emitting the inner form so it wraps exactly once, then restore it.
4067    if crate::optimize::facts::unmark_expr(crate::optimize::facts::Fact::BlackBox, expr) {
4068        let inner = codegen_expr_ctx(expr, ecx);
4069        crate::optimize::facts::mark_expr(crate::optimize::facts::Fact::BlackBox, expr);
4070        return format!("std::hint::black_box({})", inner);
4071    }
4072    if let Some(code) = try_mask_narrow(expr, ecx) {
4073        return code;
4074    }
4075    // Opt::StrengthReducePow2: `x % 2^k` -> `x & (2^k-1)`, `x / 2^k` -> `x >> k`, when `x >= 0`.
4076    // Intercepted HERE (before exact-chain / narrowed-op routing) so it fires uniformly on every
4077    // path. Byte-identical for `x >= 0`; the value is in `[0, x]` so it never overflows i64 — the
4078    // surrounding overflow guard is unaffected. Hands LLVM the single AND/SHR it can't derive from a
4079    // signed i64 `%`/`/`, which also unblocks auto-vectorization.
4080    if let Expr::BinaryOp { op, left, right } = expr {
4081        if matches!(op, BinaryOpKind::Modulo | BinaryOpKind::Divide)
4082            && crate::optimize::active_config().is_on(crate::optimization::Opt::StrengthReducePow2)
4083        {
4084            if let Expr::Literal(Literal::Number(d)) = right {
4085                // Skip a bignum-promoted operand: `LogosInt` has no `Shr`/`BitAnd` with an integer, so
4086                // `len >> 3` / `len & 7` would be an E0369 — the division/modulo must stay on the exact
4087                // bignum path. (Only fire on a raw i64 `x >= 0`, where the mask/shift is valid + faster.)
4088                if *d > 0
4089                    && (*d as u64).is_power_of_two()
4090                    && is_nonneg_expr(left)
4091                    && !mentions_bigint_var(left, ecx.variable_types)
4092                {
4093                    crate::optimize::mark_fired(crate::optimization::Opt::StrengthReducePow2);
4094                    let l = codegen_expr_ctx(left, ecx);
4095                    return match op {
4096                        BinaryOpKind::Modulo => format!("({} & {})", l, d - 1),
4097                        _ => format!("({} >> {})", l, d.trailing_zeros()),
4098                    };
4099                }
4100            }
4101        }
4102    }
4103    if let Some(code) = try_mod_wrap(expr, ecx) {
4104        return code;
4105    }
4106    // Bind the fields the match arms read directly; `registry` rides along in
4107    // `ecx` and reaches recursion via the `recurse!` macro.
4108    let ExprCtx {
4109        interner,
4110        synced_vars,
4111        boxed_fields,
4112        async_functions,
4113        boxed_bindings,
4114        string_vars,
4115        variable_types,
4116        fast_div,
4117        ..
4118    } = *ecx;
4119    let names = RustNames::new(interner);
4120    // Helper macro for recursive calls with all context
4121    macro_rules! recurse {
4122        ($e:expr) => {
4123            codegen_expr_ctx($e, ecx)
4124        };
4125    }
4126    // Recurse into an INDEX subexpression: arithmetic there is a `usize`
4127    // computation (raw i64, never exact-promoted). The flag propagates through
4128    // nested arithmetic automatically.
4129    macro_rules! irecurse {
4130        ($e:expr) => {
4131            codegen_expr_ctx(
4132                $e,
4133                &ExprCtx {
4134                    int_index_context: true,
4135                    ..*ecx
4136                },
4137            )
4138        };
4139    }
4140
4141    match expr {
4142        // Server rendering of a View lands with `## Route … -> View`; until then the AOT tier
4143        // refuses at compile time rather than emitting a value it cannot represent.
4144        Expr::View(_) => {
4145            return "compile_error!(\"LGX: a View value has no AOT-Rust representation yet\")"
4146                .to_string()
4147        }
4148        Expr::Dom(_) => {
4149            return "compile_error!(\"LGX: a page query has no AOT-Rust representation yet\")"
4150                .to_string()
4151        }
4152        Expr::Literal(lit) => codegen_literal(lit, interner),
4153
4154        Expr::Identifier(sym) => {
4155            let name = names.ident(*sym);
4156            // Dereference boxed bindings from enum destructuring, and a `mutable` parameter lent
4157            // as `&mut` — both are read and written as the place behind the reference.
4158            let base = if boxed_bindings.contains(sym) || lent_in_place(*sym, variable_types) {
4159                format!("(*{})", name)
4160            } else {
4161                name
4162            };
4163            // An overflow-promoting `LogosInt` variable: in an INDEX position it must narrow to
4164            // an i64 (`.expect_i64`, then `- 1 as usize` downstream); in any other value position
4165            // it is read by value, so `.clone()` avoids a move (LogosInt is not Copy).
4166            if variable_types
4167                .get(sym)
4168                .map_or(false, |t| t.contains("__bigint"))
4169            {
4170                if ecx.int_index_context {
4171                    format!("{}.expect_i64(\"Int\")", base)
4172                } else if is_movable_last_use(*sym) {
4173                    // Dead last-use (reassigned/returned right after): move, not clone.
4174                    base
4175                } else {
4176                    format!("{}.clone()", base)
4177                }
4178            } else {
4179                base
4180            }
4181        }
4182
4183        Expr::BinaryOp { op, left, right } => {
4184            // A comparison or equality reads a counter operand as its total (`is_counter_read`).
4185            let compares = matches!(
4186                op,
4187                BinaryOpKind::Lt
4188                    | BinaryOpKind::Gt
4189                    | BinaryOpKind::LtEq
4190                    | BinaryOpKind::GtEq
4191                    | BinaryOpKind::Eq
4192                    | BinaryOpKind::NotEq
4193            );
4194            macro_rules! recurse {
4195                ($e:expr) => {{
4196                    let operand: &Expr = $e;
4197                    let code = codegen_expr_ctx(operand, ecx);
4198                    if compares && is_counter_read(operand, ecx) {
4199                        format!("{}.value()", code)
4200                    } else {
4201                        code
4202                    }
4203                }};
4204            }
4205            // Rotate-idiom recognition: an inlined/const-specialized `rotateLeft(x,s,w)` folds to
4206            // `((x << s) & M) | ((x & M) >> (w-s))` — a masked shift LLVM will not turn into a
4207            // rotate. That shape IS a w-bit rotate of x's low w bits, so emit the single-`ROL`
4208            // intrinsic. (The clean call-site form is handled in the `Call` arm; this catches the
4209            // post-specialization form the optimizer produces when the args are constant.)
4210            if matches!(op, BinaryOpKind::BitOr)
4211                && crate::optimize::active_config().is_on(crate::optimization::Opt::BitIntrinsics)
4212            {
4213                if let Some(code) = try_rotate_intrinsic(*left, *right, &|e| recurse!(e)) {
4214                    crate::optimize::mark_fired(crate::optimization::Opt::BitIntrinsics);
4215                    return code;
4216                }
4217            }
4218            // O9 libdivide: a loop-invariant POSITIVE divisor lowers to a
4219            // precomputed `LogosDivU64` magic multiply (`helper.rem(x)` /
4220            // `helper.div(x)`) instead of a hardware `div`/`idiv`. `detect_fast_div`
4221            // already proved the divisor immutable and `>= 1` and the dividend
4222            // `>= 0` at every site, so the `i64`→`u64` reinterpretation is
4223            // value-preserving.
4224            // A promoted (`LogosInt`) dividend can hold a value beyond i64, so the `i64`→`u64`
4225            // libdivide reinterpretation is neither valid (no `as` cast on `LogosInt`) nor correct;
4226            // it falls through to the exact helper below.
4227            if matches!(op, BinaryOpKind::Modulo | BinaryOpKind::Divide)
4228                && !mentions_bigint_var(left, variable_types)
4229            {
4230                if let Expr::Identifier(n) = right {
4231                    if let Some(helper) = fast_div.get(n) {
4232                        let dividend = recurse!(left);
4233                        let method = if matches!(op, BinaryOpKind::Modulo) {
4234                            "rem"
4235                        } else {
4236                            "div"
4237                        };
4238                        return format!("({}.{}(({}) as u64) as i64)", helper, method, dividend);
4239                    }
4240                }
4241            }
4242
4243            // Flatten chained string concat/add into a single format! call.
4244            // Turns O(n^2) nested format! into O(n) single-allocation.
4245            // ★ A TEXT-TYPED FIELD READ, PARAMETER, OR INDEXED READ IS A STRING OPERAND. `p's left
4246            // + p's right` was not recognised as concatenation, so it emitted `p.left + p.right` —
4247            // and Rust's `+` on `String` wants `&str` on the right, so it did not build. The type
4248            // is the only thing that can answer this: a FieldAccess alone cannot be assumed to be
4249            // text, because an Int field under `+` is ADDITION and folding it into a `format!`
4250            // would turn `5 + 1` into "51". The same blind spot hits a Text-typed function
4251            // PARAMETER (never entered into `string_vars`, only a `Let` local is) and an indexed
4252            // read of a `Seq of Text` / `Map of _ to Text` (`is_definitely_string_expr_with_vars`
4253            // has no `Expr::Index` arm at all) — `is_text_typed_identifier` and
4254            // `is_text_typed_index` close both the same way `record_field_rust_type` closes the
4255            // field case: by consulting the DECLARED type instead of guessing from shape alone.
4256            let string_operand = |e: &Expr| {
4257                is_definitely_string_expr_with_vars(e, string_vars)
4258                    || super::absent::holds_text(e, ecx)
4259                    || is_text_typed_identifier(e, variable_types)
4260                    || is_text_typed_index(e, variable_types)
4261                    || record_field_rust_type(e, interner, variable_types, ecx.registry)
4262                        .is_some_and(|t| t == "String")
4263            };
4264            let is_string_concat = matches!(op, BinaryOpKind::Concat)
4265                || (matches!(op, BinaryOpKind::Add)
4266                    && (string_operand(left) || string_operand(right)));
4267
4268            if is_string_concat {
4269                let mut operands = Vec::new();
4270                collect_string_concat_operands_with(expr, &string_operand, &mut operands);
4271                let placeholders: String =
4272                    operands.iter().map(|_| "{}").collect::<Vec<_>>().join("");
4273                let values: Vec<String> = operands
4274                    .iter()
4275                    .map(|e| {
4276                        // String literals can be &str inside format!() — no heap allocation needed
4277                        if let Expr::Literal(Literal::Text(sym)) = e {
4278                            format!(
4279                                "\"{}\"",
4280                                crate::codegen::stmt::rust_string_escape(interner.resolve(*sym))
4281                            )
4282                        } else if matches!(e, Expr::Literal(Literal::Nothing) | Expr::OptionNone) {
4283                            "\"nothing\"".to_string()
4284                        } else if super::absent::is_held(e, ecx) {
4285                            // A value-or-nothing joins as it shows: its value, or `nothing`.
4286                            format!("logicaffeine_system::io::show_string(&({}))", recurse!(e))
4287                        } else {
4288                            recurse!(e)
4289                        }
4290                    })
4291                    .collect();
4292                return format_in_order(&placeholders, &operands, values, variable_types);
4293            }
4294
4295            // `a followed by b` — merge two sequences into one fresh `LogosSeq` (the default repr
4296            // for a `Seq of T`, matching list literals and slices). `.to_vec()` clones from either
4297            // representation (a plain `Vec<T>` or a `LogosSeq<T>`), so the operands are
4298            // representation-agnostic.
4299            if matches!(op, BinaryOpKind::SeqConcat) {
4300                let l = recurse!(left);
4301                let r = recurse!(right);
4302                return format!(
4303                    "LogosSeq::from_vec({{ let mut __sc = ({}).to_vec(); __sc.extend(({}).to_vec()); __sc }})",
4304                    l, r
4305                );
4306            }
4307
4308            // `a is approximately b` — the ONE shared isclose definition
4309            // (both operands promoted to f64; approximation is inherently
4310            // tolerant, so the lossy view is correct here).
4311            if matches!(op, BinaryOpKind::ApproxEq) {
4312                let l = recurse!(left);
4313                let r = recurse!(right);
4314                return format!("logos_approx_eq(({}) as f64, ({}) as f64)", l, r);
4315            }
4316
4317            // `| & ^ -` on SET operands are the set operations (insertion-
4318            // ordered IndexSet methods; `-` reaches here only for Sets — the
4319            // numeric subtract keeps the plain emission below).
4320            if matches!(
4321                op,
4322                BinaryOpKind::BitAnd
4323                    | BinaryOpKind::BitOr
4324                    | BinaryOpKind::BitXor
4325                    | BinaryOpKind::Subtract
4326            ) {
4327                let set_typed = |e: &Expr| -> bool {
4328                    matches!(e, Expr::Identifier(sym)
4329                        if variable_types.get(sym).is_some_and(|t| t.starts_with("Set<") || t.starts_with("FxHashSet<")))
4330                        || matches!(e, Expr::Call { function, .. } if names.raw(*function) == "setOf")
4331                };
4332                if set_typed(left) || set_typed(right) {
4333                    let l = recurse!(left);
4334                    let r = recurse!(right);
4335                    let method = match op {
4336                        BinaryOpKind::BitAnd => "intersection",
4337                        BinaryOpKind::BitOr => "union",
4338                        BinaryOpKind::BitXor => "symmetric_difference",
4339                        _ => "difference",
4340                    };
4341                    return format!("({}).{}(&({})).cloned().collect::<Set<_>>()", l, method, r);
4342                }
4343            }
4344
4345            // `xs + ys` on sequences IS `followed by` — the same fresh-merge emission.
4346            if matches!(op, BinaryOpKind::Add)
4347                && (is_definitely_seq_expr(left, variable_types, interner)
4348                    || is_definitely_seq_expr(right, variable_types, interner))
4349            {
4350                let l = recurse!(left);
4351                let r = recurse!(right);
4352                return format!(
4353                    "LogosSeq::from_vec({{ let mut __sc = ({}).to_vec(); __sc.extend(({}).to_vec()); __sc }})",
4354                    l, r
4355                );
4356            }
4357
4358            // `xs * n` / `n * xs` — repeat into a fresh sequence; every slot is
4359            // an independent `fill_clone` of its element (n rows, never n
4360            // aliases of one). n ≤ 0 is empty, matching the tree-walker.
4361            if matches!(op, BinaryOpKind::Multiply) {
4362                let seq_first = is_definitely_seq_expr(left, variable_types, interner);
4363                let seq_second = is_definitely_seq_expr(right, variable_types, interner);
4364                if seq_first || seq_second {
4365                    let (seq_e, n_e) = if seq_first {
4366                        (left, right)
4367                    } else {
4368                        (right, left)
4369                    };
4370                    let s = recurse!(seq_e);
4371                    let n = recurse!(n_e);
4372                    return format!(
4373                        "{{ let __rp_src = ({}).to_vec(); let __rp_n = (({}) as i64).max(0) as usize; \
4374                         let mut __rp = Vec::with_capacity(__rp_src.len() * __rp_n); \
4375                         for _ in 0..__rp_n {{ __rp.extend(__rp_src.iter().map(|__e| __e.fill_clone())); }} \
4376                         LogosSeq::from_vec(__rp) }}",
4377                        s, n
4378                    );
4379                }
4380            }
4381
4382            // Optimize HashMap .get() for equality comparisons to avoid cloning
4383            if matches!(op, BinaryOpKind::Eq | BinaryOpKind::NotEq) {
4384                let neg = matches!(op, BinaryOpKind::NotEq);
4385                // Check if left side is a HashMap/LogosMap index
4386                if let Expr::Index { collection, index } = left {
4387                    if let Expr::Identifier(sym) = collection {
4388                        if let Some(t) = variable_types.get(sym) {
4389                            if is_logos_map_type(t) {
4390                                let coll_str = recurse!(collection);
4391                                let key_str = irecurse!(index);
4392                                let val_str = recurse!(right);
4393                                let cmp = if neg { "!=" } else { "==" };
4394                                return format!(
4395                                    "({}.get(&({})) {} Some({}))",
4396                                    coll_str, key_str, cmp, val_str
4397                                );
4398                            } else if t.starts_with("std::collections::HashMap")
4399                                || t.starts_with("HashMap")
4400                                || t.starts_with("rustc_hash::FxHashMap")
4401                                || t.starts_with("FxHashMap")
4402                            {
4403                                let coll_str = recurse!(collection);
4404                                let key_str = irecurse!(index);
4405                                let val_str = recurse!(right);
4406                                let cmp = if neg { "!=" } else { "==" };
4407                                if has_copy_value_type(t) {
4408                                    return format!(
4409                                        "({}.get(&({})).copied() {} Some({}))",
4410                                        coll_str, key_str, cmp, val_str
4411                                    );
4412                                } else {
4413                                    return format!(
4414                                        "({}.get(&({})) {} Some(&({})))",
4415                                        coll_str, key_str, cmp, val_str
4416                                    );
4417                                }
4418                            }
4419                        }
4420                    }
4421                }
4422                // Check if right side is a HashMap/LogosMap index
4423                if let Expr::Index { collection, index } = right {
4424                    if let Expr::Identifier(sym) = collection {
4425                        if let Some(t) = variable_types.get(sym) {
4426                            if is_logos_map_type(t) {
4427                                let coll_str = recurse!(collection);
4428                                let key_str = irecurse!(index);
4429                                let val_str = recurse!(left);
4430                                let cmp = if neg { "!=" } else { "==" };
4431                                return format!(
4432                                    "(Some({}) {} {}.get(&({})))",
4433                                    val_str, cmp, coll_str, key_str
4434                                );
4435                            } else if t.starts_with("std::collections::HashMap")
4436                                || t.starts_with("HashMap")
4437                                || t.starts_with("rustc_hash::FxHashMap")
4438                                || t.starts_with("FxHashMap")
4439                            {
4440                                let coll_str = recurse!(collection);
4441                                let key_str = irecurse!(index);
4442                                let val_str = recurse!(left);
4443                                let cmp = if neg { "!=" } else { "==" };
4444                                if has_copy_value_type(t) {
4445                                    return format!(
4446                                        "(Some({}) {} {}.get(&({})).copied())",
4447                                        val_str, cmp, coll_str, key_str
4448                                    );
4449                                } else {
4450                                    return format!(
4451                                        "(Some(&({})) {} {}.get(&({})))",
4452                                        val_str, cmp, coll_str, key_str
4453                                    );
4454                                }
4455                            }
4456                        }
4457                    }
4458                }
4459
4460                // Optimize string-index-vs-string-index comparison to use direct
4461                // byte comparison via as_bytes() instead of logos_get_char().
4462                // Byte equality is correct for UTF-8: two characters are equal
4463                // iff their byte representations are equal, and the logos_get_char
4464                // function already uses byte-level indexing for the ASCII fast path.
4465                if let (
4466                    Expr::Index {
4467                        collection: left_coll,
4468                        index: left_idx,
4469                    },
4470                    Expr::Index {
4471                        collection: right_coll,
4472                        index: right_idx,
4473                    },
4474                ) = (left, right)
4475                {
4476                    let left_is_string = if let Expr::Identifier(sym) = left_coll {
4477                        string_vars.contains(sym)
4478                            || variable_types.get(sym).map_or(false, |t| t == "String")
4479                    } else {
4480                        false
4481                    };
4482                    let right_is_string = if let Expr::Identifier(sym) = right_coll {
4483                        string_vars.contains(sym)
4484                            || variable_types.get(sym).map_or(false, |t| t == "String")
4485                    } else {
4486                        false
4487                    };
4488                    if left_is_string && right_is_string {
4489                        let cmp = if neg { "!=" } else { "==" };
4490                        let left_coll_str = recurse!(left_coll);
4491                        let right_coll_str = recurse!(right_coll);
4492                        let left_idx_simplified = super::peephole::simplify_1based_index(
4493                            left_idx,
4494                            interner,
4495                            true,
4496                            variable_types,
4497                        );
4498                        let right_idx_simplified = super::peephole::simplify_1based_index(
4499                            right_idx,
4500                            interner,
4501                            true,
4502                            variable_types,
4503                        );
4504                        return format!(
4505                            "({}.as_bytes()[{}] {} {}.as_bytes()[{}])",
4506                            left_coll_str,
4507                            left_idx_simplified,
4508                            cmp,
4509                            right_coll_str,
4510                            right_idx_simplified
4511                        );
4512                    }
4513                }
4514
4515                // Optimize string-index-vs-single-char-literal comparison to use
4516                // logos_get_char() == 'c' instead of LogosIndex::logos_get() == String::from("c").
4517                // Avoids two heap allocations per comparison in hot loops.
4518                let is_string_index = |expr: &Expr| -> bool {
4519                    if let Expr::Index { collection, .. } = expr {
4520                        if let Expr::Identifier(sym) = collection {
4521                            return string_vars.contains(sym)
4522                                || variable_types.get(sym).map_or(false, |t| t == "String");
4523                        }
4524                    }
4525                    false
4526                };
4527                let single_char_literal = |expr: &Expr| -> Option<char> {
4528                    if let Expr::Literal(Literal::Text(sym)) = expr {
4529                        let s = interner.resolve(*sym);
4530                        let mut chars = s.chars();
4531                        if let Some(c) = chars.next() {
4532                            if chars.next().is_none() {
4533                                return Some(c);
4534                            }
4535                        }
4536                    }
4537                    None
4538                };
4539
4540                // Left is string index, right is single-char literal
4541                if is_string_index(left) {
4542                    if let Some(ch) = single_char_literal(right) {
4543                        if let Expr::Index { collection, index } = left {
4544                            let coll_str = recurse!(collection);
4545                            let idx_str = irecurse!(index);
4546                            let cmp = if neg { "!=" } else { "==" };
4547                            let ch_escaped = match ch {
4548                                '\'' => "\\'".to_string(),
4549                                '\\' => "\\\\".to_string(),
4550                                '\n' => "\\n".to_string(),
4551                                '\t' => "\\t".to_string(),
4552                                '\r' => "\\r".to_string(),
4553                                _ => ch.to_string(),
4554                            };
4555                            return format!(
4556                                "({}.logos_get_char({}) {} '{}')",
4557                                coll_str, idx_str, cmp, ch_escaped
4558                            );
4559                        }
4560                    }
4561                }
4562                // Right is string index, left is single-char literal
4563                if is_string_index(right) {
4564                    if let Some(ch) = single_char_literal(left) {
4565                        if let Expr::Index { collection, index } = right {
4566                            let coll_str = recurse!(collection);
4567                            let idx_str = irecurse!(index);
4568                            let cmp = if neg { "!=" } else { "==" };
4569                            let ch_escaped = match ch {
4570                                '\'' => "\\'".to_string(),
4571                                '\\' => "\\\\".to_string(),
4572                                '\n' => "\\n".to_string(),
4573                                '\t' => "\\t".to_string(),
4574                                '\r' => "\\r".to_string(),
4575                                _ => ch.to_string(),
4576                            };
4577                            return format!(
4578                                "('{}' {} {}.logos_get_char({}))",
4579                                ch_escaped, cmp, coll_str, idx_str
4580                            );
4581                        }
4582                    }
4583                }
4584            }
4585
4586            // OPT-8b: Zero-based counter in comparison.
4587            // When a __zero_based_i64 counter appears as a bare operand in a comparison,
4588            // emit (counter + 1) to compensate for the 0-based range shift.
4589            // E.g., `If i > 3` with 0-based `i` becomes `if (i + 1) > 3`.
4590            if matches!(
4591                op,
4592                BinaryOpKind::Lt
4593                    | BinaryOpKind::LtEq
4594                    | BinaryOpKind::Gt
4595                    | BinaryOpKind::GtEq
4596                    | BinaryOpKind::Eq
4597                    | BinaryOpKind::NotEq
4598            ) {
4599                let left_zb = if let Expr::Identifier(sym) = left {
4600                    variable_types
4601                        .get(sym)
4602                        .map_or(false, |t| t == "__zero_based_i64")
4603                } else {
4604                    false
4605                };
4606                let right_zb = if let Expr::Identifier(sym) = right {
4607                    variable_types
4608                        .get(sym)
4609                        .map_or(false, |t| t == "__zero_based_i64")
4610                } else {
4611                    false
4612                };
4613                if left_zb || right_zb {
4614                    let left_str = if left_zb {
4615                        format!("({} + 1)", recurse!(left))
4616                    } else {
4617                        recurse!(left)
4618                    };
4619                    let right_str = if right_zb {
4620                        format!("({} + 1)", recurse!(right))
4621                    } else {
4622                        recurse!(right)
4623                    };
4624                    let op_str = match op {
4625                        BinaryOpKind::Lt => "<",
4626                        BinaryOpKind::LtEq => "<=",
4627                        BinaryOpKind::Gt => ">",
4628                        BinaryOpKind::GtEq => ">=",
4629                        BinaryOpKind::Eq => "==",
4630                        BinaryOpKind::NotEq => "!=",
4631                        _ => unreachable!(),
4632                    };
4633                    return format!("({} {} {})", left_str, op_str, right_str);
4634                }
4635            }
4636
4637            let left_str = recurse!(left);
4638            let right_str = recurse!(right);
4639
4640            // And/Or are logical: truthiness in, Bool out, short-circuit (Rust's
4641            // `&&`/`||` keep the right operand lazy). Bool×Bool skips the trait call.
4642            if matches!(op, BinaryOpKind::And | BinaryOpKind::Or) {
4643                let op_str = match op {
4644                    BinaryOpKind::And => "&&",
4645                    BinaryOpKind::Or => "||",
4646                    _ => unreachable!(),
4647                };
4648                let bools = matches!(
4649                    infer_logos_type(left, interner, variable_types),
4650                    crate::analysis::types::LogosType::Bool
4651                ) && matches!(
4652                    infer_logos_type(right, interner, variable_types),
4653                    crate::analysis::types::LogosType::Bool
4654                );
4655                return if bools {
4656                    format!("({} {} {})", left_str, op_str, right_str)
4657                } else {
4658                    format!(
4659                        "(logos_truthy(&({})) {} logos_truthy(&({})))",
4660                        left_str, op_str, right_str
4661                    )
4662                };
4663            }
4664
4665            // Dimensioned quantity arithmetic. `+ −` need two quantities (same dimension, checked
4666            // at runtime), `× ÷` combine dimensions (two quantities) or scale a quantity by an
4667            // integer; magnitudes stay exact on the rational tower. Comparison/equality use the
4668            // derived PartialOrd/PartialEq (same-dimension; physical equality).
4669            if matches!(
4670                op,
4671                BinaryOpKind::Add
4672                    | BinaryOpKind::Subtract
4673                    | BinaryOpKind::Multiply
4674                    | BinaryOpKind::Divide
4675                    | BinaryOpKind::Lt
4676                    | BinaryOpKind::Gt
4677                    | BinaryOpKind::LtEq
4678                    | BinaryOpKind::GtEq
4679                    | BinaryOpKind::Eq
4680                    | BinaryOpKind::NotEq
4681            ) && (is_quantity_expr(left, variable_types, interner)
4682                || is_quantity_expr(right, variable_types, interner))
4683            {
4684                let l_q = is_quantity_expr(left, variable_types, interner);
4685                let r_q = is_quantity_expr(right, variable_types, interner);
4686                let code: Option<std::string::String> = match (op, l_q, r_q) {
4687                    (BinaryOpKind::Add, true, true) => {
4688                        Some(format!("{}.add(&{})", left_str, right_str))
4689                    }
4690                    (BinaryOpKind::Subtract, true, true) => {
4691                        Some(format!("{}.sub(&{})", left_str, right_str))
4692                    }
4693                    (BinaryOpKind::Multiply, true, true) => {
4694                        Some(format!("{}.mul(&{})", left_str, right_str))
4695                    }
4696                    (BinaryOpKind::Divide, true, true) => {
4697                        Some(format!("{}.div_exact(&{})", left_str, right_str))
4698                    }
4699                    // Scale a quantity by an integer (the common case), commuting for ×.
4700                    (BinaryOpKind::Multiply, true, false) => {
4701                        Some(format!("{}.scale_int({})", left_str, right_str))
4702                    }
4703                    (BinaryOpKind::Multiply, false, true) => {
4704                        Some(format!("{}.scale_int({})", right_str, left_str))
4705                    }
4706                    (BinaryOpKind::Divide, true, false) => {
4707                        Some(format!("{}.div_int({})", left_str, right_str))
4708                    }
4709                    // Comparison / equality over two quantities (PartialOrd / physical PartialEq).
4710                    (BinaryOpKind::Lt, true, true) => {
4711                        Some(format!("({} < {})", left_str, right_str))
4712                    }
4713                    (BinaryOpKind::Gt, true, true) => {
4714                        Some(format!("({} > {})", left_str, right_str))
4715                    }
4716                    (BinaryOpKind::LtEq, true, true) => {
4717                        Some(format!("({} <= {})", left_str, right_str))
4718                    }
4719                    (BinaryOpKind::GtEq, true, true) => {
4720                        Some(format!("({} >= {})", left_str, right_str))
4721                    }
4722                    (BinaryOpKind::Eq, true, true) => {
4723                        Some(format!("({} == {})", left_str, right_str))
4724                    }
4725                    (BinaryOpKind::NotEq, true, true) => {
4726                        Some(format!("({} != {})", left_str, right_str))
4727                    }
4728                    _ => None,
4729                };
4730                if let Some(c) = code {
4731                    return c;
4732                }
4733            }
4734
4735            // Money arithmetic. `+ −` require the same currency, `× ÷` scale by an integer, and a
4736            // same-currency `Money ÷ Money` is the dimensionless ratio. Mirrors the interpreter.
4737            if matches!(
4738                op,
4739                BinaryOpKind::Add
4740                    | BinaryOpKind::Subtract
4741                    | BinaryOpKind::Multiply
4742                    | BinaryOpKind::Divide
4743                    | BinaryOpKind::Lt
4744                    | BinaryOpKind::Gt
4745                    | BinaryOpKind::LtEq
4746                    | BinaryOpKind::GtEq
4747                    | BinaryOpKind::Eq
4748                    | BinaryOpKind::NotEq
4749            ) && (is_money_expr(left, variable_types, interner)
4750                || is_money_expr(right, variable_types, interner))
4751            {
4752                let l_m = is_money_expr(left, variable_types, interner);
4753                let r_m = is_money_expr(right, variable_types, interner);
4754                let code: Option<std::string::String> = match (op, l_m, r_m) {
4755                    (BinaryOpKind::Add, true, true) => {
4756                        Some(format!("{}.add(&{})", left_str, right_str))
4757                    }
4758                    (BinaryOpKind::Subtract, true, true) => {
4759                        Some(format!("{}.sub(&{})", left_str, right_str))
4760                    }
4761                    // Same-currency ratio → an exact Rational.
4762                    (BinaryOpKind::Divide, true, true) => {
4763                        Some(format!("{}.ratio(&{})", left_str, right_str))
4764                    }
4765                    // Scale money by an integer (commutes for ×); split money by an integer.
4766                    (BinaryOpKind::Multiply, true, false) => {
4767                        Some(format!("{}.scale_int({})", left_str, right_str))
4768                    }
4769                    (BinaryOpKind::Multiply, false, true) => {
4770                        Some(format!("{}.scale_int({})", right_str, left_str))
4771                    }
4772                    (BinaryOpKind::Divide, true, false) => {
4773                        Some(format!("{}.div_int({})", left_str, right_str))
4774                    }
4775                    (BinaryOpKind::Lt, true, true) => {
4776                        Some(format!("({} < {})", left_str, right_str))
4777                    }
4778                    (BinaryOpKind::Gt, true, true) => {
4779                        Some(format!("({} > {})", left_str, right_str))
4780                    }
4781                    (BinaryOpKind::LtEq, true, true) => {
4782                        Some(format!("({} <= {})", left_str, right_str))
4783                    }
4784                    (BinaryOpKind::GtEq, true, true) => {
4785                        Some(format!("({} >= {})", left_str, right_str))
4786                    }
4787                    (BinaryOpKind::Eq, true, true) => {
4788                        Some(format!("({} == {})", left_str, right_str))
4789                    }
4790                    (BinaryOpKind::NotEq, true, true) => {
4791                        Some(format!("({} != {})", left_str, right_str))
4792                    }
4793                    _ => None,
4794                };
4795                if let Some(c) = code {
4796                    return c;
4797                }
4798            }
4799
4800            // Modular (ℤ/nℤ) arithmetic. `+ − × ÷` wrap in the ring when BOTH operands are
4801            // modular (same modulus; no auto-lift). `÷` multiplies by the modular inverse.
4802            if matches!(
4803                op,
4804                BinaryOpKind::Add
4805                    | BinaryOpKind::Subtract
4806                    | BinaryOpKind::Multiply
4807                    | BinaryOpKind::Divide
4808            ) && is_modular_expr(left, variable_types, interner)
4809                && is_modular_expr(right, variable_types, interner)
4810            {
4811                let method = match op {
4812                    BinaryOpKind::Add => "add",
4813                    BinaryOpKind::Subtract => "sub",
4814                    BinaryOpKind::Multiply => "mul",
4815                    BinaryOpKind::Divide => "div_exact",
4816                    _ => unreachable!(),
4817                };
4818                return format!("{}.{}(&{})", left_str, method, right_str);
4819            }
4820
4821            // Floating-point complex arithmetic. `+ − × ÷` stay a `LogosComplexF` the moment one
4822            // operand is `ComplexF` (a real/exact operand embeds as `re + 0i`). Checked BEFORE the
4823            // exact-Complex path, so two exact complexes still stay exact.
4824            if matches!(
4825                op,
4826                BinaryOpKind::Add
4827                    | BinaryOpKind::Subtract
4828                    | BinaryOpKind::Multiply
4829                    | BinaryOpKind::Divide
4830            ) && (is_complexf_expr(left, variable_types, interner)
4831                || is_complexf_expr(right, variable_types, interner))
4832            {
4833                let l = complexf_operand(left, &left_str, variable_types, interner);
4834                let r = complexf_operand(right, &right_str, variable_types, interner);
4835                let method = match op {
4836                    BinaryOpKind::Add => "add",
4837                    BinaryOpKind::Subtract => "sub",
4838                    BinaryOpKind::Multiply => "mul",
4839                    BinaryOpKind::Divide => "div_exact",
4840                    _ => unreachable!(),
4841                };
4842                return format!("{}.{}(&{})", l, method, r);
4843            }
4844
4845            // Exact Complex arithmetic. `+ − × ÷` stay an exact `LogosComplex` (the field is
4846            // closed) the moment one operand is Complex; an integer operand embeds as `re + 0i`.
4847            if matches!(
4848                op,
4849                BinaryOpKind::Add
4850                    | BinaryOpKind::Subtract
4851                    | BinaryOpKind::Multiply
4852                    | BinaryOpKind::Divide
4853            ) && (is_complex_expr(left, variable_types, interner)
4854                || is_complex_expr(right, variable_types, interner))
4855            {
4856                let l = complex_operand(left, &left_str, variable_types, interner);
4857                let r = complex_operand(right, &right_str, variable_types, interner);
4858                let method = match op {
4859                    BinaryOpKind::Add => "add",
4860                    BinaryOpKind::Subtract => "sub",
4861                    BinaryOpKind::Multiply => "mul",
4862                    BinaryOpKind::Divide => "div_exact",
4863                    _ => unreachable!(),
4864                };
4865                return format!("{}.{}(&{})", l, method, r);
4866            }
4867
4868            // Exact Decimal (money) arithmetic. `+ − ×` stay an exact `LogosDecimal` the
4869            // moment one operand is a Decimal (scale preserved); an integer operand is widened.
4870            // (`÷` widening to Rational is a separate follow-up; not emitted here.)
4871            if matches!(
4872                op,
4873                BinaryOpKind::Add | BinaryOpKind::Subtract | BinaryOpKind::Multiply
4874            ) && (is_decimal_expr(left, variable_types, interner)
4875                || is_decimal_expr(right, variable_types, interner))
4876            {
4877                let l = decimal_operand(left, &left_str, variable_types, interner);
4878                let r = decimal_operand(right, &right_str, variable_types, interner);
4879                let method = match op {
4880                    BinaryOpKind::Add => "add",
4881                    BinaryOpKind::Subtract => "sub",
4882                    BinaryOpKind::Multiply => "mul",
4883                    _ => unreachable!(),
4884                };
4885                return format!("{}.{}(&{})", l, method, r);
4886            }
4887
4888            // Decimal division widens to an exact `LogosRational` (base-10 division need not
4889            // terminate) — `19.99 / 3` is exact, never a lossy float or a floored int.
4890            if matches!(op, BinaryOpKind::Divide)
4891                && (is_decimal_expr(left, variable_types, interner)
4892                    || is_decimal_expr(right, variable_types, interner))
4893            {
4894                let l = decimal_operand(left, &left_str, variable_types, interner);
4895                let r = decimal_operand(right, &right_str, variable_types, interner);
4896                return format!("{}.to_rational().div_exact(&{}.to_rational())", l, r);
4897            }
4898
4899            // Decimal comparison / equality: coerce each operand to `LogosDecimal` (which
4900            // derives Ord/Eq) so `price > 10` and `a == b` compile exactly, cross-type included.
4901            if matches!(
4902                op,
4903                BinaryOpKind::Lt
4904                    | BinaryOpKind::Gt
4905                    | BinaryOpKind::LtEq
4906                    | BinaryOpKind::GtEq
4907                    | BinaryOpKind::Eq
4908                    | BinaryOpKind::NotEq
4909            ) && (is_decimal_expr(left, variable_types, interner)
4910                || is_decimal_expr(right, variable_types, interner))
4911            {
4912                let l = decimal_operand(left, &left_str, variable_types, interner);
4913                let r = decimal_operand(right, &right_str, variable_types, interner);
4914                let op_str = match op {
4915                    BinaryOpKind::Lt => "<",
4916                    BinaryOpKind::Gt => ">",
4917                    BinaryOpKind::LtEq => "<=",
4918                    BinaryOpKind::GtEq => ">=",
4919                    BinaryOpKind::Eq => "==",
4920                    BinaryOpKind::NotEq => "!=",
4921                    _ => unreachable!(),
4922                };
4923                return format!("({} {} {})", l, op_str, r);
4924            }
4925
4926            // Complex equality: coerce each operand to `LogosComplex` (derives Eq). Complex
4927            // has NO order, so relational `< >` are deliberately left to fail to compile.
4928            if matches!(op, BinaryOpKind::Eq | BinaryOpKind::NotEq)
4929                && (is_complex_expr(left, variable_types, interner)
4930                    || is_complex_expr(right, variable_types, interner))
4931            {
4932                let l = complex_operand(left, &left_str, variable_types, interner);
4933                let r = complex_operand(right, &right_str, variable_types, interner);
4934                let op_str = if matches!(op, BinaryOpKind::Eq) {
4935                    "=="
4936                } else {
4937                    "!="
4938                };
4939                return format!("({} {} {})", l, op_str, r);
4940            }
4941
4942            // Exact Rational arithmetic. `ExactDivide` only ever appears in a Rational
4943            // context (the `resolve_divisions` invariant), and `+ − ×` become Rational the
4944            // moment one operand is. Coerce each operand to `LogosRational` and call the
4945            // exact method, so `Let x: Rational be 7 / 2` compiles to `7/2`, not floored `3`.
4946            if matches!(op, BinaryOpKind::ExactDivide)
4947                || (matches!(
4948                    op,
4949                    BinaryOpKind::Add | BinaryOpKind::Subtract | BinaryOpKind::Multiply
4950                ) && (is_rational_expr(left, variable_types)
4951                    || is_rational_expr(right, variable_types)))
4952            {
4953                let l = rational_operand(left, &left_str, variable_types);
4954                let r = rational_operand(right, &right_str, variable_types);
4955                let method = match op {
4956                    BinaryOpKind::Add => "add",
4957                    BinaryOpKind::Subtract => "sub",
4958                    BinaryOpKind::Multiply => "mul",
4959                    BinaryOpKind::ExactDivide => "div_exact",
4960                    _ => unreachable!(),
4961                };
4962                return format!("{}.{}(&{})", l, method, r);
4963            }
4964
4965            // `**` exponentiation has no native Rust operator, so it never
4966            // reaches the operator-string match below. Integer power is EXACT —
4967            // overflow promotes to BigInt via `logos_pow_exact` (a negative Int
4968            // exponent panics loudly, the interp's error). Any Float operand
4969            // switches to `powf`, widening the Int side to f64. Mirrors
4970            // `semantics::arith::power`.
4971            if matches!(op, BinaryOpKind::Pow) {
4972                let lt = infer_numeric_type(left, interner, variable_types);
4973                let rt = infer_numeric_type(right, interner, variable_types);
4974                if lt == "f64" || rt == "f64" {
4975                    let l = if lt == "f64" {
4976                        left_str.clone()
4977                    } else {
4978                        format!("(({}) as f64)", left_str)
4979                    };
4980                    let r = if rt == "f64" {
4981                        right_str.clone()
4982                    } else {
4983                        format!("(({}) as f64)", right_str)
4984                    };
4985                    return format!("({}).powf({})", l, r);
4986                }
4987                // Both operands constant: fold at compile time. The i64 fast path
4988                // (`checked_pow`) emits a plain literal; overflow or a negative/oversized
4989                // exponent falls through to the runtime helper (BigInt promotion, or the
4990                // loud negative-exponent error), never a giant compile-time BigInt.
4991                if let (Expr::Literal(Literal::Number(a)), Expr::Literal(Literal::Number(b))) =
4992                    (left, right)
4993                {
4994                    if let Ok(e) = u32::try_from(*b) {
4995                        if let Some(v) = a.checked_pow(e) {
4996                            return format!("{}i64", v);
4997                        }
4998                    }
4999                }
5000                let tol = ExprCtx {
5001                    int_exact_tolerant: true,
5002                    ..*ecx
5003                };
5004                let l = codegen_expr_ctx(left, &tol);
5005                let r = codegen_expr_ctx(right, &tol);
5006                // A bare integer-literal operand needs its `i64` suffix: only `i64: Into<LogosInt>`,
5007                // so a bare `{integer}` (default i32) would fail the `logos_pow_exact` bound.
5008                let l = if matches!(left, Expr::Literal(Literal::Number(_))) {
5009                    format!("{}i64", l)
5010                } else {
5011                    l
5012                };
5013                let r = if matches!(right, Expr::Literal(Literal::Number(_))) {
5014                    format!("{}i64", r)
5015                } else {
5016                    r
5017                };
5018                let inner = format!("logos_pow_exact({}, {})", l, r);
5019                return if ecx.int_exact_tolerant {
5020                    inner
5021                } else {
5022                    format!("{}.expect_i64(\"Int\")", inner)
5023                };
5024            }
5025
5026            // `//` floor division rounds toward NEGATIVE INFINITY, which Rust's `/`
5027            // (truncation) does not, so it never reaches the operator-string match
5028            // below. Integer floor is EXACT — overflow promotes to BigInt via
5029            // `logos_floordiv_exact` (a zero divisor panics loudly, the interp's
5030            // error). Any Float operand floors the float quotient, staying f64.
5031            // Mirrors `semantics::arith::floor_divide`.
5032            if matches!(op, BinaryOpKind::FloorDivide) {
5033                let lt = infer_numeric_type(left, interner, variable_types);
5034                let rt = infer_numeric_type(right, interner, variable_types);
5035                if lt == "f64" || rt == "f64" {
5036                    let l = if lt == "f64" {
5037                        left_str.clone()
5038                    } else {
5039                        format!("(({}) as f64)", left_str)
5040                    };
5041                    let r = if rt == "f64" {
5042                        right_str.clone()
5043                    } else {
5044                        format!("(({}) as f64)", right_str)
5045                    };
5046                    return format!("({} / {}).floor()", l, r);
5047                }
5048                // Both operands constant: fold the floored quotient at compile time when
5049                // it fits i64 (a zero divisor or the `i64::MIN // -1` overflow falls
5050                // through to the promoting runtime helper).
5051                if let (Expr::Literal(Literal::Number(a)), Expr::Literal(Literal::Number(b))) =
5052                    (left, right)
5053                {
5054                    if *b != 0 {
5055                        if let (Some(q), Some(r)) = (a.checked_div(*b), a.checked_rem(*b)) {
5056                            let floored = if r != 0 && (r < 0) != (*b < 0) {
5057                                q - 1
5058                            } else {
5059                                q
5060                            };
5061                            return format!("{}i64", floored);
5062                        }
5063                    }
5064                }
5065                let tol = ExprCtx {
5066                    int_exact_tolerant: true,
5067                    ..*ecx
5068                };
5069                let l = codegen_expr_ctx(left, &tol);
5070                let r = codegen_expr_ctx(right, &tol);
5071                let l = if matches!(left, Expr::Literal(Literal::Number(_))) {
5072                    format!("{}i64", l)
5073                } else {
5074                    l
5075                };
5076                let r = if matches!(right, Expr::Literal(Literal::Number(_))) {
5077                    format!("{}i64", r)
5078                } else {
5079                    r
5080                };
5081                let inner = format!("logos_floordiv_exact({}, {})", l, r);
5082                return if ecx.int_exact_tolerant {
5083                    inner
5084                } else {
5085                    format!("{}.expect_i64(\"Int\")", inner)
5086                };
5087            }
5088
5089            let op_str = match op {
5090                BinaryOpKind::Add => "+",
5091                BinaryOpKind::Subtract => "-",
5092                BinaryOpKind::Multiply => "*",
5093                // Floor division (the integer default); `ExactDivide` is handled above.
5094                BinaryOpKind::Divide | BinaryOpKind::ExactDivide => "/",
5095                BinaryOpKind::Modulo => "%",
5096                BinaryOpKind::Eq => "==",
5097                BinaryOpKind::NotEq => "!=",
5098                BinaryOpKind::Lt => "<",
5099                BinaryOpKind::Gt => ">",
5100                BinaryOpKind::LtEq => "<=",
5101                BinaryOpKind::GtEq => ">=",
5102                BinaryOpKind::And | BinaryOpKind::Or => unreachable!(), // handled above
5103                BinaryOpKind::Concat => unreachable!(),                 // handled above
5104                BinaryOpKind::SeqConcat => unreachable!(),              // handled above
5105                BinaryOpKind::ApproxEq => unreachable!(),               // handled above
5106                BinaryOpKind::Pow => unreachable!(),                    // handled above
5107                BinaryOpKind::FloorDivide => unreachable!(),            // handled above
5108                BinaryOpKind::BitXor => "^",
5109                BinaryOpKind::BitAnd => "&",
5110                BinaryOpKind::BitOr => "|",
5111                BinaryOpKind::Shl => "<<",
5112                BinaryOpKind::Shr => ">>",
5113            };
5114
5115            // Mixed Float*Int handling. ARITHMETIC promotes the Int side to
5116            // f64 (float math is the result type). COMPARISON is EXACT —
5117            // mathematical values via `logos_cmp_i64_f64`, never a lossy cast
5118            // (`i as f64` rounds above 2^53, which would call
5119            // `9007199254740993` equal to the float `9007199254740992.0`).
5120            // Same-type compares are untouched: hot loops pay nothing.
5121            if !matches!(op, BinaryOpKind::And | BinaryOpKind::Or) {
5122                let left_type = numeric_type_through_arith(left, interner, variable_types);
5123                let right_type = numeric_type_through_arith(right, interner, variable_types);
5124                let is_cmp = matches!(
5125                    op,
5126                    BinaryOpKind::Eq
5127                        | BinaryOpKind::NotEq
5128                        | BinaryOpKind::Lt
5129                        | BinaryOpKind::Gt
5130                        | BinaryOpKind::LtEq
5131                        | BinaryOpKind::GtEq
5132                );
5133                // `(int_expr, float_expr)` operand order for the exact helper;
5134                // `flip` marks that the FLOAT was on the left, so the ordering
5135                // reverses (`f < i` ⟺ `cmp(i, f) == Greater`).
5136                let mixed_cmp = if is_cmp && left_type == "f64" && right_type == "i64" {
5137                    Some((right_str.clone(), left_str.clone(), true))
5138                } else if is_cmp && left_type == "i64" && right_type == "f64" {
5139                    Some((left_str.clone(), right_str.clone(), false))
5140                } else {
5141                    None
5142                };
5143                if let Some((int_e, float_e, flip)) = mixed_cmp {
5144                    let pat = match (op, flip) {
5145                        (BinaryOpKind::Lt, false) | (BinaryOpKind::Gt, true) => {
5146                            "Some(core::cmp::Ordering::Less)"
5147                        }
5148                        (BinaryOpKind::Gt, false) | (BinaryOpKind::Lt, true) => {
5149                            "Some(core::cmp::Ordering::Greater)"
5150                        }
5151                        (BinaryOpKind::LtEq, false) | (BinaryOpKind::GtEq, true) => {
5152                            "Some(core::cmp::Ordering::Less | core::cmp::Ordering::Equal)"
5153                        }
5154                        (BinaryOpKind::GtEq, false) | (BinaryOpKind::LtEq, true) => {
5155                            "Some(core::cmp::Ordering::Greater | core::cmp::Ordering::Equal)"
5156                        }
5157                        (BinaryOpKind::Eq, _) => {
5158                            return format!("logos_i64_eq_f64({}, {})", int_e, float_e);
5159                        }
5160                        (BinaryOpKind::NotEq, _) => {
5161                            return format!("(!logos_i64_eq_f64({}, {}))", int_e, float_e);
5162                        }
5163                        _ => unreachable!("is_cmp covers exactly the six comparison ops"),
5164                    };
5165                    return format!(
5166                        "matches!(logos_cmp_i64_f64({}, {}), {})",
5167                        int_e, float_e, pat
5168                    );
5169                }
5170                if left_type == "f64" && right_type != "f64" {
5171                    return format!("({} {} (({}) as f64))", left_str, op_str, right_str);
5172                } else if right_type == "f64" && left_type != "f64" {
5173                    return format!("((({}) as f64) {} {})", left_str, op_str, right_str);
5174                }
5175
5176                // Under a `wordN(...)` truncation the result is mod 2^N, so Int add/sub/mul lower to raw
5177                // i64 `wrapping_*` — identical low bits to the checked-exact helper, at a fraction of the
5178                // cost (the MD5 byte→word schedule was ~half the runtime as `logos_*_exact`). The flag
5179                // propagates down the additive chain (recurse with `ecx`) and is reset at call boundaries.
5180                if ecx.int_wrapping
5181                    && left_type == "i64"
5182                    && right_type == "i64"
5183                    && !ecx.int_index_context
5184                    && matches!(
5185                        op,
5186                        BinaryOpKind::Add | BinaryOpKind::Subtract | BinaryOpKind::Multiply
5187                    )
5188                {
5189                    let method = match op {
5190                        BinaryOpKind::Add => "wrapping_add",
5191                        BinaryOpKind::Subtract => "wrapping_sub",
5192                        BinaryOpKind::Multiply => "wrapping_mul",
5193                        _ => unreachable!("matches! guards exactly these three"),
5194                    };
5195                    let l = codegen_expr_ctx(left, ecx);
5196                    let r = codegen_expr_ctx(right, ecx);
5197                    // Pin the receiver to `i64`: the codegen already proved both sides are i64, but a
5198                    // syntactically-unconstrained operand (e.g. a loop counter `for i in 1..=8` whose
5199                    // only use is this op) is an ambiguous `{integer}` in the emitted Rust, and
5200                    // `wrapping_add` exists on every integer type → E0689. `as i64` is a no-op on an
5201                    // already-i64 value and resolves the method. The result is i64, as before.
5202                    return format!("(({}) as i64).{}({})", l, method, r);
5203                }
5204
5205                // Overflow ruling v2 (stage 2): compiled Int arithmetic is EXACT.
5206                // Constant operands promote at COMPILE time; Oracle-proven-in-range
5207                // arithmetic stays raw i64 (hot loops pay nothing); everything else
5208                // emits the checked-exact helper — an inlined checked op whose
5209                // overflow spills to the promoting `LogosInt`. `%` rides along for
5210                // its own rims (zero divisor message, `i64::MIN % -1`).
5211                let is_exactable = matches!(
5212                    op,
5213                    BinaryOpKind::Add
5214                        | BinaryOpKind::Subtract
5215                        | BinaryOpKind::Multiply
5216                        | BinaryOpKind::Divide
5217                        | BinaryOpKind::Modulo
5218                );
5219                // A `LogosInt`-typed (promoted) operand forces the exact helper even when the
5220                // OTHER operand's type is unknown (e.g. a `while`→`for` loop counter that was never
5221                // registered): the result must stay `LogosInt`, and a raw `LogosInt * i64` has no
5222                // operator. `logos_*_exact` takes `impl Into<LogosInt>`, so a bare `i64` flows in.
5223                let has_bigint_operand = mentions_bigint_var(left, variable_types)
5224                    || mentions_bigint_var(right, variable_types);
5225
5226                // ★ BIT OPERATIONS ACT ON MACHINE WORDS. `semantics::arith::binary_op` defines `|`, `^`,
5227                // `<<` and `>>` on two `Int`s alone, and `&` also on a big integer that is not negative
5228                // beside a low mask `2^k - 1`, taking its low `k` bits; any other big operand is refused in
5229                // the operator's words. An Int operand that may be a big integer here — a promoted binding
5230                // or field, a bignum call, or arithmetic the Oracle cannot keep within i64 — is computed
5231                // exactly and handed to the runtime's rule (`logos_band_exact`, `logos_word_operand`), so
5232                // the value, or the refusal, is the reference's. A raw `LogosInt & i64` has no operator.
5233                let is_bitwise = matches!(
5234                    op,
5235                    BinaryOpKind::Shl
5236                        | BinaryOpKind::Shr
5237                        | BinaryOpKind::BitAnd
5238                        | BinaryOpKind::BitOr
5239                        | BinaryOpKind::BitXor
5240                );
5241                let promotes = |e: &Expr| {
5242                    mentions_bigint_var(e, variable_types) || !emits_pure_i64(e, ecx)
5243                };
5244                let int_operand = |e: &Expr, ty: &str| {
5245                    ty == "i64" || mentions_bigint_var(e, variable_types)
5246                };
5247                if is_bitwise
5248                    && int_operand(left, left_type)
5249                    && int_operand(right, right_type)
5250                    && (promotes(left) || promotes(right))
5251                {
5252                    if let Some(dual) =
5253                        try_guarded_bitwise(*op, op_str, left, right, ecx, &promotes)
5254                    {
5255                        return dual;
5256                    }
5257                    let exact = ExprCtx {
5258                        int_exact_tolerant: true,
5259                        ..*ecx
5260                    };
5261                    let l = codegen_expr_ctx(left, &exact);
5262                    let r = codegen_expr_ctx(right, &exact);
5263                    if matches!(op, BinaryOpKind::BitAnd) {
5264                        return format!("logos_band_exact({l}, {r})");
5265                    }
5266                    let refusal = match op {
5267                        BinaryOpKind::BitOr => "BITOR_OPERANDS",
5268                        BinaryOpKind::BitXor => "BITXOR_OPERANDS",
5269                        BinaryOpKind::Shl => "SHL_OPERANDS",
5270                        _ => "SHR_OPERANDS",
5271                    };
5272                    let word = |e: &Expr, code: String| {
5273                        if promotes(e) {
5274                            format!(
5275                                "logos_word_operand({code}, logicaffeine_data::failure::{refusal})"
5276                            )
5277                        } else {
5278                            code
5279                        }
5280                    };
5281                    return format!("({} {} {})", word(left, l), op_str, word(right, r));
5282                }
5283                if is_exactable
5284                    && (left_type == "i64" && right_type == "i64" || has_bigint_operand)
5285                    && !ecx.int_index_context
5286                {
5287                    let narrow = |e: String| {
5288                        if ecx.int_exact_tolerant {
5289                            e
5290                        } else {
5291                            format!("{}.expect_i64(\"Int\")", e)
5292                        }
5293                    };
5294                    // `/` and `%` by a NONZERO literal can never overflow i64
5295                    // (a remainder is bounded by the divisor; a quotient shrinks
5296                    // — the sole exception `i64::MIN / -1` is excluded) and can
5297                    // never divide by zero, so raw matches the interpreter and
5298                    // keeps the mod-pow2 strength reduction (`x % 1024 → x & 1023`)
5299                    // legible. A zero (or `-1` for `/`) literal falls through to
5300                    // the checked helper for the canonical loud error.
5301                    if let Expr::Literal(Literal::Number(d)) = right {
5302                        let safe_div = matches!(op, BinaryOpKind::Divide) && *d != 0 && *d != -1;
5303                        let safe_mod = matches!(op, BinaryOpKind::Modulo) && *d != 0;
5304                        // A promoted (`LogosInt`) dividend has no raw `/`/`%` operator and may exceed
5305                        // i64, so it must use the exact helper below rather than this raw fast-path —
5306                        // including a dividend whose own inner sub-op promotes (`emits_pure_i64`).
5307                        if (safe_div || safe_mod)
5308                            && !has_bigint_operand
5309                            && emits_pure_i64(left, ecx)
5310                        {
5311                            // The raw i64 `/`/`%` needs an i64 DIVIDEND. In a tolerant context `left_str` is
5312                            // a promoted `LogosInt` (no `Div<i64>`/`Rem<i64>`) — e.g. `(a + b) / 64` inside
5313                            // an exact op — so recompute the dividend as i64; the i64 result flows back into
5314                            // the enclosing exact op via `Into`. (The divisor `d` is a literal, always i64.)
5315                            let l = if ecx.int_exact_tolerant {
5316                                codegen_expr_ctx(
5317                                    left,
5318                                    &ExprCtx {
5319                                        int_exact_tolerant: false,
5320                                        ..*ecx
5321                                    },
5322                                )
5323                            } else {
5324                                left_str.clone()
5325                            };
5326                            return format!("({} {} {})", l, op_str, right_str);
5327                        }
5328                    }
5329                    if let (Expr::Literal(Literal::Number(a)), Expr::Literal(Literal::Number(b))) =
5330                        (left, right)
5331                    {
5332                        match const_exact_int(*op, *a, *b) {
5333                            Some(ConstExact::InRange) => {
5334                                return format!("({} {} {})", left_str, op_str, right_str);
5335                            }
5336                            Some(ConstExact::Promoted(lit)) => return narrow(lit),
5337                            // A constant zero divisor falls to the runtime
5338                            // helper: the loud canonical error, the interp's.
5339                            None => {}
5340                        }
5341                    } else if !has_bigint_operand
5342                        && oracle_proves_int_op_in_range(ecx, expr, *op, left, right)
5343                        && emits_pure_i64(left, ecx)
5344                        && emits_pure_i64(right, ecx)
5345                    {
5346                        // A raw `left op right` needs both sides to be i64. With a promoted operand
5347                        // (`LogosInt`, no arithmetic operators) the exact helper below is the only
5348                        // valid lowering, even when the result provably fits i64 — the Oracle can
5349                        // prove THIS sum in range while an inner sub-sum promotes (E0369 otherwise).
5350                        return format!("({} {} {})", left_str, op_str, right_str);
5351                    }
5352                    // A root-NARROWED op (non-tolerant, no promoted operand)
5353                    // has two register-shaped exact lowerings that skip the
5354                    // `LogosInt` round-trip entirely; a TOLERANT root must
5355                    // stay on the promoting chain so an oversized
5356                    // intermediate flows exact into the enclosing op.
5357                    if !ecx.int_exact_tolerant && !has_bigint_operand {
5358                        if let Some(fused) = try_fuse_narrowed_int_op(*op, left, right, ecx) {
5359                            return fused;
5360                        }
5361                        if let Some(dual) = try_guarded_dual_chain(*op, left, right, ecx) {
5362                            return dual;
5363                        }
5364                        if let Some(chain) = try_i128_chain(*op, left, right, ecx) {
5365                            return chain;
5366                        }
5367                    }
5368                    // By-reference bignum arithmetic (clone elision). A promoted (`LogosInt`)
5369                    // operand forces the exact helper — but `logos_*_exact(a, b)` takes its
5370                    // operands BY VALUE, so a reused bignum variable `.clone()`s its heap buffer
5371                    // every time purely to be passed. `LogosInt::{add,sub,mul}` are already
5372                    // `(&self, &LogosInt) -> LogosInt`, and `logos_mul_exact(a, b)` is DEFINED as
5373                    // `a.into().mul(&b.into())` — so the by-ref method is byte-identical (same
5374                    // overflow-promotion) minus the clone. A reused bignum var is BORROWED; an
5375                    // i64/temporary operand is bound once to a `LogosInt` and borrowed. `/`/`%`
5376                    // keep the helper (its loud zero-divisor panic has no by-ref method form).
5377                    if has_bigint_operand
5378                        && matches!(
5379                            op,
5380                            BinaryOpKind::Add | BinaryOpKind::Subtract | BinaryOpKind::Multiply
5381                        )
5382                        && crate::optimize::active_config()
5383                            .is_on(crate::optimization::Opt::BignumByRef)
5384                    {
5385                        crate::optimize::mark_fired(crate::optimization::Opt::BignumByRef);
5386                        let method = match op {
5387                            BinaryOpKind::Add => "add",
5388                            BinaryOpKind::Subtract => "sub",
5389                            BinaryOpKind::Multiply => "mul",
5390                            _ => unreachable!("guarded to Add/Subtract/Multiply"),
5391                        };
5392                        let mut prelude = String::new();
5393                        let l_place = bignum_operand_place(left, ecx, &names, &mut prelude);
5394                        let r_place = bignum_operand_place(right, ecx, &names, &mut prelude);
5395                        let core = format!("{}.{}(&{})", l_place, method, r_place);
5396                        let body = if prelude.is_empty() {
5397                            core
5398                        } else {
5399                            // Parenthesize a block so `.expect_i64(..)` (the non-tolerant narrow)
5400                            // never mis-parses it at statement position.
5401                            format!("({{ {}{} }})", prelude, core)
5402                        };
5403                        return narrow(body);
5404                    }
5405                    let helper = match op {
5406                        BinaryOpKind::Add => "logos_add_exact",
5407                        BinaryOpKind::Subtract => "logos_sub_exact",
5408                        BinaryOpKind::Multiply => "logos_mul_exact",
5409                        BinaryOpKind::Divide => "logos_div_exact",
5410                        BinaryOpKind::Modulo => "logos_rem_exact",
5411                        _ => unreachable!("is_exactable covers exactly these five"),
5412                    };
5413                    // Exactness flows DOWN the operand chain: intermediates stay
5414                    // `LogosInt` (Into-chained), narrowing happens once at the root.
5415                    let tol = ExprCtx {
5416                        int_exact_tolerant: true,
5417                        ..*ecx
5418                    };
5419                    let l = codegen_expr_ctx(left, &tol);
5420                    let r = codegen_expr_ctx(right, &tol);
5421                    return narrow(format!("{}({}, {})", helper, l, r));
5422                }
5423            }
5424
5425            format!("({} {} {})", left_str, op_str, right_str)
5426        }
5427
5428        Expr::Call { function, args } => {
5429            let func_name = names.ident(*function);
5430            let raw_name = names.raw(*function);
5431            // ★ THE TEXT `contains(haystack, needle)` BUILTIN. `xs contains v` — the OPERATOR form —
5432            // has always emitted `logos_contains`; the CALL form had no arm at all, so it fell
5433            // through to an ordinary call and emitted `contains(a, b)`, a free function that does
5434            // not exist in the generated crate. Any program asking whether a text holds something
5435            // produced Rust that would not build — including `web.lg`'s `isIntText`, which is what
5436            // every typed route parameter is validated with. One meaning, one emission.
5437            if raw_name == "contains" && args.len() == 2 {
5438                return format!(
5439                    "{}.logos_contains(&{})",
5440                    recurse!(&args[0]),
5441                    recurse!(&args[1])
5442                );
5443            }
5444            // ★ THE `format` BUILTIN renders a value exactly as `Show` prints it — the same
5445            // `show_string` interpolation holes use. It had no arm at all, so every `format(x)` the
5446            // guide teaches emitted a call to Rust's `format!` MACRO as a function and the program
5447            // did not build. A program that defines its own `format` keeps it (declarer wins).
5448            if raw_name == "format" && args.len() == 1 && !program_defines_function(*function) {
5449                return format!(
5450                    "logicaffeine_system::io::show_string(&({}))",
5451                    recurse!(&args[0])
5452                );
5453            }
5454            // `length(x)` and `copy(x)` are the call spellings of `length of x` and `copy of x`: each
5455            // emits exactly what its dedicated node emits. A program's own `length`/`copy` wins.
5456            if args.len() == 1 && !program_defines_function(*function) {
5457                let canonical = match raw_name {
5458                    "length" => Some(Expr::Length {
5459                        collection: args[0],
5460                    }),
5461                    "copy" => Some(Expr::Copy { expr: args[0] }),
5462                    _ => None,
5463                };
5464                if let Some(canonical) = canonical {
5465                    return recurse!(&canonical);
5466                }
5467            }
5468            // Native-width BIT INTRINSICS (the stdlib `bits` ops). The stdlib `rotateLeft`/
5469            // `rotateRight`/`reverseBits`/`reverseBytes` are width-parameterized and compile to a
5470            // masked LOGOS loop that LLVM will NOT recognize as a rotate/reverse. But with a
5471            // COMPILE-TIME native word width (8/16/32/64) the body is EXACTLY one Rust intrinsic —
5472            // `(x as uW).rotate_left(n)` / `.reverse_bits()` / `.swap_bytes()` — which LLVM lowers
5473            // to a single CPU instruction (ROL/ROR, bit-reverse, BSWAP). The rewrite is exact for
5474            // any correct rotate/reverse (their meaning at a fixed native width is universal), and
5475            // is matched by stdlib name + arity + native-width literal, like the other name-keyed
5476            // builtins (`contains`, `wordN`). A non-native or non-literal width falls through to
5477            // the general stdlib call unchanged.
5478            if crate::optimize::active_config().is_on(crate::optimization::Opt::BitIntrinsics)
5479                && crate::loader::is_library_function(raw_name)
5480            {
5481                let width_of = |a: &Expr| -> Option<i64> {
5482                    if let Expr::Literal(Literal::Number(w)) = a {
5483                        if matches!(*w, 8 | 16 | 32 | 64) {
5484                            return Some(*w);
5485                        }
5486                    }
5487                    None
5488                };
5489                let fired = || crate::optimize::mark_fired(crate::optimization::Opt::BitIntrinsics);
5490                match (raw_name, args.len()) {
5491                    ("rotateLeft", 3) | ("rotateRight", 3) => {
5492                        if let Some(w) = width_of(args[2]) {
5493                            fired();
5494                            let m = if raw_name == "rotateLeft" {
5495                                "rotate_left"
5496                            } else {
5497                                "rotate_right"
5498                            };
5499                            return format!(
5500                                "(({} as u{w}).{}(({}) as u32) as i64)",
5501                                recurse!(&args[0]),
5502                                m,
5503                                recurse!(&args[1])
5504                            );
5505                        }
5506                    }
5507                    ("reverseBits", 2) => {
5508                        if let Some(w) = width_of(args[1]) {
5509                            fired();
5510                            return format!(
5511                                "(({} as u{w}).reverse_bits() as i64)",
5512                                recurse!(&args[0])
5513                            );
5514                        }
5515                    }
5516                    ("reverseBytes", 2) => {
5517                        if let Some(w) = width_of(args[1]) {
5518                            fired();
5519                            return format!(
5520                                "(({} as u{w}).swap_bytes() as i64)",
5521                                recurse!(&args[0])
5522                            );
5523                        }
5524                    }
5525                    _ => {}
5526                }
5527            }
5528            let args_str: Vec<String> = call_arguments(*function, args, ecx);
5529            // Builtin math functions → Rust method call syntax
5530            match raw_name {
5531                // stdlib `indexOf`/`countSub` (Text substring search) → the
5532                // `memchr` crate's SIMD `memmem` (a vectorized skip-loop that
5533                // beats glibc `strstr` and Rust's std two-way `str::find`). The
5534                // byte-indexed 1-based result and non-overlapping count are
5535                // identical to the pure-LOGOS body (so the tier differential
5536                // holds); empty needle is guarded to match its `0` return, and a
5537                // String identifier is borrowed (not cloned) so a large haystack
5538                // is not copied on every call. (`build.rs` injects the `memchr`
5539                // dep when the generated code names it.)
5540                "indexOf" | "countSub" if args_str.len() == 2 && crate::loader::is_library_function(raw_name) => {
5541                    let mut decl = String::new();
5542                    let hv = if let Expr::Identifier(sym) = &args[0] {
5543                        format!("&{}", names.ident(*sym))
5544                    } else {
5545                        decl.push_str(&format!("let __ho = ({}).to_string(); ", args_str[0]));
5546                        "&__ho".to_string()
5547                    };
5548                    let nv = if let Expr::Identifier(sym) = &args[1] {
5549                        format!("&{}", names.ident(*sym))
5550                    } else {
5551                        decl.push_str(&format!("let __no = ({}).to_string(); ", args_str[1]));
5552                        "&__no".to_string()
5553                    };
5554                    let op = if raw_name == "indexOf" {
5555                        // glibc `strstr`'s strategy — a single-byte SIMD prefilter
5556                        // on the needle's first byte + a `starts_with` verify — but
5557                        // with the `memchr` crate's scanner (the one behind ripgrep,
5558                        // which beats glibc's own memchr). One memory sweep, no
5559                        // two-byte-prefilter overhead of `memmem::find`.
5560                        "if __n.is_empty() { 0i64 } else { let __hb = __h.as_bytes(); let __nb = __n.as_bytes(); let __m = __nb.len(); if __m > __hb.len() { 0i64 } else { let __f = __nb[0]; let __last = __hb.len() - __m; let mut __o = 0usize; let mut __r = 0i64; while __o <= __last { match memchr::memchr(__f, &__hb[__o..=__last]) { Some(__p) => { let __i = __o + __p; if __hb[__i..].starts_with(__nb) { __r = __i as i64 + 1; break; } __o = __i + 1; } None => break, } } __r } }"
5561                    } else {
5562                        // Non-overlapping count: `memmem::find_iter` builds ONE
5563                        // Finder and iterates it (no per-match setup), which a
5564                        // hand-rolled per-match `memchr` cannot match when the
5565                        // needle is frequent (a match every few bytes).
5566                        "if __n.is_empty() { 0i64 } else { memchr::memmem::find_iter(__h.as_bytes(), __n.as_bytes()).count() as i64 }"
5567                    };
5568                    format!("{{ {}let __h: &str = {}; let __n: &str = {}; {} }}", decl, hv, nv, op)
5569                }
5570                "sqrt" if args_str.len() == 1 && is_complexf_expr(&args[0], variable_types, interner) => {
5571                    // Complex sqrt (`√(3+4i)=2+i`) — a `LogosComplexF`, via the real-sqrt formula.
5572                    format!("({}).sqrt()", args_str[0])
5573                }
5574                "sqrt" if args_str.len() == 1 => {
5575                    format!("(({}) as f64).sqrt()", args_str[0])
5576                }
5577                "conjugate"
5578                    if args_str.len() == 1
5579                        && (is_complexf_expr(&args[0], variable_types, interner)
5580                            || is_complex_expr(&args[0], variable_types, interner)) =>
5581                {
5582                    // Conjugate of a complex (exact `LogosComplex` or float `LogosComplexF`) — the same
5583                    // `.conjugate()` method negates the imaginary part on both.
5584                    format!("({}).conjugate()", args_str[0])
5585                }
5586                "conjugate" if args_str.len() == 1 => {
5587                    // A real number is its own conjugate — emit it unchanged.
5588                    format!("({})", args_str[0])
5589                }
5590                "re" if args_str.len() == 1
5591                    && (is_complexf_expr(&args[0], variable_types, interner)
5592                        || is_complex_expr(&args[0], variable_types, interner)) =>
5593                {
5594                    format!("({}).re()", args_str[0])
5595                }
5596                "re" if args_str.len() == 1 => {
5597                    // A real number IS its real part.
5598                    format!("(({}) as f64)", args_str[0])
5599                }
5600                "im" if args_str.len() == 1
5601                    && (is_complexf_expr(&args[0], variable_types, interner)
5602                        || is_complex_expr(&args[0], variable_types, interner)) =>
5603                {
5604                    format!("({}).im()", args_str[0])
5605                }
5606                "im" if args_str.len() == 1 => {
5607                    // A real number has zero imaginary part.
5608                    let _ = &args_str[0];
5609                    "0f64".to_string()
5610                }
5611                // `{k: v, …}` map literal — flat pairs into an insertion-ordered
5612                // LogosMap (block expression; `insert` takes `&self`).
5613                "mapOf" if !args_str.is_empty() && args_str.len() % 2 == 0 => {
5614                    let mut s = String::from("{ let __map_lit = LogosMap::new(); ");
5615                    for pair in args_str.chunks(2) {
5616                        s.push_str(&format!("__map_lit.insert({}, {}); ", pair[0], pair[1]));
5617                    }
5618                    s.push_str("__map_lit }");
5619                    s
5620                }
5621                // `repeatSeq(x, n)` — the `n copies of x` fill: n independent
5622                // `fill_clone` slots (the element evaluates once).
5623                "repeatSeq" if args_str.len() == 2 => {
5624                    format!(
5625                        "{{ let __rp_x = ({}); let __rp_n = (({}) as i64).max(0) as usize; \
5626                         let mut __rp = Vec::with_capacity(__rp_n); \
5627                         for _ in 0..__rp_n {{ __rp.push(__rp_x.fill_clone()); }} \
5628                         LogosSeq::from_vec(__rp) }}",
5629                        args_str[0], args_str[1]
5630                    )
5631                }
5632                // `{a, b, …}` set literal — elements into the Set repr
5633                // (hash-set semantics: dedup by value equality).
5634                "setOf" if !args_str.is_empty() => {
5635                    let mut s = String::from("{ let mut __set_lit = Set::default(); ");
5636                    for a in &args_str {
5637                        s.push_str(&format!("__set_lit.insert({}); ", a));
5638                    }
5639                    s.push_str("__set_lit }");
5640                    s
5641                }
5642                // Exact base-10: `decimal_of` takes the argument by its Rust type (Text is read, an Int
5643                // widens, a Decimal is itself, any other kind fails with the engines' sentence).
5644                "decimal" if args_str.len() == 1 => {
5645                    format!("logicaffeine_data::decimal_of({})", args_str[0])
5646                }
5647                // Complex `re + im·i`: a float part makes it a floating-point `LogosComplexF` (has a
5648                // `sqrt`); two exact reals stay an exact `LogosComplex` (integers embed as `n/1`).
5649                "complex" if args_str.len() == 2 => {
5650                    if complex_call_is_float(args, variable_types, interner) {
5651                        format!("LogosComplexF::new(({}) as f64, ({}) as f64)", args_str[0], args_str[1])
5652                    } else {
5653                        let re = rational_operand(&args[0], &args_str[0], variable_types);
5654                        let im = rational_operand(&args[1], &args_str[1], variable_types);
5655                        format!("LogosComplex::new({}, {})", re, im)
5656                    }
5657                }
5658                // A ℤ/nℤ element from a value and a modulus (both integers).
5659                "modular" if args_str.len() == 2 => {
5660                    format!("LogosModular::new(({}) as i64, ({}) as i64)", args_str[0], args_str[1])
5661                }
5662                // A dimensioned quantity from an exact magnitude and a unit name (`quantity(2, "inch")`).
5663                // The magnitude rides the rational tower (integers embed as `n/1`), so it never truncates.
5664                "quantity" if args_str.len() == 2 => {
5665                    let mag = rational_operand(&args[0], &args_str[0], variable_types);
5666                    format!("LogosQuantity::from_rational({}, &({}).to_string())", mag, args_str[1])
5667                }
5668                // Re-express a quantity in another unit of the same dimension (`convert(q, "foot")`).
5669                "convert" if args_str.len() == 2 => {
5670                    format!("({}).convert(&({}).to_string())", args_str[0], args_str[1])
5671                }
5672                // Construct money: a Decimal amount → `LogosMoney::of`, an Int amount → `from_i64`.
5673                "money" if args_str.len() == 2 => {
5674                    if is_decimal_expr(&args[0], variable_types, interner) {
5675                        let amt = decimal_operand(&args[0], &args_str[0], variable_types, interner);
5676                        format!("LogosMoney::of({}, &({}).to_string())", amt, args_str[1])
5677                    } else {
5678                        format!("LogosMoney::from_i64({}, &({}).to_string())", args_str[0], args_str[1])
5679                    }
5680                }
5681                // UUID — parse, the two special ids, the well-known namespaces, name-based v3/v5, and
5682                // the version accessor. All lower to `LogosUuid` associated functions.
5683                "uuid" if args_str.len() == 1 => {
5684                    format!("LogosUuid::parse(&({}).to_string())", args_str[0])
5685                }
5686                "uuid_nil" if args_str.is_empty() => "LogosUuid::nil()".to_string(),
5687                "uuid_max" if args_str.is_empty() => "LogosUuid::max()".to_string(),
5688                "uuid_dns" if args_str.is_empty() => "LogosUuid::namespace_dns()".to_string(),
5689                "uuid_url" if args_str.is_empty() => "LogosUuid::namespace_url()".to_string(),
5690                "uuid_oid" if args_str.is_empty() => "LogosUuid::namespace_oid()".to_string(),
5691                "uuid_x500" if args_str.is_empty() => "LogosUuid::namespace_x500()".to_string(),
5692                "uuid_version" if args_str.len() == 1 => format!("({}).version()", args_str[0]),
5693                // Byte-level primitives backing the Logos-written uuid.lg constructors. (`md5`/`sha1`/
5694                // `uuid_v3`/`uuid_v5` are Logos stdlib functions now, emitted as normal calls.)
5695                // Both builtins only BORROW their argument (`&…`), so a bare identifier needs no
5696                // `.clone()` — the identifier emitter adds one for non-Copy values, which here is a
5697                // full O(n) copy of the source text / byte-list on every call for nothing.
5698                "text_bytes" if args_str.len() == 1 => match args[0] {
5699                    Expr::Identifier(sym) => format!("text_bytes(&{})", names.ident(*sym)),
5700                    _ => format!("text_bytes(&({}))", args_str[0]),
5701                },
5702                "text_from_bytes" if args_str.len() == 1 => match args[0] {
5703                    // Write-side byte builder (Opt::TextFromBytesBuilder): `out` is already a
5704                    // `Vec<u8>`, so validate once and move it into the String — no `Vec<i64>`
5705                    // detour, no `i64`->`u8` rebuild. Same trap as the runtime on invalid UTF-8.
5706                    Expr::Identifier(sym) if variable_types.get(sym).map_or(false, |t| t == "ByteBuilder") =>
5707                        format!("String::from_utf8({}).unwrap_or_else(|e| panic!(\"{{}}\", logicaffeine_data::failure::invalid_utf8(e)))", names.ident(*sym)),
5708                    Expr::Identifier(sym) => format!("text_from_bytes(&{})", names.ident(*sym)),
5709                    _ => format!("text_from_bytes(&({}))", args_str[0]),
5710                },
5711                // A file's raw bytes as a `Seq of Int` (the `readBytes` builtin — serving a
5712                // `.wasm`/image from a handler). Mirrors the interpreter: a failed read is a
5713                // LOGOS runtime error carrying the same `readBytes: cannot read …` message,
5714                // never a silent empty Seq.
5715                // The total byte reader: a `Result` VALUE rather than a `panic!`. A LOGOS
5716                // `Result` is Rust's own `Result` on this tier — `file::read` has always answered
5717                // that way — so an `Inspect` over it lowers with the machinery already there.
5718                //
5719                // ★ IT CALLS THE SAME FUNCTION THE INTERPRETER DOES, which is the point: the read
5720                // AND its error wording live once, in `logicaffeine_system::file::read_bytes`. Two
5721                // `std::fs::read` calls with two hand-written format strings is how a message comes
5722                // to differ between the tier an author tests on and the tier they ship.
5723                "tryReadBytes" if args_str.len() == 1 => {
5724                    format!("match logicaffeine_system::file::read_bytes(({}).to_string()) {{ Ok(__b) => Ok(LogosSeq::from_vec(__b.iter().map(|&__x| __x as i64).collect())), Err(__e) => Err(__e) }}", args_str[0])
5725                }
5726                // The read and its refusals live once, in `logicaffeine_system::file::read_reals`, which the
5727                // interpreter calls too.
5728                "readReals" if args_str.len() == 1 => {
5729                    format!("match logicaffeine_system::file::read_reals(({}).to_string()) {{ Ok(__r) => LogosSeq::from_vec(__r), Err(__e) => panic!(\"{{}}\", __e) }}", args_str[0])
5730                }
5731                "readBytes" if args_str.len() == 1 => {
5732                    format!("{{ let __p = ({}).to_string(); match std::fs::read(&__p) {{ Ok(__b) => LogosSeq::from_vec(__b.iter().map(|&__x| __x as i64).collect()), Err(__e) => panic!(\"{{}}\", logicaffeine_data::failure::cannot_read_bytes(&__p, __e)) }} }}", args_str[0])
5733                }
5734                "readWireProgram" if args_str.is_empty() => {
5735                    "{ use std::io::Read as _; logicaffeine_system::io::flush_stdout(); let mut __len = [0u8; 4]; if std::io::stdin().read_exact(&mut __len).is_err() { std::process::exit(0); } let __n = u32::from_le_bytes(__len) as usize; let mut __wb = vec![0u8; __n]; std::io::stdin().read_exact(&mut __wb).expect(\"readWireProgram: frame\"); <CProgram as logicaffeine_data::wire::WireDecode>::wire_decode(&__wb, &mut 0usize).expect(\"readWireProgram: decode\") }".to_string()
5736                }
5737                "writeWireResidual" if args_str.len() == 1 => {
5738                    format!("{{ use std::io::Write as _; logicaffeine_system::io::flush_stdout(); let __s: String = ({}).into(); let __b = __s.as_bytes(); let __o = std::io::stdout(); let mut __h = __o.lock(); __h.write_all(&(__b.len() as u32).to_le_bytes()).unwrap(); __h.write_all(__b).unwrap(); __h.flush().unwrap(); __b.len() as i64 }}", args_str[0])
5739                }
5740                "uuid_bytes" if args_str.len() == 1 => format!("({}).byte_seq()", args_str[0]),
5741                "uuid_from_bytes" if args_str.len() == 1 => {
5742                    format!("LogosUuid::from_byte_seq(&({}))", args_str[0])
5743                }
5744                // `chr(code)` → a one-char String (the char code → text; used building the canonical
5745                // UUID hex in Logos). Fully qualified — it lives in the `text` submodule, not the glob.
5746                "chr" if args_str.len() == 1 => {
5747                    format!("logicaffeine_system::text::chr(({}) as i64)", args_str[0])
5748                }
5749                // `parseInt`/`parseFloat(text)` → i64/f64. Like `chr`, they live in the `text`
5750                // submodule (not the crate-root glob), so the call MUST be fully qualified — a bare
5751                // `parseFloat(..)` fails to resolve (E0425) and poisons any spliced stdlib module
5752                // that uses it. `.to_string()` normalizes the argument to the `String` the runtime
5753                // takes, whether it arrives as a `&str`, a `String`, or an interpolated `format!`.
5754                "parseInt" if args_str.len() == 1 => {
5755                    format!("logicaffeine_system::text::parseInt(({}).to_string())", args_str[0])
5756                }
5757                "parseFloat" if args_str.len() == 1 => {
5758                    format!("logicaffeine_system::text::parseFloat(({}).to_string())", args_str[0])
5759                }
5760                // Parse an RFC 3339 timestamp into a `LogosMoment` (delegates to base::temporal).
5761                "parse_timestamp" if args_str.len() == 1 => {
5762                    format!("LogosMoment::parse_rfc3339(&({}).to_string())", args_str[0])
5763                }
5764                // Render a `LogosMoment` as an RFC 3339 string.
5765                "format_timestamp" if args_str.len() == 1 => {
5766                    format!("({}).format_rfc3339()", args_str[0])
5767                }
5768                // UTC calendar component extractors on a `LogosMoment`.
5769                "year_of" if args_str.len() == 1 => format!("({}).year()", args_str[0]),
5770                "month_of" if args_str.len() == 1 => format!("({}).month()", args_str[0]),
5771                "day_of" if args_str.len() == 1 => format!("({}).day()", args_str[0]),
5772                "weekday_of" if args_str.len() == 1 => format!("({}).weekday()", args_str[0]),
5773                "hour_of" if args_str.len() == 1 => format!("({}).hour()", args_str[0]),
5774                "minute_of" if args_str.len() == 1 => format!("({}).minute()", args_str[0]),
5775                "second_of" if args_str.len() == 1 => format!("({}).second()", args_str[0]),
5776                // The ISO-8601 week number (1..=53) of the Moment/Date.
5777                "week_of" if args_str.len() == 1 => format!("({}).iso_week()", args_str[0]),
5778                // The calendar quarter (1..=4) of the Moment/Date.
5779                "quarter_of" if args_str.len() == 1 => format!("({}).quarter()", args_str[0]),
5780                // The calendar day (a `LogosDate`) the Moment falls on.
5781                "date_of" if args_str.len() == 1 => format!("({}).date()", args_str[0]),
5782                // The wall-clock time-of-day (a `LogosTime`) of the Moment.
5783                "time_of" if args_str.len() == 1 => format!("({}).time_of_day()", args_str[0]),
5784                // Construct a `LogosDate`/`LogosMoment` from civil components (base `days_from_civil`).
5785                "makeDate" if args_str.len() == 3 => format!(
5786                    "LogosDate::from_ymd({}, {}, {})",
5787                    args_str[0], args_str[1], args_str[2]
5788                ),
5789                "makeMoment" if args_str.len() == 6 => format!(
5790                    "LogosMoment::from_ymd({}, {}, {}, {}, {}, {})",
5791                    args_str[0], args_str[1], args_str[2], args_str[3], args_str[4], args_str[5]
5792                ),
5793                // Moment arithmetic.
5794                "seconds_between" if args_str.len() == 2 => {
5795                    format!("({}).seconds_until(&({}))", args_str[0], args_str[1])
5796                }
5797                "months_between" if args_str.len() == 2 => {
5798                    format!("({}).months_until(&({}))", args_str[0], args_str[1])
5799                }
5800                "years_between" if args_str.len() == 2 => {
5801                    format!("({}).years_until(&({}))", args_str[0], args_str[1])
5802                }
5803                "add_seconds" if args_str.len() == 2 => {
5804                    format!("({}).add_seconds({})", args_str[0], args_str[1])
5805                }
5806                "in_zone" if args_str.len() == 2 => {
5807                    format!("({}).in_zone(&({}).to_string())", args_str[0], args_str[1])
5808                }
5809                "local_instant" if args_str.len() == 2 => {
5810                    format!("({}).local_instant(&({}).to_string())", args_str[0], args_str[1])
5811                }
5812                // SHA-1 SHA-NI lane (`Lanes4Word32` = one `__m128i`): pack/unpack + the four SHA ops,
5813                // which lower to the `sha1rnds4`/`sha1msg1/2`/`sha1nexte` hardware instructions.
5814                "lanes4Word32" if args_str.len() == 1 => {
5815                    format!("lanes4_word32(&({}))", args_str[0])
5816                }
5817                "lanes4Of" if args_str.len() == 4 => {
5818                    format!("lanes4_of({}, {}, {}, {})", args_str[0], args_str[1], args_str[2], args_str[3])
5819                }
5820                // Byte-shuffle lane (`Lanes16Word8`): pshufb + per-byte shift + interleaves — the SIMD
5821                // hex codec written in Logos lowers to these.
5822                "lanes16Word8" if args_str.len() == 1 => format!("lanes16_word8(&({}))", args_str[0]),
5823                "seqOfLanes16W8" if args_str.len() == 1 => format!("seq_of_lanes16w8({})", args_str[0]),
5824                "splat16Word8" if args_str.len() == 1 => format!("splat16_word8({})", args_str[0]),
5825                "shuffle16" if args_str.len() == 2 => {
5826                    format!("shuffle16({}, {})", args_str[0], args_str[1])
5827                }
5828                "shrBytes16" if args_str.len() == 2 => {
5829                    format!("shr_bytes16({}, {})", args_str[0], args_str[1])
5830                }
5831                "interleaveLo16" if args_str.len() == 2 => {
5832                    format!("interleave_lo16({}, {})", args_str[0], args_str[1])
5833                }
5834                "interleaveHi16" if args_str.len() == 2 => {
5835                    format!("interleave_hi16({}, {})", args_str[0], args_str[1])
5836                }
5837                "byteAdd16" if args_str.len() == 2 => {
5838                    format!("byte_add16({}, {})", args_str[0], args_str[1])
5839                }
5840                "maddubs16" if args_str.len() == 2 => {
5841                    format!("maddubs16({}, {})", args_str[0], args_str[1])
5842                }
5843                "packus16" if args_str.len() == 2 => {
5844                    format!("packus16({}, {})", args_str[0], args_str[1])
5845                }
5846                "seqOfLanes4W32" if args_str.len() == 1 => {
5847                    format!("seq_of_lanes4w32({})", args_str[0])
5848                }
5849                "sha1rnds4" if args_str.len() == 3 => {
5850                    format!("sha1rnds4({}, {}, {})", args_str[0], args_str[1], args_str[2])
5851                }
5852                "sha1msg1" if args_str.len() == 2 => {
5853                    format!("sha1msg1({}, {})", args_str[0], args_str[1])
5854                }
5855                "sha1msg2" if args_str.len() == 2 => {
5856                    format!("sha1msg2({}, {})", args_str[0], args_str[1])
5857                }
5858                "sha1nexte" if args_str.len() == 2 => {
5859                    format!("sha1nexte({}, {})", args_str[0], args_str[1])
5860                }
5861                // SIMD lane vector: pack a Seq of Word32 into one `__m256i`, or read its lanes back.
5862                "lanes8Word32" if args_str.len() == 1 => {
5863                    format!("lanes8_word32(&({}))", args_str[0])
5864                }
5865                "seqOfLanes8" if args_str.len() == 1 => {
5866                    format!("seq_of_lanes8({})", args_str[0])
5867                }
5868                "splat8Word32" if args_str.len() == 1 => {
5869                    format!("splat8_word32({})", args_str[0])
5870                }
5871                "intOfWord32" if args_str.len() == 1 => {
5872                    format!("int_of_word32({})", args_str[0])
5873                }
5874                "intOfWord64" if args_str.len() == 1 => {
5875                    format!("int_of_word64({})", args_str[0])
5876                }
5877                "word64Shl" if args_str.len() == 2 => {
5878                    format!("word64_shl({}, {})", args_str[0], args_str[1])
5879                }
5880                "word64Shr" if args_str.len() == 2 => {
5881                    format!("word64_shr({}, {})", args_str[0], args_str[1])
5882                }
5883                "word32Shr" if args_str.len() == 2 => {
5884                    format!("word32_shr({}, {})", args_str[0], args_str[1])
5885                }
5886                "word64And" if args_str.len() == 2 => {
5887                    format!("word64_and({}, {})", args_str[0], args_str[1])
5888                }
5889                "word16" if args_str.len() == 1 => {
5890                    format!("word16({})", args_str[0])
5891                }
5892                "intOfWord16" if args_str.len() == 1 => {
5893                    format!("int_of_word16({})", args_str[0])
5894                }
5895                "word8" if args_str.len() == 1 => {
5896                    format!("word8({})", args_str[0])
5897                }
5898                "intOfWord8" if args_str.len() == 1 => {
5899                    format!("int_of_word8({})", args_str[0])
5900                }
5901                "lanes4Word64" if args_str.len() == 1 => {
5902                    format!("lanes4_word64(&({}))", args_str[0])
5903                }
5904                "seqOfLanes4" if args_str.len() == 1 => {
5905                    format!("seq_of_lanes4({})", args_str[0])
5906                }
5907                "mul32x32to64" if args_str.len() == 2 => {
5908                    format!("mul32x32to64({}, {})", args_str[0], args_str[1])
5909                }
5910                "hsumLanes4" if args_str.len() == 1 => {
5911                    format!("hsum_lanes4({})", args_str[0])
5912                }
5913                "splat4Word64" if args_str.len() == 1 => {
5914                    format!("splat4_word64({})", args_str[0])
5915                }
5916                "andNot4" if args_str.len() == 2 => {
5917                    format!("and_not4({}, {})", args_str[0], args_str[1])
5918                }
5919                "lanes16Word16" if args_str.len() == 1 => {
5920                    format!("lanes16_word16(&({}))", args_str[0])
5921                }
5922                "seqOfLanes16" if args_str.len() == 1 => {
5923                    format!("seq_of_lanes16({})", args_str[0])
5924                }
5925                "splat16Word16" if args_str.len() == 1 => {
5926                    format!("splat16_word16({})", args_str[0])
5927                }
5928                "mulhi16" if args_str.len() == 2 => {
5929                    format!("mulhi16({}, {})", args_str[0], args_str[1])
5930                }
5931                "montmul32" if args_str.len() == 4 => {
5932                    format!("montmul32({}, {}, {}, {})", args_str[0], args_str[1], args_str[2], args_str[3])
5933                }
5934                // Method calls so Rust resolves the right lane impl by type (Lanes16Word16 i16 NTT
5935                // strides 8/4/2; Lanes8Word32 i32 NTT strides 4/2/1).
5936                "nttBcastLo" if args_str.len() == 2 => {
5937                    format!("({}).ntt_bcast_lo(({}) as usize)", args_str[0], args_str[1])
5938                }
5939                "nttBcastHi" if args_str.len() == 2 => {
5940                    format!("({}).ntt_bcast_hi(({}) as usize)", args_str[0], args_str[1])
5941                }
5942                "nttBlend" if args_str.len() == 3 => {
5943                    format!("({}).ntt_blend({}, ({}) as usize)", args_str[0], args_str[1], args_str[2])
5944                }
5945                // Modular exponentiation: `pow(m, e)` where the base is a ℤ/nℤ element.
5946                "pow" if args_str.len() == 2 && is_modular_expr(&args[0], variable_types, interner) => {
5947                    format!("({}).pow(({}) as u64)", args_str[0], args_str[1])
5948                }
5949                // A Rational argument takes the EXACT path (BigInt num/den), never a
5950                // lossy `as f64`: `|·|` stays rational; floor/ceil/round give the exact Int.
5951                "abs" if args_str.len() == 1 && is_rational_expr(&args[0], variable_types) => {
5952                    format!("({}).abs()", args_str[0])
5953                }
5954                "floor" if args_str.len() == 1 && is_rational_expr(&args[0], variable_types) => {
5955                    format!("({}).floor()", args_str[0])
5956                }
5957                "ceil" if args_str.len() == 1 && is_rational_expr(&args[0], variable_types) => {
5958                    format!("({}).ceil()", args_str[0])
5959                }
5960                "round" if args_str.len() == 1 && is_rational_expr(&args[0], variable_types) => {
5961                    format!("({}).round()", args_str[0])
5962                }
5963                // |z| of an EXACT complex (`LogosComplex`, e.g. `complex(3, 4)`) is its `f64` modulus.
5964                // `LogosComplex` has no `abs()`; it delegates to the wrapped `Complex::abs_f64`, which is
5965                // exactly what the interpreter's `abs(Complex)` returns (`Float(c.abs_f64())`).
5966                "abs" if args_str.len() == 1 && is_complex_expr(&args[0], variable_types, interner) => {
5967                    format!("({}).abs_f64()", args_str[0])
5968                }
5969                // |z| of a float-complex is its `f64` modulus.
5970                "abs" if args_str.len() == 1 && is_complexf_expr(&args[0], variable_types, interner) => {
5971                    format!("({}).abs()", args_str[0])
5972                }
5973                "abs" if args_str.len() == 1 => {
5974                    let arg_type = infer_numeric_type(&args[0], interner, variable_types);
5975                    if arg_type == "f64" {
5976                        format!("(({}) as f64).abs()", args_str[0])
5977                    } else {
5978                        format!("(({}) as i64).abs()", args_str[0])
5979                    }
5980                }
5981                "floor" if args_str.len() == 1 => {
5982                    format!("((({}) as f64).floor() as i64)", args_str[0])
5983                }
5984                "ceil" if args_str.len() == 1 => {
5985                    format!("((({}) as f64).ceil() as i64)", args_str[0])
5986                }
5987                "round" if args_str.len() == 1 => {
5988                    format!("((({}) as f64).round() as i64)", args_str[0])
5989                }
5990                "pow" if args_str.len() == 2 => {
5991                    format!("((({}) as f64).powf(({}) as f64))", args_str[0], args_str[1])
5992                }
5993                method @ ("min" | "max") if args_str.len() == 2 => {
5994                    // A Real on either side makes the whole call Real, as the VM promotes it: both
5995                    // operands widen to f64, and the language's own `min`/`max` of reals decides the
5996                    // sign of equal zeros and a NaN as the interpreter does.
5997                    let real = |e: &Expr| infer_numeric_type(e, interner, variable_types) == "f64";
5998                    if real(&args[0]) || real(&args[1]) {
5999                        format!(
6000                            "logicaffeine_data::logos_{}_f64(({}) as f64, ({}) as f64)",
6001                            method, args_str[0], args_str[1]
6002                        )
6003                    } else {
6004                        format!("({}).{}({})", args_str[0], method, args_str[1])
6005                    }
6006                }
6007                _ => {
6008                    let fish = super::instantiation::for_expr(expr);
6009                    let path = format!("{}{}", called_function_path(*function, func_name, variable_types), fish);
6010                    let suffix = if async_functions.contains(function) { ".await" } else { "" };
6011                    sequenced_call(&path, *function, args, args_str, suffix, variable_types)
6012                }
6013            }
6014        }
6015
6016        // Affine read-only array (deleted CSR offset array): `item k of A` is the
6017        // closed form `coeff * (k-1) + offset` — no load, no array. The 1-based→
6018        // 0-based `-1` cancels a `+1` in the index, so `item (v+1) of A` with
6019        // `A[p]=5*p` becomes `v * 5` (C's `v*MAX_EDGES`).
6020        Expr::Index {
6021            collection: Expr::Identifier(sym),
6022            index,
6023        } if affine_array_coeff_offset(variable_types.get(sym)).is_some() => {
6024            let (coeff, offset) = affine_array_coeff_offset(variable_types.get(sym)).unwrap();
6025            enum Pos {
6026                Const(i64),
6027                Expr(String),
6028            }
6029            let pos = match index {
6030                Expr::Literal(Literal::Number(n)) => Pos::Const(n - 1),
6031                Expr::BinaryOp {
6032                    op: BinaryOpKind::Add,
6033                    left,
6034                    right,
6035                } => match (left, right) {
6036                    (_, Expr::Literal(Literal::Number(1))) => Pos::Expr(recurse!(left)),
6037                    (Expr::Literal(Literal::Number(1)), _) => Pos::Expr(recurse!(right)),
6038                    (_, Expr::Literal(Literal::Number(k))) if *k > 1 => {
6039                        Pos::Expr(format!("({} + {})", recurse!(left), k - 1))
6040                    }
6041                    (Expr::Literal(Literal::Number(k)), _) if *k > 1 => {
6042                        Pos::Expr(format!("({} + {})", recurse!(right), k - 1))
6043                    }
6044                    _ => Pos::Expr(format!("(({}) - 1)", irecurse!(index))),
6045                },
6046                _ => Pos::Expr(format!("(({}) - 1)", irecurse!(index))),
6047            };
6048            match pos {
6049                Pos::Const(p) => format!("{}i64", coeff.wrapping_mul(p).wrapping_add(offset)),
6050                Pos::Expr(_) if coeff == 0 => format!("{}i64", offset),
6051                Pos::Expr(p) => {
6052                    let base = if coeff == 1 {
6053                        p
6054                    } else {
6055                        format!("(({}) * {})", p, coeff)
6056                    };
6057                    if offset == 0 {
6058                        base
6059                    } else {
6060                        format!("({} + {})", base, offset)
6061                    }
6062                }
6063            }
6064        }
6065
6066        // AoS interleaving: `item i of member` reads column `col` of the fused
6067        // backing's row `i` names. Adjacent columns are memory-adjacent, so LLVM
6068        // packs them (C's struct-array load).
6069        Expr::Index {
6070            collection: member @ Expr::Identifier(sym),
6071            index,
6072        } if parse_aos_tag(variable_types.get(sym)).is_some() => {
6073            let tag = parse_aos_tag(variable_types.get(sym)).unwrap();
6074            if range_proves_index(member, index) {
6075                let offset = proven_offset_str(index, ecx, variable_types, interner);
6076                format!("{}[{}][{}]", tag.backing, offset, tag.col)
6077            } else {
6078                let at = logos_index_str(index, ecx, variable_types, interner);
6079                let item = item_accessor(index, ecx.oracle, false);
6080                format!("{}.{}({})[{}]", tag.backing, item, at, tag.col)
6081            }
6082        }
6083
6084        Expr::Index { collection, index } => {
6085            let coll_str = recurse!(collection);
6086            // Direct indexing for known collection types (avoids trait dispatch)
6087            // Strip |__hl: hoisting suffix so type parsing (strip_suffix, etc.) works correctly.
6088            let known_type = if let Expr::Identifier(sym) = collection {
6089                variable_types
6090                    .get(sym)
6091                    .map(|s| s.split("|__hl:").next().unwrap_or(s.as_str()))
6092            } else {
6093                None
6094            };
6095            // HETEROGENEOUS-TUPLE element: a CONSTANT `item N of t`, where `t` is a marked tuple variable
6096            // (`Vec<Value> /* logos_tuple: … */`), reads the boxed `Value` at position N and UNBOXES it to
6097            // that position's scalar type — so `upper(item 2 of t)` gets a `String`, not a `Value`. Only
6098            // fires for a positive constant index into a marked tuple; every other collection/index is
6099            // unchanged (a `Value` result still works for `Show`, which takes any `Display`).
6100            if let Expr::Literal(Literal::Number(n)) = index {
6101                if *n >= 1 {
6102                    let tuple_type = known_type.map(str::to_string).or_else(|| {
6103                        record_field_rust_type(collection, interner, variable_types, ecx.registry)
6104                    });
6105                    if let Some(unbox) = tuple_type
6106                        .as_deref()
6107                        .and_then(|t| super::types::logos_tuple_elem_type(t, *n))
6108                        .and_then(super::types::logos_value_unbox_call)
6109                    {
6110                        return format!(
6111                            "logicaffeine_data::LogosIndex::logos_get(&{}, {}i64).{}",
6112                            coll_str, n, unbox
6113                        );
6114                    }
6115                }
6116            }
6117            match known_type {
6118                // A bit-packed `Seq of Bool` (`Opt::BitPack`): the bit an index names, read unchecked where the
6119                // oracle proves the index in range.
6120                Some("LogosBits") => {
6121                    if oracle_proves_index(ecx, collection, index) {
6122                        let offset = proven_offset_str(index, ecx, variable_types, interner);
6123                        format!("unsafe {{ {}.get_unchecked({}) }}", coll_str, offset)
6124                    } else {
6125                        let at = logos_index_str(index, ecx, variable_types, interner);
6126                        format!("{}.item({})", coll_str, at)
6127                    }
6128                }
6129                Some(t)
6130                    if t.starts_with("LogosSeq") || t.starts_with("Vec") || t == "TextBytes" =>
6131                {
6132                    // `TextBytes` is the zero-copy `&[u8]` view of a text's bytes (Opt::TextBytesView).
6133                    // `item i of sb` reads a `u8` from the borrowed slice and casts it back to the
6134                    // `i64` the rest of the program expects — no `Vec<i64>`, no `.borrow()`.
6135                    let owner = if t.starts_with("LogosSeq") {
6136                        format!("{}.borrow()", coll_str)
6137                    } else {
6138                        coll_str.clone()
6139                    };
6140                    let copy = t == "TextBytes" || has_copy_element_type(t);
6141                    let read = indexed_read(&owner, collection, index, copy, ecx);
6142                    // A byte view and a narrowed (`Vec<i32>`) sequence widen to the i64 the rest of the
6143                    // program expects (lossless).
6144                    if item_read_widens(t) {
6145                        format!("(({}) as i64)", read)
6146                    } else {
6147                        read
6148                    }
6149                }
6150                Some(t) if t.starts_with("&[") || t.starts_with("&mut [") || t.starts_with('[') => {
6151                    // A slice (&[T] / &mut [T]) or an O3 fixed array [T; N].
6152                    let elem = if t.starts_with('[') {
6153                        t.trim_start_matches('[').split("; ").next().unwrap_or("_")
6154                    } else {
6155                        t.strip_prefix("&mut [")
6156                            .or_else(|| t.strip_prefix("&["))
6157                            .and_then(|s| s.strip_suffix(']'))
6158                            .unwrap_or("_")
6159                    };
6160                    let copy = is_copy_type(elem);
6161                    let read = indexed_read(&coll_str, collection, index, copy, ecx);
6162                    // A narrowed slice (`&[i32]`/`&mut [i32]`, from a hoisted
6163                    // `Vec<i32>`) sign-extends to i64 (lossless).
6164                    if item_read_widens(t) {
6165                        format!("(({}) as i64)", read)
6166                    } else {
6167                        read
6168                    }
6169                }
6170                // A key the map does not hold fails with the one sentence naming it. `.get` borrows the
6171                // key, so a Text key is not moved.
6172                Some(t) if is_logos_map_type(t) => {
6173                    if let Some(probe) = super::probe::read(collection, index) {
6174                        return probe;
6175                    }
6176                    let index_str = irecurse!(index);
6177                    format!(
6178                        "{{ let __key = &({}); logicaffeine_data::failure::found({}.get(__key), __key) }}",
6179                        index_str, coll_str
6180                    )
6181                }
6182                Some(t)
6183                    if t.starts_with("std::collections::HashMap")
6184                        || t.starts_with("HashMap")
6185                        || t.starts_with("rustc_hash::FxHashMap")
6186                        || t.starts_with("FxHashMap") =>
6187                {
6188                    let index_str = irecurse!(index);
6189                    format!(
6190                        "{{ let __key = &({}); logicaffeine_data::failure::found({}.get(__key).cloned(), __key) }}",
6191                        index_str, coll_str
6192                    )
6193                }
6194                Some("String") => {
6195                    let index_str = irecurse!(index);
6196                    format!("LogosIndex::logos_get(&{}, {})", coll_str, index_str)
6197                }
6198                _ => {
6199                    let index_str = irecurse!(index);
6200                    format!("LogosIndex::logos_get(&{}, {})", coll_str, index_str)
6201                }
6202            }
6203        }
6204
6205        Expr::Slice {
6206            collection,
6207            start,
6208            end,
6209        } => {
6210            let coll_str = recurse!(collection);
6211            let bound = |e: &Expr| {
6212                super::rational::integer_operand(e, crate::semantics::collections::IntegerPlace::Slice, ecx)
6213                    .unwrap_or_else(|| recurse!(e))
6214            };
6215            let start_str = bound(start);
6216            let end_str = bound(end);
6217            // For LogosSeq, need to borrow the inner Vec first
6218            let known_type = sliced_type(collection, ecx);
6219            if matches!(known_type.as_deref(), Some(t) if t.starts_with("LogosSeq")) {
6220                format!(
6221                    "{}.borrow().logos_slice({}, {})",
6222                    coll_str, start_str, end_str
6223                )
6224            } else {
6225                format!("{}.logos_slice({}, {})", coll_str, start_str, end_str)
6226            }
6227        }
6228
6229        Expr::Copy { expr: inner } => {
6230            // Special case: Copy of Slice → the slice's items `.to_vec()`, wrapped in LogosSeq
6231            if let Expr::Slice {
6232                collection,
6233                start,
6234                end,
6235            } = inner
6236            {
6237                let coll_str = recurse!(collection);
6238                let bound = |e: &Expr| {
6239                    super::rational::integer_operand(e, crate::semantics::collections::IntegerPlace::Slice, ecx)
6240                        .unwrap_or_else(|| recurse!(e))
6241                };
6242                let start_str = bound(start);
6243                let end_str = bound(end);
6244                let known_type = sliced_type(collection, ecx);
6245                if matches!(known_type.as_deref(), Some(t) if t.starts_with("LogosSeq")) {
6246                    format!(
6247                        "LogosSeq::from_vec({}.borrow().logos_slice({}, {}).to_vec())",
6248                        coll_str, start_str, end_str
6249                    )
6250                } else if matches!(known_type.as_deref(), Some(t) if t.starts_with("&[") || t.starts_with("Vec<"))
6251                {
6252                    format!(
6253                        "LogosSeq::from_vec({}.logos_slice({}, {}).to_vec())",
6254                        coll_str, start_str, end_str
6255                    )
6256                } else {
6257                    format!(
6258                        "{}.logos_slice({}, {}).to_vec()",
6259                        coll_str, start_str, end_str
6260                    )
6261                }
6262            } else {
6263                // Check if the inner expression is a LogosSeq/LogosMap → deep_clone()
6264                let known_type = if let Expr::Identifier(sym) = inner {
6265                    variable_types
6266                        .get(sym)
6267                        .map(|s| s.split("|__hl:").next().unwrap_or(s.as_str()))
6268                } else {
6269                    None
6270                };
6271                let expr_str = recurse!(inner);
6272                if matches!(known_type, Some(t) if t.starts_with("Vec<")) {
6273                    // Slice variable stored as Vec<T> — wrap with LogosSeq::from_vec.
6274                    // One copy (.clone()) + zero-cost wrap, same as old pre-ref-semantics .to_vec().
6275                    format!("LogosSeq::from_vec({}.clone())", expr_str)
6276                } else if matches!(known_type, Some(t) if t.starts_with("&[")) {
6277                    format!("LogosSeq::from_vec({}.to_vec())", expr_str)
6278                } else if matches!(known_type, Some(t) if t.starts_with("LogosSeq") || t.starts_with("LogosMap"))
6279                {
6280                    format!("{}.deep_clone()", expr_str)
6281                } else {
6282                    format!("{}.to_owned()", expr_str)
6283                }
6284            }
6285        }
6286
6287        Expr::Give { value } => {
6288            // Ownership transfer: emit value without .clone()
6289            // The move semantics are implicit in Rust - no special syntax needed
6290            recurse!(value)
6291        }
6292
6293        // Affine read-only array: `length of A` is its trip count (the array is
6294        // deleted, so there is no `.len()` to read).
6295        Expr::Length {
6296            collection: Expr::Identifier(sym),
6297        } if affine_array_trip(variable_types.get(sym)).is_some() => {
6298            format!(
6299                "(({}) as i64)",
6300                affine_array_trip(variable_types.get(sym)).unwrap()
6301            )
6302        }
6303
6304        // AoS-interleaved member: its length is the backing's fixed row count.
6305        Expr::Length {
6306            collection: Expr::Identifier(sym),
6307        } if parse_aos_tag(variable_types.get(sym)).is_some() => {
6308            format!("{}i64", parse_aos_tag(variable_types.get(sym)).unwrap().len)
6309        }
6310
6311        Expr::Length { collection } => {
6312            if let Expr::Identifier(sym) = collection {
6313                if let Some(t) = variable_types.get(sym) {
6314                    if let Some(pos) = t.find("|__hl:") {
6315                        return t[pos + "|__hl:".len()..].to_string();
6316                    }
6317                }
6318            }
6319            let coll_str = recurse!(collection);
6320            // Phase 43D: Collection length - cast to i64 for LOGOS integer semantics
6321            format!("({}.len() as i64)", coll_str)
6322        }
6323
6324        Expr::Contains { collection, value } => {
6325            let coll_str = recurse!(collection);
6326            let val_str = recurse!(value);
6327            // Numeric-unified map key: a Float indexing an `Int`-keyed map coerces to its Int
6328            // (`1.0` → key `1`; a non-integral `1.5` matches nothing), mirroring the interpreter's
6329            // `1 == 1.0` key rule. An `i64`-keyed `logos_contains` otherwise rejects the `f64` operand.
6330            if let crate::analysis::types::LogosType::Map(k, _) =
6331                super::types::infer_logos_type(collection, interner, variable_types)
6332            {
6333                if matches!(*k, crate::analysis::types::LogosType::Int)
6334                    && super::types::infer_numeric_type(value, interner, variable_types) == "f64"
6335                {
6336                    return format!(
6337                        "logicaffeine_data::logos_i64_key_of_f64({}).map_or(false, |__k| {}.logos_contains(&__k))",
6338                        val_str, coll_str
6339                    );
6340                }
6341            }
6342            // Use LogosContains trait for unified contains across List, Set, Map, Text
6343            format!("{}.logos_contains(&{})", coll_str, val_str)
6344        }
6345
6346        Expr::Union { left, right } => {
6347            let left_str = recurse!(left);
6348            let right_str = recurse!(right);
6349            format!(
6350                "{}.union(&{}).cloned().collect::<Set<_>>()",
6351                left_str, right_str
6352            )
6353        }
6354
6355        Expr::Intersection { left, right } => {
6356            let left_str = recurse!(left);
6357            let right_str = recurse!(right);
6358            format!(
6359                "{}.intersection(&{}).cloned().collect::<Set<_>>()",
6360                left_str, right_str
6361            )
6362        }
6363
6364        // Phase 48: Sipping Protocol expressions
6365        Expr::ManifestOf { zone } => {
6366            let zone_str = recurse!(zone);
6367            format!(
6368                "logicaffeine_system::network::FileSipper::from_zone(&{}).manifest()",
6369                zone_str
6370            )
6371        }
6372
6373        Expr::ChunkAt { index, zone } => {
6374            let zone_str = recurse!(zone);
6375            let index_str = irecurse!(index);
6376            // LOGOS uses 1-indexed, Rust uses 0-indexed
6377            format!("logicaffeine_system::network::FileSipper::from_zone(&{}).get_chunk(({} - 1) as usize)", zone_str, index_str)
6378        }
6379
6380        Expr::List(ref items) => {
6381            // ★ A SEQUENCE LITERAL COPIES ITS ELEMENTS, and `vec![…]` MOVES whatever it names — so
6382            // a field read among its elements moves that field out of its record (`[c's env,
6383            // c's env]` could not build twice), and a variable named twice, or read again after
6384            // the literal, is used after its move. There is no callee signature to consult here,
6385            // so the test is the element's own type; when that is unknown the clone is owed
6386            // anyway, because ownership is not in doubt at this site the way it is at a call.
6387            // `give x` is the explicit move and stays one.
6388            //
6389            // `analysis/ownership.rs` has no `Expr::List` arm at all, so nothing upstream sees it.
6390            let item_strs: Vec<String> = items
6391                .iter()
6392                .map(|i| {
6393                    let emitted = recurse!(i);
6394                    let bare = match i {
6395                        Expr::Copy { expr } => *expr,
6396                        other => other,
6397                    };
6398                    match bare {
6399                        Expr::FieldAccess { .. } => {
6400                            match record_field_rust_type(
6401                                bare,
6402                                ecx.interner,
6403                                ecx.variable_types,
6404                                ecx.registry,
6405                            ) {
6406                                Some(ty) if !field_read_moves(&ty) => emitted,
6407                                _ => format!("{emitted}.clone()"),
6408                            }
6409                        }
6410                        Expr::Identifier(sym)
6411                            if identifier_read_moves(*sym, ecx.variable_types) =>
6412                        {
6413                            format!("{emitted}.clone()")
6414                        }
6415                        _ => emitted,
6416                    }
6417                })
6418                .collect();
6419            format!("LogosSeq::from_vec(vec![{}])", item_strs.join(", "))
6420        }
6421
6422        Expr::Tuple(ref items) => {
6423            let item_strs: Vec<String> = items
6424                .iter()
6425                .map(|i| format!("Value::from({})", recurse!(i)))
6426                .collect();
6427            // A tuple is a `LogosTuple` (newtype over `Vec<Value>`, Derefs to it so indexing /
6428            // destructuring / returns are unchanged) — distinct from a Seq so `Show` renders parens.
6429            format!(
6430                "logicaffeine_data::LogosTuple(vec![{}])",
6431                item_strs.join(", ")
6432            )
6433        }
6434
6435        Expr::Range { start, end } => {
6436            let (start_str, end_str) = range_bound_strs(start, end, |e| {
6437                super::rational::integer_operand(e, crate::semantics::collections::IntegerPlace::Range, ecx)
6438                    .unwrap_or_else(|| recurse!(e))
6439            });
6440            format!("({}..={})", start_str, end_str)
6441        }
6442
6443        Expr::FieldAccess { object, field } => {
6444            let field_name = interner.resolve(*field);
6445
6446            // Phase 52: Check if root object is synced - use .get().await
6447            let root_sym = get_root_identifier(object);
6448            if let Some(sym) = root_sym {
6449                if synced_vars.contains(&sym) {
6450                    let obj_name = interner.resolve(sym);
6451                    return format!(
6452                        "{}.get().await.{}",
6453                        obj_name,
6454                        crate::codegen::escape_rust_ident(field_name)
6455                    );
6456                }
6457            }
6458
6459            // NAMED-record field access: a record is a positional `Vec<Value>` (no named Rust fields), so
6460            // `r's quotient` resolves the field NAME to its 1-based `Vec` position via the record's type
6461            // marker and reads it with `LogosIndex` — the same path `item N of r` takes — then UNBOXES the
6462            // boxed `Value` to the field's scalar type so `r's ratio * 2.0` (a `Real` field) type-checks.
6463            // Only fires when the object is a marked record variable, so a real struct still emits `.field`.
6464            if let Expr::Identifier(sym) = object {
6465                if let Some(ty) = variable_types.get(sym) {
6466                    if let Some(pos) = super::types::logos_record_field_index(ty, field_name) {
6467                        let unbox = super::types::logos_record_field_type(ty, field_name)
6468                            .and_then(super::types::logos_value_unbox_call);
6469                        let obj_str = recurse!(object);
6470                        let get = format!("LogosIndex::logos_get(&{}, {}i64)", obj_str, pos);
6471                        return match unbox {
6472                            Some(unbox) => format!("({}).{}", get, unbox),
6473                            None => get,
6474                        };
6475                    }
6476                }
6477            }
6478
6479            let obj_str = recurse!(object);
6480            format!(
6481                "{}.{}",
6482                obj_str,
6483                crate::codegen::escape_rust_ident(field_name)
6484            )
6485        }
6486
6487        Expr::New {
6488            type_name,
6489            type_args,
6490            init_fields,
6491        } => {
6492            // Sanitize a cross-module reference (`Geometry::Point`) into the same Rust
6493            // identifier the struct declaration uses (`Geometry__Point`); plain names
6494            // are unchanged, so single-module output stays byte-identical.
6495            let type_str = rust_type_ident(interner.resolve(*type_name));
6496            // The language holds nothing in a rational field a record is built without, which a compiled rational
6497            // cannot hold.
6498            if let Some(field) = super::rational::unset_rational_field(*type_name, init_fields, ecx) {
6499                return format!(
6500                    "compile_error!({:?})",
6501                    format!(
6502                        "a `{}` built without its field `{}`, a rational: the language holds nothing there, and a \
6503                         compiled rational holds no nothing",
6504                        interner.resolve(*type_name),
6505                        interner.resolve(field)
6506                    )
6507                );
6508            }
6509            if !init_fields.is_empty() {
6510                // Struct initialization with fields: Point { x: 10, y: 20, ..Default::default() }
6511                // Always add ..Default::default() to handle partial initialization (e.g., CRDT fields)
6512                let fields_str = init_fields.iter()
6513                    .map(|(name, value)| {
6514                        let field_name = crate::codegen::escape_rust_ident(interner.resolve(*name));
6515                        // A field of the exact extension holds the value model's value of what fills it.
6516                        if super::types::program_record_field_type(&type_str, *name)
6517                            .is_some_and(|t| t == super::tower::VALUE)
6518                        {
6519                            return format!("{}: {}", field_name, super::tower::value(value, ecx));
6520                        }
6521                        // A field that holds a value-or-nothing stores `nothing`, another whole, or a value present.
6522                        if let Some(code) = super::types::program_record_field_type(&type_str, *name)
6523                            .and_then(|t| super::absent::stored(value, &t, ecx))
6524                        {
6525                            return format!("{}: {}", field_name, code);
6526                        }
6527                        // An integer stored in a field that holds rationals is the rational it equals.
6528                        if let Some(code) = super::types::program_record_field_type(&type_str, *name)
6529                            .filter(|t| t.contains(super::rational::RATIONAL))
6530                            .and_then(|t| super::rational::value_as(value, &super::rational::named(&t), ecx))
6531                        {
6532                            return format!("{}: {}", field_name, code);
6533                        }
6534                        let exact_field = stores_logos_int(*type_name, *name);
6535                        let value_str = if exact_field {
6536                            exact_field_value(value, ecx)
6537                        } else {
6538                            recurse!(value)
6539                        };
6540                        // A struct OWNS its fields, so a borrowed-slice param (`&[T]`) assigned
6541                        // to an owned `LogosSeq<T>` field must be materialized — mirrors the
6542                        // Return-of-a-slice coercion in stmt.rs. Without it the generated Rust
6543                        // fails E0308 (expected `LogosSeq<T>`, found `&[T]`).
6544                        let slice_sym = match value {
6545                            Expr::Identifier(sym) => Some(*sym),
6546                            Expr::Copy { expr: inner } => {
6547                                if let Expr::Identifier(sym) = inner { Some(*sym) } else { None }
6548                            }
6549                            _ => None,
6550                        };
6551                        let borrowed_slice = slice_sym
6552                            .and_then(|sym| variable_types.get(&sym))
6553                            .map(|t| t.starts_with("&["))
6554                            .unwrap_or(false);
6555                        // A struct OWNS its fields; a non-Copy VALUE identifier (struct/enum/String)
6556                        // moved in may still be read after the construction (json's `JEntry { key:
6557                        // kname }`, where kname is later used in the dup-key message). The Identifier
6558                        // arm bare-moves it and the statement-level clone does not reach inside a
6559                        // construction, so clone here — output-preserving (value semantics: a store
6560                        // copies; a currently-working move was a last-use, equivalent to clone+drop).
6561                        // ★ AND A FIELD READ IS NOT A CONSUMPTION. `a new Todo with … text t's text …`
6562                        // inside a loop moved `t.text` out of the row, so a sibling branch pushing
6563                        // `t` itself failed to build ("use of partially moved value"). That is how
6564                        // every "change one row, keep the others" loop is written — a toggle, an
6565                        // edit — and the two branches are mutually exclusive at RUN time, which
6566                        // rustc cannot know. Reading a field must leave the row whole.
6567                        // ★ A VARIABLE STORED IN A FIELD IS MOVED ONLY AT ITS LAST USE. The record owns
6568                        // what it holds, so a variable named here that the program reads again — a list
6569                        // pushed to after it was stored, a row the next iteration builds from — is
6570                        // copied in; one this statement uses for the last time, and names once, is moved
6571                        // for free. Liveness says which (`flow::moves_at_last_use`); where it does not
6572                        // reach, the store copies.
6573                        let field_read_of_non_copy =
6574                            record_field_rust_type(value, interner, variable_types, ecx.registry)
6575                                .is_some_and(|t| field_read_moves(&t));
6576                        let last_use = matches!(value, Expr::Identifier(s) if super::flow::moves_at_last_use(*s, 1));
6577                        let owned_binding = is_value_struct_identifier(value, variable_types)
6578                            || holds_collection(value, variable_types);
6579                        let value_semantics_copy = field_read_of_non_copy || (owned_binding && !last_use);
6580                        // ★ WIDEN AT THE BOUNDARY. A field stored as `LogosInt` may be filled from
6581                        // an `i64` — a literal, a counter, a function that cannot overflow — and
6582                        // requiring both sides to have been PREDICTED the same is what made this
6583                        // whole area fragile: two analyses meeting on one value, one saying `i64`
6584                        // and the other `LogosInt`, and rustc rejecting well-formed generated code
6585                        // on a type nobody wrote.
6586                        //
6587                        // `LogosInt::from` is total in both directions of the only conversion that
6588                        // is safe: identity when the value is already a `LogosInt` (Rust's
6589                        // reflexive `From`), a widening when it is an `i64`. NARROWING is never
6590                        // emitted anywhere — `to_i64` answers an `Option`, so a value that
6591                        // genuinely exceeded `i64` would be silently replaced, trading a loud
6592                        // build failure for a wrong number.
6593                        if exact_field {
6594                            format!("{}: logicaffeine_data::LogosInt::from({})", field_name, value_str)
6595                        } else if borrowed_slice {
6596                            format!("{}: LogosSeq::from_vec(({}).to_vec())", field_name, value_str)
6597                        } else if value_semantics_copy {
6598                            format!("{}: {}.clone()", field_name, value_str)
6599                        } else {
6600                            format!("{}: {}", field_name, value_str)
6601                        }
6602                    })
6603                    .collect::<Vec<_>>()
6604                    .join(", ");
6605                // The rest of the record — fields the construction leaves out (a CRDT field, a
6606                // defaulted one) — comes from `Default`. A construction naming every field needs
6607                // no `Default`, which a generic record (`Box<T>`) has only when `T` has one.
6608                let names_every_field = match ecx.registry.get(*type_name) {
6609                    Some(crate::analysis::registry::TypeDef::Struct { fields, .. }) => fields
6610                        .iter()
6611                        .all(|f| init_fields.iter().any(|(given, _)| *given == f.name)),
6612                    _ => false,
6613                };
6614                if names_every_field {
6615                    format!("{} {{ {} }}", type_str, fields_str)
6616                } else {
6617                    format!("{} {{ {}, ..Default::default() }}", type_str, fields_str)
6618                }
6619            } else if type_args.is_empty() {
6620                format!("{}::default()", type_str)
6621            } else {
6622                // Phase 34: Turbofish syntax for generic instantiation
6623                // Bug fix: Use codegen_type_expr to support nested types like Seq of (Seq of Int)
6624                let args_str = type_args
6625                    .iter()
6626                    .map(|t| codegen_type_expr(t, interner))
6627                    .collect::<Vec<_>>()
6628                    .join(", ");
6629                format!("{}::<{}>::default()", type_str, args_str)
6630            }
6631        }
6632
6633        Expr::NewVariant {
6634            enum_name,
6635            variant,
6636            fields,
6637        } => {
6638            // The RAW interned name keys the `boxed_fields` lookup (its keys are built
6639            // from the same raw name in detection.rs); the emitted `EnumName::Variant`
6640            // PATH must be the SANITIZED ident so a cross-module enum (`Colors::Filter`)
6641            // constructs as `Colors__Filter::Variant`. Plain names are unchanged.
6642            let enum_name_raw = interner.resolve(*enum_name);
6643            let enum_str = rust_type_ident(enum_name_raw);
6644            let enum_str = enum_str.as_str();
6645            let variant_str = interner.resolve(*variant);
6646            let fish = super::instantiation::for_expr(expr);
6647            let enum_str = format!("{enum_str}{fish}");
6648            let enum_str = enum_str.as_str();
6649            let exact = |field: Symbol| stores_logos_int(*variant, field);
6650            if fields.is_empty() {
6651                // Unit variant: Shape::Point
6652                format!("{}::{}", enum_str, variant_str)
6653            } else {
6654                // A variable named in a construction is cloned at every mention but its last, which
6655                // moves it when the statement allows (`flow::moves_at_last_use`): the statement names it
6656                // nowhere else, and either reassigns it — a list built by `Set l to a new Cons with …
6657                // tail l` never deep-copies `l` — or is its last use. Otherwise the last mention clones
6658                // too. The count spans the OUTERMOST construction's whole subtree, nested constructions
6659                // included, so an inner `Node` taking `leaf` twice and an outer one taking it again do
6660                // not both move it. Only a direct field decrements the count; a mention some other arm
6661                // emits (inside a list, a call) never does, so a later direct field keeps cloning — the
6662                // safe side.
6663                let outermost = CONSTRUCTION_USES.with(|u| u.borrow().is_none());
6664                if outermost {
6665                    let mut counts: HashMap<Symbol, (usize, usize)> = HashMap::new();
6666                    super::worklist::visit_idents(expr, &mut |s| {
6667                        let c = counts.entry(s).or_insert((0, 0));
6668                        c.0 += 1;
6669                        c.1 += 1;
6670                    });
6671                    CONSTRUCTION_USES.with(|u| *u.borrow_mut() = Some(counts));
6672                }
6673
6674                // Struct variant: Shape::Circle { radius: 10 }
6675                let variant_def = ecx.registry.variant_in(*enum_name, *variant);
6676                let fields_str: Vec<(String, String)> = fields
6677                    .iter()
6678                    .map(|(field_name, value)| {
6679                        let name = interner.resolve(*field_name);
6680
6681                        let val = if let Expr::Identifier(sym) = value {
6682                            let base_name = if boxed_bindings.contains(sym) {
6683                                format!("(*{})", interner.resolve(*sym))
6684                            } else {
6685                                interner.resolve(*sym).to_string()
6686                            };
6687                            let movable = CONSTRUCTION_USES.with(|u| {
6688                                let mut uses = u.borrow_mut();
6689                                match uses.as_mut().and_then(|m| m.get_mut(sym)) {
6690                                    Some((named, left)) => {
6691                                        *left = left.saturating_sub(1);
6692                                        *left == 0 && super::flow::moves_at_last_use(*sym, *named)
6693                                    }
6694                                    None => false,
6695                                }
6696                            });
6697                            let read = if movable {
6698                                base_name
6699                            } else {
6700                                format!("{}.clone()", base_name)
6701                            };
6702                            if exact(*field_name) {
6703                                format!("logicaffeine_data::LogosInt::from({read})")
6704                            } else {
6705                                read
6706                            }
6707                        } else if exact(*field_name) {
6708                            exact_field_value(value, ecx)
6709                        } else {
6710                            recurse!(value)
6711                        };
6712
6713                        // A field stored in a box of its own is boxed here. Keyed by the RAW enum name —
6714                        // `boxed_fields` is collected from the same raw interned name. The enum's own
6715                        // declaration answers too, so a construction reached through an entry that carries
6716                        // the registry but not the collected set (a `Show`'s argument) still boxes what the
6717                        // declaration boxed.
6718                        let key = (
6719                            enum_name_raw.to_string(),
6720                            variant_str.to_string(),
6721                            name.to_string(),
6722                        );
6723                        let declared_boxed = variant_def
6724                            .and_then(|v| v.fields.iter().find(|f| f.name == *field_name))
6725                            .is_some_and(|f| {
6726                                super::types::field_is_boxed(&f.ty, enum_name_raw, interner)
6727                            });
6728                        let field = crate::codegen::escape_rust_ident(name);
6729                        if boxed_fields.contains(&key) || declared_boxed {
6730                            (field, format!("Box::new({})", val))
6731                        } else {
6732                            (field, val)
6733                        }
6734                    })
6735                    .collect();
6736                if outermost {
6737                    CONSTRUCTION_USES.with(|u| *u.borrow_mut() = None);
6738                }
6739                let shape = variant_def.map_or(super::types::VariantShape::InPlace, |v| {
6740                    super::types::VariantShape::of(v, enum_name_raw, interner)
6741                });
6742                shape.build(&format!("{}::{}", enum_str, variant_str), &fields_str)
6743            }
6744        }
6745
6746        Expr::OptionSome { value } => {
6747            format!("Some({})", recurse!(value))
6748        }
6749
6750        Expr::OptionNone => "None".to_string(),
6751
6752        Expr::Escape { code, .. } => {
6753            let raw_code = interner.resolve(*code);
6754            let mut block = String::from("{\n");
6755            for line in raw_code.lines() {
6756                block.push_str("    ");
6757                block.push_str(line);
6758                block.push('\n');
6759            }
6760            block.push('}');
6761            block
6762        }
6763
6764        Expr::WithCapacity { value, capacity } => {
6765            let cap_str = recurse!(capacity);
6766            match value {
6767                // Empty string → String::with_capacity(cap)
6768                Expr::Literal(Literal::Text(sym)) if interner.resolve(*sym).is_empty() => {
6769                    format!("String::with_capacity(({}) as usize)", cap_str)
6770                }
6771                // Non-empty string → { let mut __s = String::with_capacity(cap); __s.push_str("..."); __s }
6772                Expr::Literal(Literal::Text(sym)) => {
6773                    let text = crate::codegen::stmt::rust_string_escape(interner.resolve(*sym));
6774                    format!("{{ let mut __s = String::with_capacity(({}) as usize); __s.push_str(\"{}\"); __s }}", cap_str, text)
6775                }
6776                // Collection Expr::New → Type::with_capacity(cap)
6777                Expr::New {
6778                    type_name,
6779                    type_args,
6780                    ..
6781                } => {
6782                    let type_str = interner.resolve(*type_name);
6783                    match type_str {
6784                        "Seq" | "List" | "Vec" => {
6785                            let elem = if !type_args.is_empty() {
6786                                codegen_type_expr(&type_args[0], interner)
6787                            } else {
6788                                "()".to_string()
6789                            };
6790                            format!(
6791                                "LogosSeq::<{}>::with_capacity(({}) as usize)",
6792                                elem, cap_str
6793                            )
6794                        }
6795                        "Map" | "HashMap" => {
6796                            let (k, v) = if type_args.len() >= 2 {
6797                                (
6798                                    codegen_type_expr(&type_args[0], interner),
6799                                    codegen_type_expr(&type_args[1], interner),
6800                                )
6801                            } else {
6802                                ("String".to_string(), "String".to_string())
6803                            };
6804                            format!(
6805                                "LogosMap::<{}, {}>::with_capacity(({}) as usize)",
6806                                k, v, cap_str
6807                            )
6808                        }
6809                        "Set" | "HashSet" => {
6810                            let elem = if !type_args.is_empty() {
6811                                codegen_type_expr(&type_args[0], interner)
6812                            } else {
6813                                "()".to_string()
6814                            };
6815                            format!("{{ let __s: Set<{}> = Set::with_capacity_and_hasher(({}) as usize, Default::default()); __s }}", elem, cap_str)
6816                        }
6817                        _ => recurse!(value), // Unknown type — ignore capacity
6818                    }
6819                }
6820                // Other expressions — ignore capacity hint
6821                _ => recurse!(value),
6822            }
6823        }
6824
6825        Expr::Closure { params, body, .. } => {
6826            use crate::ast::stmt::ClosureBody;
6827            let _body_moves_nothing = super::flow::suspend();
6828            let _control = super::control::function();
6829            // A closure passed to a scalar exact-HOF (`apply(f, x)`) has its integer params typed
6830            // `LogosInt` so an overflowing body promotes to a bignum == the VM. `exact_closure` is set
6831            // ONLY on this closure's own codegen by the call-site arg loop; a `map`/`fold` closure
6832            // keeps its `i64` params (its HOF is seq-shaped, hence not exact).
6833            let exact = ecx.exact_closure;
6834            let params_str: Vec<String> = params
6835                .iter()
6836                .map(|(name, ty)| {
6837                    let param_name = names.ident(*name);
6838                    let param_type = codegen_type_expr(ty, interner);
6839                    let param_type = if exact && param_type == "i64" {
6840                        "logicaffeine_data::LogosInt".to_string()
6841                    } else {
6842                        param_type
6843                    };
6844                    format!("{}: {}", param_name, param_type)
6845                })
6846                .collect();
6847            // A closure's parameters SHADOW whatever the enclosing scope knew by the same names:
6848            // the scope's facts are keyed by symbol, and two closures in one function commonly
6849            // reuse `a`/`x` — a `(a: Text, x: Text)` closure must not make another closure's
6850            // `(a: Int, x: Int) -> a + x` read as text concatenation.
6851            let mut scope_strings = ecx.string_vars.clone();
6852            let mut scope_types = ecx.variable_types.clone();
6853            for (name, ty) in params.iter() {
6854                let declared = codegen_type_expr(ty, interner);
6855                scope_strings.remove(name);
6856                if declared == "String" {
6857                    scope_strings.insert(*name);
6858                }
6859                if scope_types.contains_key(name) {
6860                    scope_types.insert(*name, declared);
6861                }
6862            }
6863            let ecx = &ExprCtx {
6864                string_vars: &scope_strings,
6865                variable_types: &scope_types,
6866                ..*ecx
6867            };
6868            // The exactified (integer) params, registered as promoted (`__bigint`) so the body's
6869            // arithmetic (`n * 2`) routes through the exact helper and stays `LogosInt`.
6870            let exact_param_types: HashMap<Symbol, String> = if exact {
6871                let mut vt = ecx.variable_types.clone();
6872                for (name, ty) in params.iter() {
6873                    if codegen_type_expr(ty, interner) == "i64" {
6874                        vt.insert(*name, "i64|__bigint".to_string());
6875                    }
6876                }
6877                vt
6878            } else {
6879                HashMap::new()
6880            };
6881
6882            match body {
6883                ClosureBody::Expression(expr) => {
6884                    let body_str = if exact {
6885                        // Exact + tolerant: the promoted operand chain stays `LogosInt` (no narrow),
6886                        // matching the closure's `-> LogosInt` return; reset `exact_closure` so a
6887                        // nested closure does not wrongly inherit it.
6888                        let bctx = ExprCtx {
6889                            variable_types: &exact_param_types,
6890                            int_exact_tolerant: true,
6891                            exact_closure: false,
6892                            ..*ecx
6893                        };
6894                        codegen_expr_ctx(expr, &bctx)
6895                    } else {
6896                        // The body is a fresh expression root behind an `i64`-shaped boundary:
6897                        // an enclosing tolerant chain must not leak in, or the body would return
6898                        // an un-narrowed `LogosInt` from an `i64` closure.
6899                        let bctx = ExprCtx {
6900                            int_exact_tolerant: false,
6901                            exact_closure: false,
6902                            ..*ecx
6903                        };
6904                        codegen_expr_ctx(expr, &bctx)
6905                    };
6906                    format!("move |{}| {{ {} }}", params_str.join(", "), body_str)
6907                }
6908                ClosureBody::Block(stmts) => {
6909                    let mut body_str = String::new();
6910                    let mut ctx = RefinementContext::new();
6911                    // Exact-HOF closure: register the integer params as promoted (`__bigint`) so a
6912                    // statement-body's arithmetic is exact, matching the Expression path.
6913                    if exact {
6914                        ctx.set_returns_bigint(true);
6915                        for (name, ty) in params.iter() {
6916                            if codegen_type_expr(ty, interner) == "i64" {
6917                                ctx.register_variable_type(*name, "i64|__bigint".to_string());
6918                            }
6919                        }
6920                    }
6921                    let empty_mutable = collect_mutable_vars(stmts);
6922                    let empty_lww = HashSet::new();
6923                    let empty_mv = HashSet::new();
6924                    let mut empty_synced = HashSet::new();
6925                    let empty_caps = HashMap::new();
6926                    let empty_pipes = HashSet::new();
6927                    let empty_boxed = HashSet::new();
6928                    let empty_registry = TypeRegistry::new();
6929                    let type_env = crate::analysis::types::TypeEnv::new();
6930                    for stmt in stmts.iter() {
6931                        body_str.push_str(&codegen_stmt(
6932                            stmt,
6933                            interner,
6934                            2,
6935                            &empty_mutable,
6936                            &mut ctx,
6937                            &empty_lww,
6938                            &empty_mv,
6939                            &mut empty_synced,
6940                            &empty_caps,
6941                            async_functions,
6942                            &empty_pipes,
6943                            &empty_boxed,
6944                            &empty_registry,
6945                            &type_env,
6946                        ));
6947                    }
6948                    format!(
6949                        "move |{}| {{\n{}{}}}",
6950                        params_str.join(", "),
6951                        body_str,
6952                        "    "
6953                    )
6954                }
6955            }
6956        }
6957
6958        Expr::CallExpr { callee, args } => {
6959            let callee_str = recurse!(callee);
6960            let args_str: Vec<String> = args.iter().map(|a| recurse!(a)).collect();
6961            format!("({})({})", callee_str, args_str.join(", "))
6962        }
6963
6964        Expr::InterpolatedString(parts) => codegen_interpolated_string(parts, ecx),
6965
6966        Expr::Not { operand } => {
6967            // Logical negation of truthiness (`~` is the bitwise complement).
6968            let operand_str = recurse!(operand);
6969            if matches!(
6970                infer_logos_type(operand, interner, variable_types),
6971                crate::analysis::types::LogosType::Bool
6972            ) {
6973                format!("!({})", operand_str)
6974            } else {
6975                format!("(!logos_truthy(&({})))", operand_str)
6976            }
6977        }
6978    }
6979}
6980
6981pub(crate) fn codegen_interpolated_string(
6982    parts: &[crate::ast::stmt::StringPart],
6983    ecx: &ExprCtx,
6984) -> String {
6985    use crate::ast::stmt::StringPart;
6986    let interner = ecx.interner;
6987
6988    let mut fmt_str = String::new();
6989    let mut args = Vec::new();
6990    let mut holes: Vec<&Expr> = Vec::new();
6991
6992    for part in parts {
6993        match part {
6994            StringPart::Literal(sym) => {
6995                let text = interner.resolve(*sym);
6996                // Escape braces and special chars in the format string. `"` and `\` MUST be
6997                // escaped too — the literal segments sit inside the `format!("…")` string literal,
6998                // so an unescaped quote (e.g. from `"key \"{k}\""`) closes the Rust string early.
6999                // Mirrors the no-holes `String::from` path below.
7000                for ch in text.chars() {
7001                    match ch {
7002                        '{' => fmt_str.push_str("{{"),
7003                        '}' => fmt_str.push_str("}}"),
7004                        '\n' => fmt_str.push_str("\\n"),
7005                        '\t' => fmt_str.push_str("\\t"),
7006                        '\r' => fmt_str.push_str("\\r"),
7007                        '"' => fmt_str.push_str("\\\""),
7008                        '\\' => fmt_str.push_str("\\\\"),
7009                        _ => fmt_str.push(ch),
7010                    }
7011                }
7012            }
7013            StringPart::Expr {
7014                value,
7015                format_spec,
7016                debug,
7017            } => {
7018                if *debug {
7019                    let debug_prefix = expr_debug_prefix(value, interner);
7020                    for ch in debug_prefix.chars() {
7021                        match ch {
7022                            '{' => fmt_str.push_str("{{"),
7023                            '}' => fmt_str.push_str("}}"),
7024                            '"' => fmt_str.push_str("\\\""),
7025                            '\\' => fmt_str.push_str("\\\\"),
7026                            _ => fmt_str.push(ch),
7027                        }
7028                    }
7029                    fmt_str.push('=');
7030                }
7031                let arg_str = codegen_expr_ctx(value, ecx);
7032                let (piece, arg) =
7033                    interpolation_hole(format_spec.map(|s| interner.resolve(s)), &arg_str);
7034                fmt_str.push_str(&piece);
7035                args.push(arg);
7036                holes.push(value);
7037            }
7038        }
7039    }
7040
7041    if args.is_empty() {
7042        // No holes — emit raw String::from (no format! escaping needed).
7043        // Reconstruct the raw text from parts without brace escaping.
7044        let mut raw = String::new();
7045        for part in parts {
7046            if let StringPart::Literal(sym) = part {
7047                let text = interner.resolve(*sym);
7048                for ch in text.chars() {
7049                    match ch {
7050                        '\n' => raw.push_str("\\n"),
7051                        '\t' => raw.push_str("\\t"),
7052                        '\r' => raw.push_str("\\r"),
7053                        '"' => raw.push_str("\\\""),
7054                        '\\' => raw.push_str("\\\\"),
7055                        _ => raw.push(ch),
7056                    }
7057                }
7058            }
7059        }
7060        format!("::std::string::String::from(\"{}\")", raw)
7061    } else {
7062        format_in_order(&fmt_str, &holes, args, ecx.variable_types)
7063    }
7064}
7065
7066pub(crate) fn codegen_literal(lit: &Literal, interner: &Interner) -> String {
7067    match lit {
7068        Literal::Number(n) => {
7069            if *n > i32::MAX as i64 || *n < i32::MIN as i64 {
7070                format!("{}_i64", n)
7071            } else {
7072                n.to_string()
7073            }
7074        }
7075        // Non-finite values have no numeric-literal spelling in Rust
7076        // (`Display` gives "inf"/"NaN", which would emit invalid tokens).
7077        Literal::Float(f) if f.is_nan() => "f64::NAN".to_string(),
7078        Literal::Float(f) if f.is_infinite() && *f > 0.0 => "f64::INFINITY".to_string(),
7079        Literal::Float(f) if f.is_infinite() => "f64::NEG_INFINITY".to_string(),
7080        Literal::Float(f) => format!("{}f64", f),
7081        // String literals are converted to String for consistent Text type handling
7082        Literal::Text(sym) => {
7083            format!(
7084                "::std::string::String::from(\"{}\")",
7085                crate::codegen::stmt::rust_string_escape(interner.resolve(*sym))
7086            )
7087        }
7088        Literal::Boolean(b) => b.to_string(),
7089        Literal::Nothing => "()".to_string(),
7090        // Character literals
7091        Literal::Char(c) => {
7092            // Handle escape sequences for special characters
7093            match c {
7094                '\n' => "'\\n'".to_string(),
7095                '\t' => "'\\t'".to_string(),
7096                '\r' => "'\\r'".to_string(),
7097                '\\' => "'\\\\'".to_string(),
7098                '\'' => "'\\''".to_string(),
7099                '\0' => "'\\0'".to_string(),
7100                c => format!("'{}'", c),
7101            }
7102        }
7103        // Temporal literals: Duration stored as nanoseconds (i64)
7104        Literal::Duration(nanos) => format!("std::time::Duration::from_nanos({}u64)", nanos),
7105        // Date stored as days since Unix epoch (i32)
7106        Literal::Date(days) => format!("LogosDate({})", days),
7107        // Moment stored as nanoseconds since Unix epoch (i64)
7108        Literal::Moment(nanos) => format!("LogosMoment({})", nanos),
7109        // Span stored as (months, days) - separate because they're incommensurable
7110        Literal::Span { months, days } => format!("LogosSpan::new({}, {})", months, days),
7111        // Time-of-day stored as nanoseconds from midnight
7112        Literal::Time(nanos) => format!("LogosTime({})", nanos),
7113    }
7114}
7115
7116/// Converts a LogicExpr to a Rust boolean expression for debug_assert!().
7117/// Uses RustFormatter to unify all logic-to-Rust translation.
7118pub fn codegen_assertion(expr: &LogicExpr, interner: &Interner) -> String {
7119    let mut registry = SymbolRegistry::new();
7120    let formatter = RustFormatter;
7121    let mut buf = String::new();
7122
7123    match expr.write_logic(&mut buf, &mut registry, interner, &formatter) {
7124        Ok(_) => buf,
7125        Err(_) => "/* error generating assertion */ false".to_string(),
7126    }
7127}
7128
7129pub fn codegen_term(term: &Term, interner: &Interner) -> String {
7130    match term {
7131        Term::Constant(sym) => interner.resolve(*sym).to_string(),
7132        Term::Variable(sym) => interner.resolve(*sym).to_string(),
7133        Term::Value { kind, .. } => match kind {
7134            NumberKind::Integer(n) => n.to_string(),
7135            NumberKind::Real(f) => f.to_string(),
7136            NumberKind::Symbolic(sym) => interner.resolve(*sym).to_string(),
7137        },
7138        Term::Function(name, args) => {
7139            let args_str: Vec<String> = args.iter().map(|a| codegen_term(a, interner)).collect();
7140            format!("{}({})", interner.resolve(*name), args_str.join(", "))
7141        }
7142        Term::Possessed {
7143            possessor,
7144            possessed,
7145        } => {
7146            let poss_str = codegen_term(possessor, interner);
7147            format!("{}.{}", poss_str, interner.resolve(*possessed))
7148        }
7149        Term::Group(members) => {
7150            let members_str: Vec<String> =
7151                members.iter().map(|m| codegen_term(m, interner)).collect();
7152            format!("({})", members_str.join(", "))
7153        }
7154        _ => "/* unsupported Term */".to_string(),
7155    }
7156}
7157
7158#[cfg(test)]
7159#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/codegen/expr/tests.rs"]
7160mod tests;