Skip to main content

logicaffeine_compile/codegen/
stmt.rs

1use std::collections::{HashMap, HashSet};
2use std::fmt::Write;
3
4use crate::analysis::registry::{FieldType, TypeDef, TypeRegistry};
5use crate::analysis::types::RustNames;
6use crate::ast::stmt::{
7    BinaryOpKind, Block, Expr, Literal, MatchArm, Pattern, ReadSource, Stmt, TypeExpr, ZoneSource,
8};
9use crate::intern::{Interner, Symbol};
10
11use super::context::{emit_refinement_check, RefinementContext, VariableCapabilities};
12use super::detection::{
13    calls_async_function, collect_expr_identifiers, collect_stmt_identifiers, expr_debug_prefix,
14    expr_reads_any_collection, parse_aos_tag, requires_async_stmt,
15};
16use super::expr::{
17    codegen_assertion, codegen_expr_boxed_with_types, codegen_expr_boxed_with_types_oracle,
18    codegen_expr_boxed_with_types_oracle_tolerant, codegen_expr_with_async,
19    codegen_expr_with_async_and_strings, codegen_expr_with_async_oracle,
20    collect_string_concat_operands, is_definitely_string_expr_with_vars, is_rational_expr,
21    set_movable_last_use,
22};
23
24/// How many times `target` is read in `e`, counting only the expression shapes a
25/// promoted-`Int` accumulator RHS is built from (arithmetic, calls, unary not).
26/// Any shape not modeled here returns `2` — a poison that makes the total ≥ 2, so
27/// the move-on-last-use hint is disabled rather than risk a use-after-move on a
28/// subtree we did not fully account for. A result of exactly `1` therefore proves
29/// `target` occurs once, in a fully-understood position, and may be moved.
30fn count_target_reads(e: &Expr, target: Symbol) -> usize {
31    match e {
32        Expr::Identifier(s) => usize::from(*s == target),
33        Expr::Literal(_) => 0,
34        Expr::BinaryOp { left, right, .. } => {
35            count_target_reads(left, target) + count_target_reads(right, target)
36        }
37        Expr::Not { operand } => count_target_reads(operand, target),
38        Expr::Call { args, .. } => args.iter().map(|a| count_target_reads(a, target)).sum(),
39        _ => 2,
40    }
41}
42use super::escape_rust_ident;
43use super::i64_map::{dense_type_name, is_logos_map_type, map_rust_type};
44use super::peephole::{
45    body_declares_var, body_has_early_exit, body_modifies_var, body_mutates_collection,
46    body_resizes_collection, collect_expr_symbols, emit_bounds_hint_header,
47    emit_bounds_hint_preheader, exprs_equal, is_counter_increment, plan_bounds_hints,
48    simplify_1based_index, try_emit_byte_compare_window, try_emit_drain_tail_in_while,
49    BoundsHintPlan,
50};
51use super::types::{
52    codegen_type_expr, infer_numeric_type, infer_rust_type_from_expr, infer_variant_type_annotation,
53};
54
55/// Escape a LOGOS text value for a Rust `"..."` string-literal body (no surrounding
56/// quotes). Kept identical to the string-literal escaping in `codegen::expr` so the
57/// self-append fast paths (`push_str`, `write!`-with-`&str`) render byte-for-byte the
58/// same literal a normal `String::from("…")` would.
59/// A LOGOS Text as the body of a Rust string literal — the ONE escaper.
60///
61/// There were two: this, and an identical copy inlined in the expression emitter. Two copies is
62/// how three sites ended up without any — `Let s be "a\"b" + n.` emitted
63/// `format!("{}{}", "a"b", 5)`, which does not compile, while the same text on its own was fine.
64/// Every place that spells a literal into generated Rust calls THIS.
65pub(crate) fn rust_string_escape(text: &str) -> String {
66    let mut out = String::with_capacity(text.len());
67    for ch in text.chars() {
68        match ch {
69            '\n' => out.push_str("\\n"),
70            '\r' => out.push_str("\\r"),
71            '\t' => out.push_str("\\t"),
72            '\\' => out.push_str("\\\\"),
73            '"' => out.push_str("\\\""),
74            _ => out.push(ch),
75        }
76    }
77    out
78}
79
80/// Escape a single `char` for a Rust `'c'` char-literal body (no surrounding quotes).
81fn rust_char_escape(ch: char) -> String {
82    match ch {
83        '\n' => "\\n".to_string(),
84        '\r' => "\\r".to_string(),
85        '\t' => "\\t".to_string(),
86        '\\' => "\\\\".to_string(),
87        '\'' => "\\'".to_string(),
88        _ => ch.to_string(),
89    }
90}
91
92/// The `(Vec<T>, init-expr)` pair for a de-Rc'd Seq declaration, or `None`
93/// when the initializer is not a fresh scalar-Seq allocation (in which case
94/// the normal `LogosSeq` path runs). Mirrors `fresh_scalar_seq_elem` in the
95/// de-Rc eligibility analysis — only those forms are ever marked de-Rc.
96fn derc_vec_decl<'a>(
97    value: &Expr<'a>,
98    interner: &Interner,
99    synced_vars: &HashSet<Symbol>,
100    boxed_fields: &HashSet<(String, String, String)>,
101    registry: &TypeRegistry,
102    async_functions: &HashSet<Symbol>,
103    ctx: &RefinementContext<'a>,
104) -> Option<(String, String)> {
105    match value {
106        Expr::New {
107            type_name,
108            type_args,
109            init_fields,
110        } if init_fields.is_empty() => match interner.resolve(*type_name) {
111            "Seq" | "List" | "Vec" => {
112                let elem = codegen_type_expr(type_args.first()?, interner);
113                Some((format!("Vec<{}>", elem), "Vec::new()".to_string()))
114            }
115            _ => None,
116        },
117        Expr::WithCapacity {
118            value: inner,
119            capacity,
120        } => {
121            if let Expr::New {
122                type_name,
123                type_args,
124                ..
125            } = inner
126            {
127                if matches!(interner.resolve(*type_name), "Seq" | "List" | "Vec") {
128                    let elem = codegen_type_expr(type_args.first()?, interner);
129                    let cap = codegen_expr_boxed_with_types(
130                        capacity,
131                        interner,
132                        synced_vars,
133                        boxed_fields,
134                        registry,
135                        async_functions,
136                        ctx.get_string_vars(),
137                        ctx.get_variable_types(),
138                        ctx.get_fast_div(),
139                    );
140                    return Some((
141                        format!("Vec<{}>", elem),
142                        format!("Vec::with_capacity(({}) as usize)", cap),
143                    ));
144                }
145            }
146            None
147        }
148        // Phase 4: `Let r be f(...)` where `f` returns an OWNED `Vec<T>` (its
149        // return type already de-Rc'd in `fn_returns_map`). The result is a
150        // uniquely-owned fresh value — bind it as `Vec<T>` so every later access
151        // on `r` indexes directly instead of borrowing a RefCell.
152        Expr::Call { function, .. } => {
153            let ret = ctx.get_fn_return(function)?;
154            if !ret.starts_with("Vec<") {
155                return None;
156            }
157            let vec_ty = ret.clone();
158            let init = codegen_expr_boxed_with_types(
159                value,
160                interner,
161                synced_vars,
162                boxed_fields,
163                registry,
164                async_functions,
165                ctx.get_string_vars(),
166                ctx.get_variable_types(),
167                ctx.get_fast_div(),
168            );
169            Some((vec_ty, init))
170        }
171        // A homogeneous scalar-literal list de-Rc's to a plain `Vec<T>` literal — the NTT power
172        // table + coefficient array, and any `[…]` of one scalar literal kind, indexed without a
173        // RefCell borrow. Eligibility mirrors `fresh_scalar_seq_elem` via the shared helper.
174        Expr::List(items) => {
175            let elem = crate::codegen::detection::homogeneous_scalar_literal_elem(items)?;
176            let item_strs: Vec<String> = items
177                .iter()
178                .map(|i| {
179                    codegen_expr_boxed_with_types(
180                        i,
181                        interner,
182                        synced_vars,
183                        boxed_fields,
184                        registry,
185                        async_functions,
186                        ctx.get_string_vars(),
187                        ctx.get_variable_types(),
188                        ctx.get_fast_div(),
189                    )
190                })
191                .collect();
192            Some((
193                format!("Vec<{}>", elem),
194                format!("vec![{}]", item_strs.join(", ")),
195            ))
196        }
197        _ => None,
198    }
199}
200
201/// The `LogosI64Map` constructor for a `Map of Int to Int` declared via `value`
202/// (`a new Map of Int to Int` or `… with capacity n`); `None` for any other
203/// initializer (the normal `LogosMap` codegen runs). Only called when the alias
204/// analysis already selected the variable for `LogosI64Map`.
205fn i64_map_ctor<'a>(
206    value: &Expr<'a>,
207    ty: &str,
208    dense_lo: Option<i64>,
209    interner: &Interner,
210    synced_vars: &HashSet<Symbol>,
211    boxed_fields: &HashSet<(String, String, String)>,
212    registry: &TypeRegistry,
213    async_functions: &HashSet<Symbol>,
214    ctx: &RefinementContext<'a>,
215) -> Option<String> {
216    match value {
217        Expr::New {
218            type_name,
219            init_fields,
220            ..
221        } if init_fields.is_empty()
222            && matches!(interner.resolve(*type_name), "Map" | "HashMap") =>
223        {
224            Some(format!("{}::new()", ty))
225        }
226        Expr::WithCapacity {
227            value: inner,
228            capacity,
229        } => {
230            if let Expr::New { type_name, .. } = inner {
231                if matches!(interner.resolve(*type_name), "Map" | "HashMap") {
232                    let cap = codegen_expr_boxed_with_types(
233                        capacity,
234                        interner,
235                        synced_vars,
236                        boxed_fields,
237                        registry,
238                        async_functions,
239                        ctx.get_string_vars(),
240                        ctx.get_variable_types(),
241                        ctx.get_fast_div(),
242                    );
243                    // A dense map is a direct-addressed array offset by the proven
244                    // window `lo` (currently 0) and sized `capacity + 1` slots: the
245                    // bound proof gives `lo <= key <= lo + capacity`, so the highest
246                    // index `key - lo` is `capacity`, which needs `capacity + 1`
247                    // slots. A non-dense `LogosI64Map`/`Set` takes the plain capacity.
248                    return Some(match dense_lo {
249                        Some(lo) => {
250                            format!("{}::with_bounds({}, (({}) + 1) as usize)", ty, lo, cap)
251                        }
252                        None => format!("{}::with_capacity(({}) as usize)", ty, cap),
253                    });
254                }
255            }
256            None
257        }
258        _ => None,
259    }
260}
261
262/// The 0-based `usize` offset a store index proven in range names: a rebased counter as it is, any other
263/// index with its 1 taken away.
264fn store_offset(
265    index: &Expr,
266    zero_based: Option<&str>,
267    interner: &Interner,
268    ctx: &RefinementContext,
269) -> String {
270    match zero_based {
271        Some(s) => format!("{} as usize", s),
272        None => simplify_1based_index(index, interner, true, ctx.get_variable_types()),
273    }
274}
275
276/// O5: emit `assert_unchecked` bounds hints for every indexed access in `stmt`
277/// the bounds-elision oracle proves in range (a relational induction bound
278/// `i <= length(arr)` or a concrete interval). Paired with a `debug_assert!`
279/// so an unsound proof panics loudly in debug. No-op when the oracle is absent.
280/// Only Identifier collections (a name is needed for `.len()`).
281fn emit_oracle_index_hints<'a>(
282    stmt: &Stmt<'a>,
283    ctx: &RefinementContext<'a>,
284    interner: &Interner,
285    registry: &TypeRegistry,
286    indent_str: &str,
287) -> String {
288    // Kill switch (A/B): `LOGOS_ORACLE_HINTS=0` suppresses the oracle bounds
289    // hints entirely (the access keeps its runtime bounds check).
290    if !crate::optimize::active_config().is_on(crate::optimization::Opt::OracleHints) {
291        return String::new();
292    }
293    let oracle = match ctx.oracle() {
294        Some(o) => o,
295        None => return String::new(),
296    };
297    let mut accesses: Vec<(&Expr, &Expr)> = Vec::new();
298    collect_index_accesses_in_stmt(stmt, &mut accesses);
299    if accesses.is_empty() {
300        return String::new();
301    }
302    let names = RustNames::new(interner);
303    let mut out = String::new();
304    let mut seen: HashSet<usize> = HashSet::new();
305    for (coll, idx) in accesses {
306        let arr = match coll {
307            Expr::Identifier(s) => *s,
308            _ => continue,
309        };
310        // An affine read-only array is deleted — its reads are pure arithmetic,
311        // so there is no `.len()` to bound-check and no hint to emit.
312        if ctx.affine_array(arr).is_some() {
313            continue;
314        }
315        // A list of the exact extension's values is read through its model, which checks every
316        // index itself; there is no slice for a hint to bound.
317        if ctx
318            .get_variable_types()
319            .get(&arr)
320            .is_some_and(|t| t == super::tower::VALUE)
321        {
322            continue;
323        }
324        // An index held as an exact number is read as the integer it equals, checked as it converts; there is
325        // no machine word to bound.
326        let typing = super::rational::Typing {
327            interner,
328            variable_types: ctx.get_variable_types(),
329            registry,
330        };
331        if super::rational::read_as_exact(idx, typing) {
332            continue;
333        }
334        // An AoS-interleaved member folds into a `[[T; W]; N]` backing. The hint
335        // must name the BACKING (the member's own name no longer exists) and
336        // bound its ROW dimension (`backing.len()` == N) — that elides the
337        // rolled-regime row bounds-check just like C's, since the column is a
338        // constant < W.
339        let aos_backing = parse_aos_tag(ctx.get_variable_types().get(&arr)).map(|t| t.backing);
340        if !seen.insert(idx as *const Expr as usize) {
341            continue;
342        }
343        if !oracle.index_provably_in_bounds(coll, idx) {
344            continue;
345        }
346        // Discharge any `% m` element-bound precondition this elision leaned on
347        // with a hard `assert!(m > 0)` (LLVM hoists the loop-invariant check out
348        // of the loop, so it costs one comparison per region entry). For
349        // `m <= 0` the `% m`-filled array is empty and this access would be out
350        // of bounds: the assert panics there — exactly where the program would
351        // have — instead of the elision becoming UB.
352        for &m in oracle.index_positivity_guards(idx) {
353            let mn = names.ident(m);
354            writeln!(
355                out,
356                "{}assert!(({mn}) > 0, \"LOGOS positivity guard: element bound on `% {mn}` requires {mn} > 0\");",
357                indent_str, mn = mn
358            )
359            .unwrap();
360        }
361        // Match the ACCESS's 0-based index form: a `__zero_based_i64` counter
362        // indexes directly (`arr[i]`), everything else is 1-based (`arr[i-1]`).
363        // The oracle reasons about the 1-based source; codegen may rebase.
364        let i0 = match super::expr::zero_based_index_str(idx, ctx.get_variable_types(), interner) {
365            Some(s) => s,
366            None => simplify_1based_index(idx, interner, false, ctx.get_variable_types()),
367        };
368        let arr_name = aos_backing.unwrap_or_else(|| names.ident(arr));
369        let cond = format!("({}) >= 0 && ({}) < ({}.len() as i64)", i0, i0, arr_name);
370        writeln!(out, "{}debug_assert!({}, \"LOGOS oracle bounds hint violated: indexing `{}` out of range\");", indent_str, cond, arr_name).unwrap();
371        writeln!(
372            out,
373            "{}unsafe {{ std::hint::assert_unchecked({}); }}",
374            indent_str, cond
375        )
376        .unwrap();
377    }
378    if !out.is_empty() {
379        crate::optimize::mark_fired(crate::optimization::Opt::OracleHints);
380    }
381    out
382}
383
384fn collect_index_accesses_in_stmt<'a>(
385    stmt: &'a Stmt<'a>,
386    out: &mut Vec<(&'a Expr<'a>, &'a Expr<'a>)>,
387) {
388    match stmt {
389        Stmt::Let { value, .. } | Stmt::Set { value, .. } => collect_index_in_expr(value, out),
390        Stmt::SetIndex {
391            collection,
392            index,
393            value,
394        } => {
395            out.push((collection, index));
396            collect_index_in_expr(index, out);
397            collect_index_in_expr(value, out);
398        }
399        Stmt::If { cond, .. } | Stmt::While { cond, .. } => collect_index_in_expr(cond, out),
400        Stmt::Show { object, .. } | Stmt::Give { object, .. } => collect_index_in_expr(object, out),
401        Stmt::Return { value: Some(e) } => collect_index_in_expr(e, out),
402        Stmt::Push { value, .. } | Stmt::Add { value, .. } | Stmt::Remove { value, .. } => {
403            collect_index_in_expr(value, out)
404        }
405        _ => {}
406    }
407}
408
409fn collect_index_in_expr<'a>(e: &'a Expr<'a>, out: &mut Vec<(&'a Expr<'a>, &'a Expr<'a>)>) {
410    match e {
411        Expr::Index { collection, index } => {
412            out.push((collection, index));
413            collect_index_in_expr(collection, out);
414            collect_index_in_expr(index, out);
415        }
416        Expr::BinaryOp { left, right, .. } => {
417            collect_index_in_expr(left, out);
418            collect_index_in_expr(right, out);
419        }
420        Expr::Not { operand } => collect_index_in_expr(operand, out),
421        Expr::Call { args, .. } => {
422            for a in args.iter() {
423                collect_index_in_expr(a, out);
424            }
425        }
426        Expr::Length { collection } => collect_index_in_expr(collection, out),
427        _ => {}
428    }
429}
430
431/// AOT BCE-hoist: a row-major affine-offset bounds guard for one array in one
432/// loop. The index `item (offset + counter + 1) of arr` is BILINEAR (e.g.
433/// `c[i*n+j]`) — the `i*n` product defeats the linear bounds prover — but from
434/// the inner loop's view `offset` (`i*n`) is loop-INVARIANT, so the emitted
435/// index `offset + counter` is monotone in the counter. A single preheader
436/// `assert!` that `offset >= 0` and the MAX index `offset + (limit - 1) < len`
437/// lets the per-iteration access be elided soundly with no static nonlinear
438/// proof and no UB (it PANICS, never UB, on an out-of-range program).
439pub(crate) struct AffineOffsetGuard<'a> {
440    arr_sym: Symbol,
441    /// The loop-invariant offset (`i * n`).
442    offset: &'a Expr<'a>,
443    /// The emitted index `offset + counter` (`i*n + j`), for the body hint.
444    emitted_index: &'a Expr<'a>,
445    /// Every access index `(offset + counter) + 1` into the array, all of which the guard proves.
446    covered: Vec<&'a Expr<'a>>,
447}
448
449/// Match the 1-based row-major index `(offset + counter) + 1` whose emitted
450/// index is `offset + counter`. Returns `(offset, offset_plus_counter)` where
451/// `offset` is the operand that is NOT the bare counter.
452fn match_affine_offset_index<'a>(
453    index: &'a Expr<'a>,
454    counter: Symbol,
455) -> Option<(&'a Expr<'a>, &'a Expr<'a>)> {
456    if let Expr::BinaryOp {
457        op: BinaryOpKind::Add,
458        left,
459        right,
460    } = index
461    {
462        if matches!(right, Expr::Literal(Literal::Number(1))) {
463            if let Expr::BinaryOp {
464                op: BinaryOpKind::Add,
465                left: a,
466                right: b,
467            } = left
468            {
469                if matches!(b, Expr::Identifier(s) if *s == counter) {
470                    return Some((a, left));
471                }
472                if matches!(a, Expr::Identifier(s) if *s == counter) {
473                    return Some((b, left));
474                }
475            }
476        }
477    }
478    None
479}
480
481/// Plan the per-iteration `assert_unchecked` hints for row-major affine-offset accesses in an exclusive `while
482/// counter < limit` loop body: each access the loop's versioning guard proved in range
483/// ([`crate::optimize::facts::Fact::InBounds`], `optimize::version`), top-level in the body, to a `Vec`/slice that is
484/// not resized or rebound, with an offset fixed over the loop (not mentioning the counter, none of its symbols
485/// mutated). An access without the fact gets no hint and keeps its check. One guard per array.
486pub(crate) fn plan_affine_offset_guards<'a>(
487    body: &'a [Stmt<'a>],
488    counter_sym: Symbol,
489    is_exclusive: bool,
490    var_types: &HashMap<Symbol, String>,
491) -> Vec<AffineOffsetGuard<'a>> {
492    if !is_exclusive || body_has_early_exit(body) {
493        return Vec::new();
494    }
495    let mut guards: Vec<AffineOffsetGuard> = Vec::new();
496    let mut seen: HashSet<Symbol> = HashSet::new();
497    for stmt in body {
498        let mut accesses: Vec<(&Expr, &Expr)> = Vec::new();
499        collect_index_accesses_in_stmt(stmt, &mut accesses);
500        for (coll, index) in accesses {
501            let arr_sym = match coll {
502                Expr::Identifier(s) => *s,
503                _ => continue,
504            };
505            if !crate::optimize::facts::holds_expr(crate::optimize::facts::Fact::InBounds, index) {
506                continue;
507            }
508            let Some((offset, emitted)) = match_affine_offset_index(index, counter_sym) else {
509                continue;
510            };
511            let base_ty = var_types
512                .get(&arr_sym)
513                .map(|t| t.split("|__hl:").next().unwrap_or(t.as_str()));
514            let qualifies = matches!(
515                base_ty,
516                Some(t) if t.starts_with("Vec<") || t.starts_with("LogosSeq")
517                    || t.starts_with("&[") || t.starts_with("&mut [")
518            );
519            if !qualifies
520                || body_resizes_collection(body, arr_sym)
521                || body_modifies_var(body, arr_sym)
522            {
523                continue;
524            }
525            let mut osyms = Vec::new();
526            collect_expr_symbols(offset, &mut osyms);
527            if osyms.contains(&counter_sym)
528                || osyms
529                    .iter()
530                    .any(|s| body_modifies_var(body, *s) || body_mutates_collection(body, *s))
531            {
532                continue;
533            }
534            if seen.insert(arr_sym) {
535                guards.push(AffineOffsetGuard {
536                    arr_sym,
537                    offset,
538                    emitted_index: emitted,
539                    covered: vec![index],
540                });
541            } else if let Some(g) = guards
542                .iter_mut()
543                .find(|g| g.arr_sym == arr_sym && exprs_equal(g.offset, offset))
544            {
545                g.covered.push(index);
546            }
547        }
548    }
549    guards
550}
551
552/// Emit the per-iteration `assert_unchecked` for each affine-offset guard, at
553/// the top of the loop body. Sound because the preheader `assert!` proved the
554/// max index in range and the index is monotone in the (non-negative) counter.
555pub(crate) fn emit_affine_offset_header(
556    guards: &[AffineOffsetGuard],
557    interner: &Interner,
558    synced_vars: &HashSet<Symbol>,
559    async_functions: &HashSet<Symbol>,
560    var_types: &HashMap<Symbol, String>,
561    body_indent: &str,
562    output: &mut String,
563) {
564    let names = RustNames::new(interner);
565    for g in guards {
566        let arr = names.ident(g.arr_sym);
567        let e = codegen_expr_with_async(
568            g.emitted_index,
569            interner,
570            synced_vars,
571            async_functions,
572            var_types,
573        );
574        writeln!(
575            output,
576            "{}unsafe {{ std::hint::assert_unchecked(({e}) >= 0 && ({e}) < ({arr}.len() as i64)); }}",
577            body_indent, e = e, arr = arr
578        ).unwrap();
579    }
580}
581
582/// Emit a `Select` as a raw `tokio::select!` — the default (free-running) lowering and the
583/// no-arm-ready fallback of deterministic replay.
584#[allow(clippy::too_many_arguments)]
585fn write_tokio_select<'a>(
586    output: &mut String,
587    branches: &[crate::ast::stmt::SelectBranch<'a>],
588    interner: &Interner,
589    indent: usize,
590    mutable_vars: &HashSet<Symbol>,
591    ctx: &mut RefinementContext<'a>,
592    lww_fields: &HashSet<(String, String)>,
593    mv_fields: &HashSet<(String, String)>,
594    synced_vars: &mut HashSet<Symbol>,
595    var_caps: &HashMap<Symbol, VariableCapabilities>,
596    async_functions: &HashSet<Symbol>,
597    pipe_vars: &HashSet<Symbol>,
598    boxed_fields: &HashSet<(String, String, String)>,
599    registry: &TypeRegistry,
600    type_env: &crate::analysis::types::TypeEnv,
601) {
602    use crate::ast::stmt::SelectBranch;
603    let indent_str = "    ".repeat(indent);
604    writeln!(output, "{}tokio::select! {{", indent_str).unwrap();
605    for branch in branches {
606        match branch {
607            SelectBranch::Receive { var, pipe, body } => {
608                let var_name = interner.resolve(*var);
609                let pipe_str = codegen_expr_with_async(
610                    pipe,
611                    interner,
612                    synced_vars,
613                    async_functions,
614                    ctx.get_variable_types(),
615                );
616                let is_local_pipe = if let Expr::Identifier(sym) = pipe {
617                    pipe_vars.contains(sym)
618                } else {
619                    false
620                };
621                let suffix = if is_local_pipe { "_rx" } else { "" };
622                writeln!(
623                    output,
624                    "{}    {} = {}{}.recv() => {{",
625                    indent_str, var_name, pipe_str, suffix
626                )
627                .unwrap();
628                writeln!(
629                    output,
630                    "{}        if let Some({}) = {} {{",
631                    indent_str, var_name, var_name
632                )
633                .unwrap();
634                for stmt in *body {
635                    let stmt_code = codegen_stmt(
636                        stmt,
637                        interner,
638                        indent + 3,
639                        mutable_vars,
640                        ctx,
641                        lww_fields,
642                        mv_fields,
643                        synced_vars,
644                        var_caps,
645                        async_functions,
646                        pipe_vars,
647                        boxed_fields,
648                        registry,
649                        type_env,
650                    );
651                    write!(output, "{}", stmt_code).unwrap();
652                }
653                writeln!(output, "{}        }}", indent_str).unwrap();
654                writeln!(output, "{}    }}", indent_str).unwrap();
655            }
656            SelectBranch::Timeout { milliseconds, body } => {
657                let dur = match milliseconds {
658                    Expr::Literal(Literal::Duration(_)) => codegen_expr_with_async(
659                        milliseconds,
660                        interner,
661                        synced_vars,
662                        async_functions,
663                        ctx.get_variable_types(),
664                    ),
665                    Expr::Literal(Literal::Span { months, days }) => {
666                        let secs = ((*months as i64) * 30 + (*days as i64)) * 86_400;
667                        format!("std::time::Duration::from_secs({}u64)", secs.max(0))
668                    }
669                    _ => {
670                        let n = codegen_expr_with_async(
671                            milliseconds,
672                            interner,
673                            synced_vars,
674                            async_functions,
675                            ctx.get_variable_types(),
676                        );
677                        format!("std::time::Duration::from_secs({} as u64)", n)
678                    }
679                };
680                writeln!(
681                    output,
682                    "{}    _ = tokio::time::sleep({}) => {{",
683                    indent_str, dur
684                )
685                .unwrap();
686                for stmt in *body {
687                    let stmt_code = codegen_stmt(
688                        stmt,
689                        interner,
690                        indent + 2,
691                        mutable_vars,
692                        ctx,
693                        lww_fields,
694                        mv_fields,
695                        synced_vars,
696                        var_caps,
697                        async_functions,
698                        pipe_vars,
699                        boxed_fields,
700                        registry,
701                        type_env,
702                    );
703                    write!(output, "{}", stmt_code).unwrap();
704                }
705                writeln!(output, "{}    }}", indent_str).unwrap();
706            }
707        }
708    }
709    writeln!(output, "{}}}", indent_str).unwrap();
710}
711
712/// The future a Mode-A launch spawns. Each argument `(rendered, is_literal)` that is not a literal is
713/// evaluated where the launch stands and moved into the task, so a named value handed to two tasks is
714/// cloned once for each before either starts — never moved into the first — and in the order the
715/// interpreter evaluates them; a literal, which can neither move nor observe anything, stays in the
716/// call. `tail` follows the call (`.await`, a `;` to discard the result).
717fn launched_future(function: &str, args: &[(String, bool)], tail: &str) -> String {
718    let mut lets = String::new();
719    let mut call_args = Vec::with_capacity(args.len());
720    for (i, (value, literal)) in args.iter().enumerate() {
721        if *literal {
722            call_args.push(value.clone());
723        } else {
724            lets.push_str(&format!("let __logos_arg{i} = {value}; "));
725            call_args.push(format!("__logos_arg{i}"));
726        }
727    }
728    let future = format!(
729        "async move {{ {function}({}){tail} }}",
730        call_args.join(", ")
731    );
732    if lets.is_empty() {
733        future
734    } else {
735        format!("{{ {lets}{future} }}")
736    }
737}
738
739/// Emit a copy-on-write guard before an in-place mutation of `collection`, when the one gate
740/// ([`super::expr::cow_handle`]) says its buffer may be shared.
741pub(super) fn emit_cow(
742    collection: &Expr,
743    ctx: &RefinementContext,
744    names: &RustNames,
745    indent_str: &str,
746    output: &mut String,
747) {
748    if let Some(name) = super::expr::cow_handle(collection, ctx.get_variable_types(), names) {
749        writeln!(output, "{}{}.cow();", indent_str, name).unwrap();
750    }
751}
752
753/// If a loop body's sole write to a registered scratch buffer identifies it, return that buffer and its
754/// scalarization info. Only the buffer's own fill loop pushes it (post-fill reads are proven read-only by
755/// `detect_scratch_buffers`), so any loop that pushes a registered scratch buffer IS its fill loop.
756fn scratch_fill_target<'a>(
757    body: &[Stmt<'a>],
758    ctx: &RefinementContext<'a>,
759) -> Option<(Symbol, super::affine_array::ScratchInfo)> {
760    for s in body {
761        if let Stmt::Push {
762            collection: Expr::Identifier(c),
763            ..
764        } = s
765        {
766            if let Some(info) = ctx.scratch_buffer(*c) {
767                return Some((*c, info.clone()));
768            }
769        }
770    }
771    None
772}
773
774/// `Opt::StrideFill`: a loop storing one value into a bit-packed sequence at a fixed stride ([`super::bits::StrideFill`])
775/// as one strided fill, where the loop runs at all. The counter is left where the loop leaves it: the last value
776/// stored at, then the loop's own `Set j to j + step`, emitted as the loop would emit it.
777#[allow(clippy::too_many_arguments)]
778fn try_emit_stride_fill<'a>(
779    cond: &'a Expr<'a>,
780    body: Block<'a>,
781    interner: &Interner,
782    indent: usize,
783    mutable_vars: &HashSet<Symbol>,
784    ctx: &mut RefinementContext<'a>,
785    lww_fields: &HashSet<(String, String)>,
786    mv_fields: &HashSet<(String, String)>,
787    synced_vars: &mut HashSet<Symbol>,
788    var_caps: &HashMap<Symbol, VariableCapabilities>,
789    async_functions: &HashSet<Symbol>,
790    pipe_vars: &HashSet<Symbol>,
791    boxed_fields: &HashSet<(String, String, String)>,
792    registry: &TypeRegistry,
793    type_env: &crate::analysis::types::TypeEnv,
794    indent_str: &str,
795) -> Option<String> {
796    let config = crate::optimize::active_config();
797    if !config.is_on(crate::optimization::Opt::StrideFill)
798        || !config.is_on(crate::optimization::Opt::Unchecked)
799    {
800        return None;
801    }
802    let fill = super::bits::match_stride_fill(
803        cond,
804        body,
805        ctx.get_variable_types(),
806        ctx.oracle()?,
807        interner,
808    )?;
809    crate::optimize::mark_fired(crate::optimization::Opt::StrideFill);
810    crate::optimize::mark_fired(crate::optimization::Opt::Unchecked);
811    let names = RustNames::new(interner);
812    let types = ctx.get_variable_types();
813    let counter = names.ident(fill.counter);
814    let bits = names.ident(fill.bits);
815    let emit = |e: &Expr| codegen_expr_with_async(e, interner, synced_vars, async_functions, types);
816    let cond_str = codegen_expr_with_async_oracle(
817        cond,
818        interner,
819        synced_vars,
820        async_functions,
821        types,
822        ctx.oracle(),
823    );
824    let cond_str = truthy_cond_wrap(cond, cond_str, interner, types);
825    let (bound, step, value) = (emit(fill.bound), emit(fill.step), emit(fill.value));
826    let first = simplify_1based_index(fill.index, interner, false, types);
827    let below = if fill.strict { " - 1" } else { "" };
828    let inner = "    ".repeat(indent + 1);
829    let mut out = String::new();
830    writeln!(out, "{indent_str}if {cond_str} {{").unwrap();
831    writeln!(out, "{inner}let __sf_step: i64 = {step};").unwrap();
832    writeln!(
833        out,
834        "{inner}debug_assert!(({first}) >= 0, \"LOGOS oracle BCE: strided fill out of range\");"
835    )
836    .unwrap();
837    writeln!(
838        out,
839        "{inner}let __sf_more = unsafe {{ {bits}.fill_stride_through_unchecked(({first}) as usize, ({first}).wrapping_add((({bound}) as i64{below}).wrapping_sub({counter})) as usize, __sf_step as usize, {value}) }} as i64;"
840    )
841    .unwrap();
842    writeln!(out, "{inner}{counter} = {counter} + __sf_more * __sf_step;").unwrap();
843    out.push_str(&codegen_stmt(
844        fill.increment,
845        interner,
846        indent + 1,
847        mutable_vars,
848        ctx,
849        lww_fields,
850        mv_fields,
851        synced_vars,
852        var_caps,
853        async_functions,
854        pipe_vars,
855        boxed_fields,
856        registry,
857        type_env,
858    ));
859    writeln!(out, "{indent_str}}}").unwrap();
860    Some(out)
861}
862
863/// The `While` arm of [`codegen_stmt`]: the loop walker: it recurses into the body, so it sits on the stack at every nesting level.
864#[inline(never)]
865#[allow(clippy::too_many_arguments)]
866fn codegen_while_stmt<'a>(
867    mut output: String,
868    stmt: &Stmt<'a>,
869    cond: &&'a Expr<'a>,
870    body: &Block<'a>,
871    interner: &Interner,
872    indent: usize,
873    mutable_vars: &HashSet<Symbol>,
874    ctx: &mut RefinementContext<'a>,
875    lww_fields: &HashSet<(String, String)>,
876    mv_fields: &HashSet<(String, String)>,
877    synced_vars: &mut HashSet<Symbol>,
878    var_caps: &HashMap<Symbol, VariableCapabilities>,
879    async_functions: &HashSet<Symbol>,
880    pipe_vars: &HashSet<Symbol>,
881    boxed_fields: &HashSet<(String, String, String)>,
882    registry: &TypeRegistry,
883    type_env: &crate::analysis::types::TypeEnv,
884    indent_str: &str,
885) -> String {
886    // bcmp idiom: a fixed-window byte-compare loop collapses to a slice
887    // inequality (LLVM `bcmp`) — try it before the scalar while codegen.
888    if let Some(code) = try_emit_byte_compare_window(
889        stmt,
890        interner,
891        indent,
892        ctx.get_variable_types(),
893        ctx.oracle(),
894    ) {
895        return code;
896    }
897    if let Some(code) = try_emit_stride_fill(
898        *cond,
899        *body,
900        interner,
901        indent,
902        mutable_vars,
903        ctx,
904        lww_fields,
905        mv_fields,
906        synced_vars,
907        var_caps,
908        async_functions,
909        pipe_vars,
910        boxed_fields,
911        registry,
912        type_env,
913        indent_str,
914    ) {
915        output.push_str(&code);
916        return output;
917    }
918    // decreasing is compile-time only, ignored at runtime
919
920    // OPT: Loop bounds hoisting.
921    // Collect all `length of X` symbols from condition AND body where X is
922    // not modified in the loop. Emit hoisted `let x_len = (x.len() as i64);`
923    // bindings before the loop. Register a sentinel in variable_types so that
924    // Expr::Length codegen emits the hoisted name directly (no string replacement).
925    let mut all_length_syms_raw = extract_length_expr_syms(cond);
926    collect_length_syms_from_stmts(body, &mut all_length_syms_raw);
927    let mut seen = HashSet::new();
928    let all_length_syms: Vec<Symbol> = all_length_syms_raw
929        .into_iter()
930        .filter(|s| seen.insert(*s))
931        .collect();
932
933    let mut hoisted_syms: Vec<(Symbol, Option<String>)> = Vec::new();
934    for len_sym in &all_length_syms {
935        // An affine read-only array is deleted; `length of` it is its trip
936        // count (no `.len()` to hoist). Leave its `__affine_array:` tag intact.
937        if ctx.affine_array(*len_sym).is_some() {
938            continue;
939        }
940        if !body_mutates_collection(body, *len_sym)
941            && !body_modifies_var(body, *len_sym)
942            && !body_declares_var(body, *len_sym)
943        {
944            let name = interner.resolve(*len_sym);
945            let hoisted_name = format!("{}_len", name);
946            writeln!(
947                output,
948                "{}let {} = ({}.len() as i64);",
949                indent_str, hoisted_name, name
950            )
951            .unwrap();
952            let old_type = ctx.get_variable_types().get(len_sym).cloned();
953            // Append hoisted sentinel to existing type string. Expr::Length checks
954            // for |__hl: suffix to emit the hoisted name. All other type checks
955            // use starts_with() so the suffix doesn't interfere.
956            let new_type = match &old_type {
957                Some(existing) => format!("{}|__hl:{}", existing, hoisted_name),
958                None => format!("|__hl:{}", hoisted_name),
959            };
960            ctx.register_variable_type(*len_sym, new_type);
961            hoisted_syms.push((*len_sym, old_type));
962        }
963    }
964
965    // OPT-9: bounds hints for arrays indexed by a unit-stepping while
966    // counter (`while counter <= bound:` / `< bound:`). Unlike the
967    // for-range site, this loop shape guarantees nothing by
968    // construction, so everything plan_bounds_hints assumes must be
969    // checked here: the counter takes every value up to the bound
970    // (unit increment last, no other counter writes) and the bound is
971    // loop-invariant.
972    let mut while_bounds_hints: Vec<BoundsHintPlan> = Vec::new();
973    let mut affine_guards: Vec<AffineOffsetGuard> = Vec::new();
974    if let Expr::BinaryOp {
975        op: op @ (BinaryOpKind::LtEq | BinaryOpKind::Lt),
976        left: Expr::Identifier(counter_sym),
977        right: bound_expr,
978    } = cond
979    {
980        let body_sans_inc =
981            if !body.is_empty() && is_counter_increment(&body[body.len() - 1], *counter_sym) {
982                Some(&body[..body.len() - 1])
983            } else {
984                None
985            };
986        if let Some(body_sans_inc) = body_sans_inc {
987            let counter_clean = !body_modifies_var(body_sans_inc, *counter_sym);
988            let mut bound_syms = Vec::new();
989            collect_expr_symbols(bound_expr, &mut bound_syms);
990            let bound_invariant = bound_syms
991                .iter()
992                .all(|s| !body_modifies_var(body, *s) && !body_mutates_collection(body, *s));
993            if counter_clean && bound_invariant {
994                let bound_str = codegen_expr_with_async(
995                    bound_expr,
996                    interner,
997                    synced_vars,
998                    async_functions,
999                    ctx.get_variable_types(),
1000                );
1001                while_bounds_hints = plan_bounds_hints(
1002                    body_sans_inc,
1003                    *counter_sym,
1004                    matches!(op, BinaryOpKind::Lt),
1005                    false,
1006                    bound_expr,
1007                    &bound_str,
1008                    ctx.get_variable_types(),
1009                );
1010                emit_bounds_hint_preheader(&while_bounds_hints, interner, &indent_str, &mut output);
1011
1012                // Row-major affine-offset accesses the loop's versioning guard proved in range get a
1013                // per-iteration hint in the body (`plan_affine_offset_guards`).
1014                affine_guards = plan_affine_offset_guards(
1015                    body_sans_inc,
1016                    *counter_sym,
1017                    matches!(op, BinaryOpKind::Lt),
1018                    ctx.get_variable_types(),
1019                );
1020            }
1021        }
1022    }
1023
1024    // Scratch-buffer allocation hoisting: a loop-local buffer that is
1025    // freshly allocated, fully overwritten by a copy of a source slice,
1026    // used/mutated in place, and never escapes the iteration is hoisted
1027    // to ONE allocation before the loop and reused (`clear()` +
1028    // `extend_from_slice`) each iteration — eliminating one malloc/free
1029    // per iteration (fannkuch's `perm`: ~n! of them). Value-identical to
1030    // the per-iteration `.to_vec()`; gated on the de-Rc non-escape proof.
1031    let scratch_hoisted: Vec<Symbol> =
1032        super::peephole::detect_scratch_hoist_in_body(body, interner, ctx)
1033            .into_iter()
1034            .map(|(dst, elem_type)| {
1035                writeln!(
1036                    output,
1037                    "{}let mut {}: Vec<{}> = Vec::new();",
1038                    indent_str,
1039                    interner.resolve(dst),
1040                    elem_type
1041                )
1042                .unwrap();
1043                ctx.register_variable_type(dst, format!("Vec<{}>", elem_type));
1044                ctx.register_scratch_hoist(dst);
1045                dst
1046            })
1047            .collect();
1048
1049    // O1: scope-extract per-handle borrows around the whole while
1050    // loop when the alias oracle proves it sound. The cond is part of
1051    // the access scan; opened before cond emission so the condition
1052    // also indexes slices.
1053    let hoist_plan = super::hoist::plan_borrow_hoist(stmt, Some(cond), body, ctx, interner);
1054    super::hoist::emit_hoist_open(&hoist_plan, interner, &indent_str, ctx, &mut output);
1055
1056    let cond_str = codegen_expr_with_async_oracle(
1057        cond,
1058        interner,
1059        synced_vars,
1060        async_functions,
1061        ctx.get_variable_types(),
1062        ctx.oracle(),
1063    );
1064    let cond_str = truthy_cond_wrap(cond, cond_str, interner, ctx.get_variable_types());
1065    let loop_start = output.len();
1066    writeln!(output, "{}while {} {{", indent_str, cond_str).unwrap();
1067    emit_bounds_hint_header(
1068        &while_bounds_hints,
1069        interner,
1070        &"    ".repeat(indent + 1),
1071        &mut output,
1072    );
1073    emit_affine_offset_header(
1074        &affine_guards,
1075        interner,
1076        synced_vars,
1077        async_functions,
1078        ctx.get_variable_types(),
1079        &"    ".repeat(indent + 1),
1080        &mut output,
1081    );
1082    ctx.push_scope();
1083
1084    // OPT-5: Extract sentinel context from while condition.
1085    // For `While counter < limit:`, detect `Set counter to limit` inside If blocks
1086    // as sentinel exits and replace with `break`.
1087    let sentinel_ctx: Option<(Symbol, &Expr)> = match cond {
1088        Expr::BinaryOp {
1089            op: BinaryOpKind::Lt,
1090            left,
1091            right,
1092        } => {
1093            if let Expr::Identifier(sym) = left {
1094                Some((*sym, *right))
1095            } else {
1096                None
1097            }
1098        }
1099        _ => None,
1100    };
1101
1102    // Peephole: process body statements with peephole optimizations.
1103    let body_refs: Vec<&Stmt> = body.iter().collect();
1104    let mut bi = 0;
1105    while bi < body_refs.len() {
1106        if let Some((code, skip)) = super::peephole::try_block_peepholes(
1107            &body_refs,
1108            bi,
1109            interner,
1110            indent + 1,
1111            mutable_vars,
1112            ctx,
1113            lww_fields,
1114            mv_fields,
1115            synced_vars,
1116            var_caps,
1117            async_functions,
1118            pipe_vars,
1119            boxed_fields,
1120            registry,
1121            type_env,
1122        ) {
1123            output.push_str(&code);
1124            bi += 1 + skip;
1125            continue;
1126        }
1127        // Drain-tail optimization: If a branch in the while body is a
1128        // loop-invariant sequential drain (push-from-array + increment), emit
1129        // extend_from_slice + break instead of element-by-element push.
1130        if let Some(code) = try_emit_drain_tail_in_while(
1131            body_refs[bi],
1132            cond,
1133            interner,
1134            indent + 1,
1135            mutable_vars,
1136            ctx,
1137            lww_fields,
1138            mv_fields,
1139            synced_vars,
1140            var_caps,
1141            async_functions,
1142            pipe_vars,
1143            boxed_fields,
1144            registry,
1145            type_env,
1146        ) {
1147            output.push_str(&code);
1148            bi += 1;
1149            continue;
1150        }
1151        // OPT-5: Sentinel → break transformation.
1152        // If this statement is an If whose then_block ends with `Set counter to limit`,
1153        // emit break instead of the sentinel set.
1154        if let Some((counter_sym, limit_expr)) = &sentinel_ctx {
1155            if let Some(code) = try_emit_sentinel_break(
1156                body_refs[bi],
1157                *counter_sym,
1158                limit_expr,
1159                interner,
1160                indent + 1,
1161                mutable_vars,
1162                ctx,
1163                lww_fields,
1164                mv_fields,
1165                synced_vars,
1166                var_caps,
1167                async_functions,
1168                pipe_vars,
1169                boxed_fields,
1170                registry,
1171                type_env,
1172            ) {
1173                // This peephole emits the If inline (bypassing codegen_stmt),
1174                // so the oracle bounds hints for index accesses in its guard
1175                // (string_search's `text[i+j]`) must be emitted here too.
1176                output.push_str(&emit_oracle_index_hints(
1177                    body_refs[bi],
1178                    ctx,
1179                    interner,
1180                    registry,
1181                    &"    ".repeat(indent + 1),
1182                ));
1183                output.push_str(&code);
1184                bi += 1;
1185                continue;
1186            }
1187        }
1188        output.push_str(&codegen_stmt(
1189            body_refs[bi],
1190            interner,
1191            indent + 1,
1192            mutable_vars,
1193            ctx,
1194            lww_fields,
1195            mv_fields,
1196            synced_vars,
1197            var_caps,
1198            async_functions,
1199            pipe_vars,
1200            boxed_fields,
1201            registry,
1202            type_env,
1203        ));
1204        bi += 1;
1205    }
1206    ctx.pop_scope();
1207
1208    // Restore original variable_types for hoisted symbols.
1209    // variable_types is a flat HashMap (not scoped), so push/pop_scope doesn't clean it.
1210    for (sym, old_type) in hoisted_syms {
1211        if let Some(old) = old_type {
1212            ctx.register_variable_type(sym, old);
1213        } else {
1214            ctx.get_variable_types_mut().remove(&sym);
1215        }
1216    }
1217
1218    // Stop treating the hoisted scratch buffers as reused once their
1219    // loop closes, so a same-named buffer in a sibling loop is not
1220    // mis-rewritten into a refill of a buffer that was never hoisted.
1221    for dst in scratch_hoisted {
1222        ctx.clear_scratch_hoist(dst);
1223    }
1224
1225    writeln!(output, "{}}}", indent_str).unwrap();
1226    super::peephole::version_on_bounds_hints(
1227        &mut output,
1228        loop_start,
1229        &while_bounds_hints,
1230        body,
1231        ctx.oracle(),
1232        interner,
1233        &indent_str,
1234    );
1235    // Close the borrow-hoist scope and restore slice-shadowed types.
1236    super::hoist::emit_hoist_close(&hoist_plan, &indent_str, ctx, &mut output);
1237    output
1238}
1239
1240/// Mark the body's accesses `item counter of arr` that a literal range proves in range: `counter` runs over
1241/// `lo..=hi` with `1 <= lo`, `arr` is a fixed-size `[T; N]` with `hi <= N`, and nothing in the body binds
1242/// `counter` anew, so every such access names an item. A closure or a nested function is another scope, where
1243/// `counter` may name a parameter; its accesses keep the rule.
1244fn mark_fixed_array_counter_accesses(
1245    counter: Symbol,
1246    iterable: &Expr,
1247    body: &[Stmt],
1248    var_types: &HashMap<Symbol, String>,
1249) {
1250    let Expr::Range { start, end } = iterable else {
1251        return;
1252    };
1253    let (Expr::Literal(Literal::Number(lo)), Expr::Literal(Literal::Number(hi))) = (start, end)
1254    else {
1255        return;
1256    };
1257    if *lo < 1 || crate::optimize::WriteSet::of_block(body).may_write(counter) {
1258        return;
1259    }
1260    let fixed_len = |arr: Symbol| -> Option<i64> {
1261        let t = var_types.get(&arr)?;
1262        let t = t.split("|__hl:").next().unwrap_or(t.as_str());
1263        t.strip_prefix('[')?
1264            .strip_suffix(']')?
1265            .rsplit_once("; ")?
1266            .1
1267            .trim()
1268            .parse()
1269            .ok()
1270    };
1271    use logicaffeine_language::ast_depth::{walk_nodes, Visited, Walk};
1272    walk_nodes(body, |node| {
1273        let (arr, index) = match node {
1274            Visited::Stmt(Stmt::FunctionDef { .. }) | Visited::Expr(Expr::Closure { .. }) => {
1275                return Walk::Past
1276            }
1277            Visited::Expr(Expr::Index {
1278                collection: Expr::Identifier(arr),
1279                index,
1280            }) => (*arr, *index),
1281            Visited::Stmt(Stmt::SetIndex {
1282                collection: Expr::Identifier(arr),
1283                index,
1284                ..
1285            }) => (*arr, *index),
1286            _ => return Walk::Into,
1287        };
1288        if matches!(index, Expr::Identifier(s) if *s == counter)
1289            && fixed_len(arr).is_some_and(|n| *hi <= n)
1290        {
1291            super::expr::mark_index_in_range(index);
1292        }
1293        Walk::Into
1294    });
1295}
1296
1297/// The `Repeat` arm of [`codegen_stmt`]: an arm of [`codegen_stmt`], in a frame of its own — see [`codegen_let_stmt`].
1298#[inline(never)]
1299#[allow(clippy::too_many_arguments)]
1300fn codegen_repeat_stmt<'a>(
1301    mut output: String,
1302    repeat: &Stmt<'a>,
1303    pattern: &Pattern,
1304    iterable: &&'a Expr<'a>,
1305    body: &Block<'a>,
1306    interner: &Interner,
1307    indent: usize,
1308    mutable_vars: &HashSet<Symbol>,
1309    ctx: &mut RefinementContext<'a>,
1310    lww_fields: &HashSet<(String, String)>,
1311    mv_fields: &HashSet<(String, String)>,
1312    synced_vars: &mut HashSet<Symbol>,
1313    var_caps: &HashMap<Symbol, VariableCapabilities>,
1314    async_functions: &HashSet<Symbol>,
1315    pipe_vars: &HashSet<Symbol>,
1316    boxed_fields: &HashSet<(String, String, String)>,
1317    registry: &TypeRegistry,
1318    type_env: &crate::analysis::types::TypeEnv,
1319    indent_str: &str,
1320    names: &RustNames,
1321) -> String {
1322    use crate::ast::stmt::Pattern;
1323
1324    // The loop's bindings. A body that sets one (`Set t to t + 10`) changes it for the rest of that pass,
1325    // and the next pass binds the next item, so Rust needs that binding `mut`.
1326    let written = crate::optimize::WriteSet::of_block(body);
1327    let binding = |sym: Symbol| {
1328        let name = interner.resolve(sym);
1329        if written.may_write(sym) {
1330            format!("mut {name}")
1331        } else {
1332            name.to_string()
1333        }
1334    };
1335    let pattern_str = match pattern {
1336        Pattern::Identifier(sym) => binding(*sym),
1337        Pattern::Tuple(syms) => {
1338            let names = syms.iter().map(|s| binding(*s)).collect::<Vec<_>>().join(", ");
1339            format!("({})", names)
1340        }
1341    };
1342
1343    // A `Repeat` over a value of the exact extension binds each of its items, a `LogosValue`.
1344    if super::tower::is_tower_expr(iterable, ctx.get_variable_types(), interner) {
1345        let items = super::tower::statement_value(
1346            iterable,
1347            interner,
1348            synced_vars,
1349            async_functions,
1350            boxed_fields,
1351            registry,
1352            ctx.get_variable_types(),
1353        );
1354        let bound: Vec<Symbol> = match pattern {
1355            Pattern::Identifier(sym) => {
1356                writeln!(
1357                    output,
1358                    "{}for {} in logicaffeine_data::failure::answered(({}).items()) {{",
1359                    indent_str, pattern_str, items
1360                )
1361                .unwrap();
1362                vec![*sym]
1363            }
1364            Pattern::Tuple(syms) => {
1365                writeln!(
1366                    output,
1367                    "{}for __tower_item in logicaffeine_data::failure::answered(({}).items()) {{",
1368                    indent_str, items
1369                )
1370                .unwrap();
1371                for (k, sym) in syms.iter().enumerate() {
1372                    writeln!(
1373                        output,
1374                        "{}    let {}: {} = logicaffeine_data::failure::answered(__tower_item.item(&LogosValue::Int({}_i64)));",
1375                        indent_str,
1376                        binding(*sym),
1377                        super::tower::VALUE,
1378                        k + 1
1379                    )
1380                    .unwrap();
1381                }
1382                syms.clone()
1383            }
1384        };
1385        ctx.push_scope();
1386        let shadowed: Vec<(Symbol, Option<String>)> = bound
1387            .iter()
1388            .map(|sym| (*sym, ctx.get_variable_types().get(sym).cloned()))
1389            .collect();
1390        for sym in &bound {
1391            ctx.register_variable_type(*sym, super::tower::VALUE.to_string());
1392        }
1393        for s in body.iter() {
1394            output.push_str(&codegen_stmt(
1395                s,
1396                interner,
1397                indent + 1,
1398                mutable_vars,
1399                ctx,
1400                lww_fields,
1401                mv_fields,
1402                synced_vars,
1403                var_caps,
1404                async_functions,
1405                pipe_vars,
1406                boxed_fields,
1407                registry,
1408                type_env,
1409            ));
1410        }
1411        for (sym, before) in shadowed {
1412            match before {
1413                Some(t) => ctx.register_variable_type(sym, t),
1414                None => {
1415                    ctx.get_variable_types_mut().remove(&sym);
1416                }
1417            }
1418        }
1419        ctx.pop_scope();
1420        writeln!(output, "{}}}", indent_str).unwrap();
1421        return output;
1422    }
1423
1424    // A `Repeat` over a value-or-nothing list iterates the list it holds; one over a list of them binds each item as one.
1425    let held = match pattern {
1426        Pattern::Identifier(item) => {
1427            let ecx = operand_ctx(interner, ctx, synced_vars, async_functions, boxed_fields, registry);
1428            super::absent::iteration(iterable, &ecx).map(|(items, ty)| (*item, items, ty))
1429        }
1430        Pattern::Tuple(_) => None,
1431    };
1432    if let Some((item, items, ty)) = held {
1433        writeln!(output, "{}for {} in {} {{", indent_str, pattern_str, items).unwrap();
1434        ctx.push_scope();
1435        let before = ctx.get_variable_types().get(&item).cloned();
1436        ctx.register_variable_type(item, ty);
1437        for s in body.iter() {
1438            output.push_str(&codegen_stmt(
1439                s,
1440                interner,
1441                indent + 1,
1442                mutable_vars,
1443                ctx,
1444                lww_fields,
1445                mv_fields,
1446                synced_vars,
1447                var_caps,
1448                async_functions,
1449                pipe_vars,
1450                boxed_fields,
1451                registry,
1452                type_env,
1453            ));
1454        }
1455        match before {
1456            Some(t) => ctx.register_variable_type(item, t),
1457            None => {
1458                ctx.get_variable_types_mut().remove(&item);
1459            }
1460        }
1461        ctx.pop_scope();
1462        writeln!(output, "{}}}", indent_str).unwrap();
1463        return output;
1464    }
1465
1466    // Indexed-buffer zero-init loop: dropped — the `let mut buf: [T; N] = [0; N]` the O3 `Let`
1467    // handler already emitted zeroes every slot, and the subsequent `Set item i of buf` writes hit
1468    // the array directly. (A push-fill of a `[T; N]` array would be wrong: the fill counter is
1469    // compile-time, so a runtime loop would set slot 0 repeatedly.)
1470    if super::affine_array::is_indexed_init_loop(body, |s| ctx.is_indexed_buffer(s)) {
1471        return output;
1472    }
1473
1474    // Scratch-buffer scalarization: a counted loop whose sole job is to fill a registered
1475    // fixed-size, non-escaping buffer is emitted in place as `let w: [T; N] = from_fn(|__k| { let
1476    // j = LO + __k; <body-lets>; <push-val> })` — a single stack array — instead of a `Vec` that a
1477    // per-entry push loop reallocates on every entry. All non-push body statements (intermediate
1478    // `Let`s) become the closure's leading `let`s; the sole `Push`'s value is the tail expression.
1479    if let Pattern::Identifier(loop_var) = pattern {
1480        if let Some((w, info)) = scratch_fill_target(body, ctx) {
1481            let wname = names.ident(w);
1482            writeln!(
1483                output,
1484                "{}let {}{}: [{}; {}] = ::std::array::from_fn(|__k: usize| {{",
1485                indent_str,
1486                if info.mutated { "mut " } else { "" },
1487                wname,
1488                info.elem_ty,
1489                info.len
1490            )
1491            .unwrap();
1492            writeln!(
1493                output,
1494                "{}    let {} = ({} as i64) + (__k as i64);",
1495                indent_str,
1496                interner.resolve(*loop_var),
1497                info.lo
1498            )
1499            .unwrap();
1500            ctx.push_scope();
1501            ctx.register_variable_type(*loop_var, "i64".to_string());
1502            let mut push_val: Option<&Expr> = None;
1503            for s in body.iter() {
1504                match s {
1505                    Stmt::Push {
1506                        collection: Expr::Identifier(c),
1507                        value,
1508                    } if *c == w => {
1509                        push_val = Some(value);
1510                    }
1511                    other => output.push_str(&codegen_stmt(
1512                        other,
1513                        interner,
1514                        indent + 1,
1515                        mutable_vars,
1516                        ctx,
1517                        lww_fields,
1518                        mv_fields,
1519                        synced_vars,
1520                        var_caps,
1521                        async_functions,
1522                        pipe_vars,
1523                        boxed_fields,
1524                        registry,
1525                        type_env,
1526                    )),
1527                }
1528            }
1529            let val = codegen_expr_boxed_with_types_oracle(
1530                push_val.expect("scratch fill loop has exactly one push"),
1531                interner,
1532                synced_vars,
1533                boxed_fields,
1534                registry,
1535                async_functions,
1536                ctx.get_string_vars(),
1537                ctx.get_variable_types(),
1538                ctx.get_fast_div(),
1539                ctx.oracle(),
1540            );
1541            writeln!(output, "{}    {}", indent_str, val).unwrap();
1542            ctx.pop_scope();
1543            writeln!(output, "{}}});", indent_str).unwrap();
1544            return output;
1545        }
1546    }
1547
1548    let iter_str = codegen_expr_with_async(
1549        iterable,
1550        interner,
1551        synced_vars,
1552        async_functions,
1553        ctx.get_variable_types(),
1554    );
1555    if let Pattern::Identifier(counter) = pattern {
1556        mark_fixed_array_counter_accesses(*counter, iterable, body, ctx.get_variable_types());
1557    }
1558
1559    // OPT-PAR: Automatic parallelization for commutative reduction patterns.
1560    // Detect: Repeat for x in coll: Set acc = acc + expr(x)
1561    // Emit: acc += coll.par_iter().copied().map(|x| expr).sum::<i64>()
1562    let par_emitted = if let Pattern::Identifier(var_sym) = pattern {
1563        if let Some(par_code) = try_emit_parallel_reduction(
1564            *var_sym,
1565            &pattern_str,
1566            &iter_str,
1567            iterable,
1568            body,
1569            interner,
1570            indent,
1571            ctx,
1572            synced_vars,
1573            async_functions,
1574        ) {
1575            output.push_str(&par_code);
1576            true
1577        } else {
1578            false
1579        }
1580    } else {
1581        false
1582    };
1583
1584    if par_emitted {
1585        // Parallel code already emitted — skip normal loop codegen
1586    } else if body
1587        .iter()
1588        .any(|s| requires_async_stmt(s) || calls_async_function(s, async_functions))
1589    {
1590        // Use while-let with explicit iterator for async compatibility
1591        writeln!(
1592            output,
1593            "{}let mut __iter = ({}).into_iter();",
1594            indent_str, iter_str
1595        )
1596        .unwrap();
1597        writeln!(
1598            output,
1599            "{}while let Some({}) = __iter.next() {{",
1600            indent_str, pattern_str
1601        )
1602        .unwrap();
1603    } else {
1604        // Determine iteration strategy based on collection type
1605        let is_logos_seq = if let Expr::Identifier(coll_sym) = iterable {
1606            ctx.get_variable_types()
1607                .get(coll_sym)
1608                .map(|s| s.split("|__hl:").next().unwrap_or(s.as_str()))
1609                .map_or(false, |t| t.starts_with("LogosSeq"))
1610        } else {
1611            false
1612        };
1613        // `TextBytes` is the zero-copy `&[u8]` byte-view (Opt::TextBytesView): iterating it
1614        // yields each byte widened to the `i64` the body expects, over the borrowed slice.
1615        let is_text_bytes = if let Expr::Identifier(coll_sym) = iterable {
1616            ctx.get_variable_types()
1617                .get(coll_sym)
1618                .map(|s| s.split("|__hl:").next().unwrap_or(s.as_str()))
1619                .map_or(false, |t| t == "TextBytes")
1620        } else {
1621            false
1622        };
1623
1624        // ★ `For each c in <Text>` WALKS CHARACTERS. A `String` is not an iterator, so the default
1625        // `.clone()` below emitted Rust that does not compile — and this sentence is how the whole
1626        // standard library reads text: `htmlEscape` escapes one character at a time, `isIntText`
1627        // validates one at a time, `urlDecode` scans for an escape. None of them could be built
1628        // for the AOT tier, and nothing said so, because the refusal is invalid Rust in a string
1629        // the compiler returns as `Ok`.
1630        //
1631        // Each `c` is a one-character TEXT, which is what the body expects: LOGOS compares it with
1632        // `c is equal to "&"` and concatenates it. CHARACTERS, not bytes — a check mark is three
1633        // UTF-8 bytes and one character, and a byte walk would hand the body a fragment that is
1634        // not a character at all.
1635        let iterates_text = matches!(
1636            super::types::infer_logos_type(iterable, interner, ctx.get_variable_types()),
1637            crate::analysis::types::LogosType::String
1638        );
1639        if let (Pattern::Identifier(_), Expr::Range { start, end }) = (pattern, iterable) {
1640            let emit = |e: &Expr| {
1641                let ecx = super::expr::ExprCtx {
1642                    async_functions,
1643                    variable_types: ctx.get_variable_types(),
1644                    ..super::expr::ExprCtx::bare(interner, synced_vars)
1645                };
1646                super::rational::integer_operand(e, crate::semantics::collections::IntegerPlace::Range, &ecx)
1647                    .unwrap_or_else(|| {
1648                        codegen_expr_with_async(
1649                            e,
1650                            interner,
1651                            synced_vars,
1652                            async_functions,
1653                            ctx.get_variable_types(),
1654                        )
1655                    })
1656            };
1657            let (start_str, end_str) = super::expr::range_bound_strs(start, end, emit);
1658            let range =
1659                super::expr::counted_loop_range(start, end, &start_str, &end_str, ctx.oracle());
1660            writeln!(output, "{}for {} in {} {{", indent_str, pattern_str, range).unwrap();
1661        } else if iterates_text {
1662            // The bound name is a `String`, and saying so is what makes the rest of the body
1663            // compile: a non-Copy loop variable read twice needs the `.clone()` the identifier
1664            // emitter adds only for a variable whose type it knows. `htmlEscape`'s
1665            // `Let mutable piece be c.` followed by `If c is equal to "&"` is exactly that shape.
1666            if let Pattern::Identifier(sym) = pattern {
1667                ctx.register_variable_type(*sym, "String".to_string());
1668            }
1669            writeln!(
1670                output,
1671                "{}for {} in {}.chars().map(|__c| __c.to_string()).collect::<Vec<String>>() {{",
1672                indent_str, pattern_str, iter_str
1673            )
1674            .unwrap();
1675        } else if is_text_bytes {
1676            // ── OPT TextBytesView (iteration) ───────────────────────────────
1677            // `for b in sb` over the borrowed `&[u8]` view yields each byte widened
1678            // to `i64` — no `Vec<i64>`, no clone. The loop variable is an `i64`.
1679            if let Pattern::Identifier(sym) = pattern {
1680                ctx.register_variable_type(*sym, "i64".to_string());
1681            }
1682            writeln!(
1683                output,
1684                "{}for {} in {}.iter().map(|&__x| __x as i64) {{",
1685                indent_str, pattern_str, iter_str
1686            )
1687            .unwrap();
1688        } else if is_logos_seq {
1689            // A `Seq` nothing in the loop can change is iterated through a shared borrow of its buffer, which is the
1690            // snapshot every tier iterates (`optimize::iteration`); `.copied()` for a `Copy` element, the lazy
1691            // per-element `.cloned()` otherwise. Any other loop iterates an owned copy taken on entry.
1692            let coll = match iterable {
1693                Expr::Identifier(xs) => Some(*xs),
1694                _ => None,
1695            };
1696            let lent = crate::optimize::facts::holds_stmt(
1697                crate::optimize::facts::Fact::LentIteration,
1698                repeat,
1699            );
1700            if lent {
1701                crate::optimize::mark_fired(crate::optimization::Opt::Borrow);
1702                let seq_ty = coll
1703                    .and_then(|xs| ctx.get_variable_types().get(&xs))
1704                    .cloned()
1705                    .unwrap_or_default();
1706                let held = seq_ty.split("|__hl:").next().unwrap_or(&seq_ty);
1707                let elem = held
1708                    .strip_prefix("LogosSeq<")
1709                    .and_then(|t| t.strip_suffix('>'))
1710                    .unwrap_or("_");
1711                let each = if is_copy_type(elem) {
1712                    "copied"
1713                } else {
1714                    "cloned"
1715                };
1716                writeln!(
1717                    output,
1718                    "{}for {} in {}.borrow().iter().{}() {{",
1719                    indent_str, pattern_str, iter_str, each
1720                )
1721                .unwrap();
1722            } else {
1723                writeln!(
1724                    output,
1725                    "{}for {} in {}.to_vec() {{",
1726                    indent_str, pattern_str, iter_str
1727                )
1728                .unwrap();
1729            }
1730        } else {
1731            // Optimization: for known Vec<T>/&[T] with Copy element type,
1732            // use .iter().copied() instead of .clone() to avoid copying the entire collection.
1733            // For slices, must use .iter() since .clone() on &[T] clones the reference, not the data.
1734            let (use_iter_copied, use_iter_cloned) = if let Expr::Identifier(coll_sym) = iterable {
1735                if let Some(coll_type_raw) = ctx.get_variable_types().get(coll_sym) {
1736                    // Strip |__hl: hoisting suffix so strip_suffix(']') works correctly.
1737                    let coll_type = coll_type_raw
1738                        .split("|__hl:")
1739                        .next()
1740                        .unwrap_or(coll_type_raw.as_str());
1741                    if coll_type.starts_with('[') {
1742                        // O3 fixed array `[T; N]` — iterate by borrow so the array is not consumed.
1743                        let elem = coll_type
1744                            .strip_prefix('[')
1745                            .and_then(|s| s.split(';').next())
1746                            .unwrap_or("_")
1747                            .trim();
1748                        if is_copy_type(elem) {
1749                            (true, false)
1750                        } else {
1751                            (false, true)
1752                        }
1753                    } else if coll_type.starts_with("&[") {
1754                        // Borrowed slice `&[T]` or fixed-array ref `&[T; N]`: must use .iter() (can't
1755                        // move/clone a borrowed slice). Take the element type before any `; N` length so
1756                        // a `&[i64; 3]` param iterates by `.copied()` exactly like the `&[i64]` slice.
1757                        let inner = coll_type
1758                            .strip_prefix("&[")
1759                            .and_then(|s| s.strip_suffix(']'))
1760                            .unwrap_or("_");
1761                        let elem = inner.split(';').next().unwrap_or(inner).trim();
1762                        if is_copy_type(elem) {
1763                            (true, false)
1764                        } else {
1765                            (false, true)
1766                        }
1767                    } else if coll_type.starts_with("Vec")
1768                        && has_copy_element_type(coll_type)
1769                        && !body_mutates_collection(body, *coll_sym)
1770                    {
1771                        (true, false)
1772                    } else if coll_type.starts_with("Vec")
1773                        && !body_mutates_collection(body, *coll_sym)
1774                    {
1775                        // Non-Copy element type, but body doesn't mutate the collection:
1776                        // use .iter().cloned() for lazy per-element cloning instead of
1777                        // .clone() which copies the entire collection upfront.
1778                        (false, true)
1779                    } else {
1780                        (false, false)
1781                    }
1782                } else {
1783                    (false, false)
1784                }
1785            } else {
1786                (false, false)
1787            };
1788
1789            if use_iter_copied {
1790                writeln!(
1791                    output,
1792                    "{}for {} in {}.iter().copied() {{",
1793                    indent_str, pattern_str, iter_str
1794                )
1795                .unwrap();
1796            } else if use_iter_cloned {
1797                writeln!(
1798                    output,
1799                    "{}for {} in {}.iter().cloned() {{",
1800                    indent_str, pattern_str, iter_str
1801                )
1802                .unwrap();
1803            } else {
1804                // Clone the collection before iterating to avoid moving it.
1805                // This allows the collection to be reused after the loop.
1806                writeln!(
1807                    output,
1808                    "{}for {} in {}.clone() {{",
1809                    indent_str, pattern_str, iter_str
1810                )
1811                .unwrap();
1812            }
1813        }
1814    }
1815    if !par_emitted {
1816        ctx.push_scope();
1817        // A loop over a list of rationals binds each item as the rational it is.
1818        if let Pattern::Identifier(pvar) = pattern {
1819            if let Some(list) = super::rational::rational_type_of(iterable, super::rational::Typing { interner, variable_types: ctx.get_variable_types(), registry }) {
1820                if let crate::analysis::types::LogosType::Seq(item) = super::rational::named(&list) {
1821                    ctx.register_variable_type(*pvar, item.to_rust_type());
1822                }
1823            }
1824        }
1825        // Register a VALUE-TYPE loop variable's element type so `is_money_expr`/`is_quantity_expr`/
1826        // etc. recognize it — this is what lets `Set total to total + m` reduce over a `Seq of Money`
1827        // (else `m` is untyped and `total + m` lowers to a raw Rust `+` → E0369). Surgical: fires
1828        // ONLY for the exact-value element types, so scalar/struct loops are entirely unchanged.
1829        if let (Pattern::Identifier(pvar), Expr::Identifier(coll_sym)) = (pattern, iterable) {
1830            if let Some(ct) = ctx.get_variable_types().get(coll_sym).cloned() {
1831                let inner = ct.split("|__hl:").next().unwrap_or(ct.as_str());
1832                let elem = inner
1833                    .strip_prefix("LogosSeq<")
1834                    .and_then(|s| s.strip_suffix('>'))
1835                    .or_else(|| inner.strip_prefix("Vec<").and_then(|s| s.strip_suffix('>')))
1836                    // A `Seq of T` PARAMETER arrives as a borrowed slice `&[T]` (or `&[T; N]`),
1837                    // which the two owned forms above do not match — and a parameter is exactly
1838                    // where a loop over a table of records comes from.
1839                    .or_else(|| {
1840                        inner
1841                            .strip_prefix("&[")
1842                            .and_then(|s| s.strip_suffix(']'))
1843                            .map(|s| s.split(';').next().unwrap_or(s))
1844                    })
1845                    .or_else(|| {
1846                        inner
1847                            .strip_prefix('[')
1848                            .and_then(|s| s.strip_suffix(']'))
1849                            .map(|s| s.split(';').next().unwrap_or(s))
1850                    })
1851                    .map(str::trim);
1852                if let Some(e) = elem {
1853                    if matches!(
1854                        e,
1855                        "LogosMoney"
1856                            | "LogosQuantity"
1857                            | "LogosModular"
1858                            | "LogosUuid"
1859                            | "LogosComplex"
1860                            | "LogosDecimal"
1861                    ) {
1862                        ctx.register_variable_type(*pvar, e.to_string());
1863                    } else if registry.iter_types().any(|(sym, def)| {
1864                        matches!(def, TypeDef::Struct { .. })
1865                            && crate::codegen::types::rust_type_ident(interner.resolve(*sym)) == e
1866                    }) && !ctx.get_variable_types().contains_key(pvar)
1867                    {
1868                        // ★ A RECORD loop element must be typed too, and for the same reason the
1869                        // note above gives for `String`: without a type, a FIELD READ of the row
1870                        // (`t's text`) is emitted as a bare move, so a sibling branch that uses the
1871                        // whole row fails to build — "use of partially moved value". That is the
1872                        // ordinary "change one row, keep the others" loop, and it could not be
1873                        // compiled for the AOT tier at all. The type is also what tells the
1874                        // concatenation path that `p's left + p's right` is TEXT rather than a
1875                        // numeric `+`, which is the same blind spot in its other position.
1876                        ctx.register_variable_type(*pvar, e.to_string());
1877                    } else if e == "String" && !ctx.get_variable_types().contains_key(pvar) {
1878                        // A `String` loop element (`Repeat for part in sfParts` over a `Seq of Text`)
1879                        // must be typed so a call-arg read of it (`removePrefix(part, …)`) clones by
1880                        // value — the Set/OPT-1C call codegen moves an UNKNOWN-typed identifier, and
1881                        // a loop variable read across sibling branches would then be a use-after-move.
1882                        ctx.register_variable_type(*pvar, "String".to_string());
1883                    } else if e.starts_with("LogosTuple ")
1884                        && !ctx.get_variable_types().contains_key(pvar)
1885                    {
1886                        // A tuple element keeps its marker, so `item N of t` inside the loop gives
1887                        // each element back as itself.
1888                        ctx.register_variable_type(*pvar, e.to_string());
1889                    }
1890                }
1891            }
1892        }
1893        // Peephole: process body statements with swap, seq-copy, and rotate-left detection
1894        {
1895            let body_refs: Vec<&Stmt> = body.iter().collect();
1896            let mut bi = 0;
1897            while bi < body_refs.len() {
1898                if let Some((code, skip)) = super::peephole::try_block_peepholes(
1899                    &body_refs,
1900                    bi,
1901                    interner,
1902                    indent + 1,
1903                    mutable_vars,
1904                    ctx,
1905                    lww_fields,
1906                    mv_fields,
1907                    synced_vars,
1908                    var_caps,
1909                    async_functions,
1910                    pipe_vars,
1911                    boxed_fields,
1912                    registry,
1913                    type_env,
1914                ) {
1915                    output.push_str(&code);
1916                    bi += 1 + skip;
1917                    continue;
1918                }
1919                output.push_str(&codegen_stmt(
1920                    body_refs[bi],
1921                    interner,
1922                    indent + 1,
1923                    mutable_vars,
1924                    ctx,
1925                    lww_fields,
1926                    mv_fields,
1927                    synced_vars,
1928                    var_caps,
1929                    async_functions,
1930                    pipe_vars,
1931                    boxed_fields,
1932                    registry,
1933                    type_env,
1934                ));
1935                bi += 1;
1936            }
1937        }
1938        ctx.pop_scope();
1939        writeln!(output, "{}}}", indent_str).unwrap();
1940    }
1941    output
1942}
1943
1944/// The `Inspect` arm of [`codegen_stmt`]: an arm of [`codegen_stmt`], in a frame of its own — see [`codegen_let_stmt`].
1945#[inline(never)]
1946#[allow(clippy::too_many_arguments)]
1947fn codegen_inspect_stmt<'a>(
1948    mut output: String,
1949    target: &&'a Expr<'a>,
1950    arms: &[MatchArm<'a>],
1951    interner: &Interner,
1952    indent: usize,
1953    mutable_vars: &HashSet<Symbol>,
1954    ctx: &mut RefinementContext<'a>,
1955    lww_fields: &HashSet<(String, String)>,
1956    mv_fields: &HashSet<(String, String)>,
1957    synced_vars: &mut HashSet<Symbol>,
1958    var_caps: &HashMap<Symbol, VariableCapabilities>,
1959    async_functions: &HashSet<Symbol>,
1960    pipe_vars: &HashSet<Symbol>,
1961    boxed_fields: &HashSet<(String, String, String)>,
1962    registry: &TypeRegistry,
1963    type_env: &crate::analysis::types::TypeEnv,
1964    indent_str: &str,
1965) -> String {
1966    let target_str = codegen_expr_with_async(
1967        target,
1968        interner,
1969        synced_vars,
1970        async_functions,
1971        ctx.get_variable_types(),
1972    );
1973
1974    // ★ THE SCRUTINEE IS BOUND FIRST, so its temporaries die at the semicolon.
1975    //
1976    // An `Inspect` emits a bare `match` with no trailing semicolon, and nothing is emitted after a
1977    // function's last statement — so a TERMINAL `Inspect` becomes the function's TAIL EXPRESSION.
1978    // A `Seq` argument at a borrow-role index is emitted `&*xs.borrow()`, and in edition 2021 (the
1979    // edition every generated crate pins) a tail expression's temporaries are dropped AFTER the
1980    // block's locals. The `Ref` guard therefore outlived the local it borrowed:
1981    // `error[E0597]: does not live long enough`, in generated code, for a program the tree-walker
1982    // and the VM both run.
1983    //
1984    // Binding to a local ends the borrow at the `let`, which is where it always belonged. It costs
1985    // nothing — the match still reads the same value — and it makes the emission independent of
1986    // whether this `Inspect` happens to be last, which is the property that made the bug so hard
1987    // to see: the same statement was correct anywhere but the end.
1988    //
1989    // (Rust 2024's RFC 3606 changes the tail-expression rule and would have made this unnecessary;
1990    // the generated crates are 2021 and this must not depend on that.)
1991    // ★ ONLY A SCRUTINEE THAT PRODUCES A TEMPORARY IS HOISTED, and the first version of this fix
1992    // got that wrong in a way worth recording. Binding unconditionally — `let __inspect_target =
1993    // e;` — MOVES a place expression that `match e { … }` merely matched on, so every `Inspect e:`
1994    // followed by a later use of `e` became `error[E0382]: borrow of moved value`. It turned one
1995    // borrow bug into a move bug across the whole partial-evaluation corpus.
1996    //
1997    // A CALL is the shape that needs it: its result is a temporary, and a `Seq` argument inside it
1998    // is emitted `&*xs.borrow()`, whose guard would otherwise outlive the block's locals when the
1999    // `Inspect` is the function's tail expression. A CONSTRUCTION is a temporary too, and a struct
2000    // literal is not a scrutinee Rust accepts (`match Json::JNum { n } {`). A variable or a field read
2001    // owns no temporary and is left exactly as it was.
2002    let hoist = matches!(
2003        target,
2004        Expr::Call { .. } | Expr::CallExpr { .. } | Expr::New { .. } | Expr::NewVariant { .. }
2005    );
2006    // A lent scrutinee (`&T`, a lent parameter or binding, `codegen::lent`) is matched through the reference: its arms bind
2007    // by `ref`, so matching the place `*x` moves nothing.
2008    let lent_scrutinee = matches!(target, Expr::Identifier(t)
2009        if ctx.get_variable_types().get(t).is_some_and(|ty| super::expr::is_lent_record(ty)));
2010    if hoist {
2011        // One fixed name is safe: a NESTED `Inspect` shadows it, and the outer match has already
2012        // evaluated its own scrutinee by the time any inner one is declared.
2013        writeln!(
2014            output,
2015            "{}let __inspect_target = {};",
2016            indent_str, target_str
2017        )
2018        .unwrap();
2019        writeln!(output, "{}match __inspect_target {{", indent_str).unwrap();
2020    } else if lent_scrutinee {
2021        writeln!(output, "{}match *{} {{", indent_str, target_str).unwrap();
2022    } else {
2023        writeln!(output, "{}match {} {{", indent_str, target_str).unwrap();
2024    }
2025
2026    for arm in arms {
2027        // Phase 102: Track which bindings come from boxed fields for inner Inspects
2028        // Use NAMES (strings) not symbols, because parser may create different symbols
2029        // for the same identifier in different syntactic positions.
2030        // Must be per-arm so bindings from other arms don't leak into this arm's scope.
2031        let mut inner_boxed_binding_names: HashSet<String> = HashSet::new();
2032        // The RAW interned enum name keys the boxed-field lookup: its keys are built from the same raw name.
2033        if let (Some(variant), Some(enum_name)) =
2034            (arm.variant, enum_name_of_arm(arm, registry, interner))
2035        {
2036            for (field, binding) in arm.bindings.iter() {
2037                let key = (
2038                    enum_name.clone(),
2039                    interner.resolve(variant).to_string(),
2040                    interner.resolve(*field).to_string(),
2041                );
2042                if boxed_fields.contains(&key) {
2043                    inner_boxed_binding_names.insert(interner.resolve(*binding).to_string());
2044                }
2045            }
2046        }
2047        let (pattern, prelude) = inspect_arm_pattern(arm, registry, interner);
2048        writeln!(output, "{}    {} => {{", indent_str, pattern).unwrap();
2049        if !prelude.is_empty() {
2050            writeln!(output, "{}        {}", indent_str, prelude).unwrap();
2051        }
2052
2053        ctx.push_scope();
2054
2055        // A binding of one of the program's enum types that the arm only inspects or lends on (`codegen::lent`) is
2056        // bound as a borrow of the matched field — no copy of the subtree it names.
2057        let mut lent_bindings: HashSet<Symbol> = HashSet::new();
2058
2059        // Register pattern-bound variable types from Inspect arms so that
2060        // type inference (e.g. for mixed Int/Real coercion) works correctly.
2061        if let Some(variant_sym) = arm.variant {
2062            if let Some((_enum_name, variant_def)) = registry.find_variant(variant_sym) {
2063                for (field_sym, binding_sym) in &arm.bindings {
2064                    if let Some(field_def) =
2065                        variant_def.fields.iter().find(|f| f.name == *field_sym)
2066                    {
2067                        let rust_type = super::types::codegen_field_type(&field_def.ty, interner);
2068                        let lendable = field_is_user_enum(&field_def.ty, registry)
2069                            && !mutable_vars.contains(binding_sym)
2070                            && super::lent::only_borrowed_uses(
2071                                arm.body,
2072                                *binding_sym,
2073                                interner,
2074                                &|f, j| {
2075                                    super::expr::lends_record_at(f, j, ctx.get_variable_types())
2076                                },
2077                            );
2078                        if lendable {
2079                            lent_bindings.insert(*binding_sym);
2080                            ctx.register_variable_type(*binding_sym, format!("&{}", rust_type));
2081                        } else {
2082                            ctx.register_variable_type(*binding_sym, rust_type);
2083                        }
2084                    }
2085                }
2086            }
2087        }
2088        for sym in &lent_bindings {
2089            inner_boxed_binding_names.remove(interner.resolve(*sym));
2090        }
2091
2092        // An arm's bindings are owned copies of the matched fields, rebound `mut` when the arm
2093        // writes one — pushes to it, sets its items, lends it to a `mutable` parameter — since
2094        // each write first copies the binding on write. Matched by name, as the boxed set is.
2095        let written = |name: &str| {
2096            if mutable_vars.iter().any(|s| interner.resolve(*s) == name) {
2097                "mut "
2098            } else {
2099                ""
2100            }
2101        };
2102
2103        // Generate explicit dereferences for boxed bindings at the start of the arm
2104        // With ref bindings, boxed fields need double deref: ref -> Box -> inner
2105        for binding_name in &inner_boxed_binding_names {
2106            let ident = escape_rust_ident(binding_name);
2107            writeln!(
2108                output,
2109                "{}        let {}{} = (**{}).clone();",
2110                indent_str,
2111                written(binding_name),
2112                ident,
2113                ident
2114            )
2115            .unwrap();
2116        }
2117
2118        // Clone non-boxed ref bindings to get owned values; a lent binding stays the `ref` borrow the pattern made,
2119        // seen through its box when the field is boxed.
2120        if let Some(_) = arm.variant {
2121            for (_field, binding) in &arm.bindings {
2122                let binding_name = interner.resolve(*binding);
2123                let ident = escape_rust_ident(binding_name);
2124                if lent_bindings.contains(binding) {
2125                    if arm_binding_is_boxed(
2126                        arm,
2127                        *binding,
2128                        enum_name_of_arm(arm, registry, interner).as_deref(),
2129                        boxed_fields,
2130                        interner,
2131                    ) {
2132                        writeln!(
2133                            output,
2134                            "{}        let {} = &**{};",
2135                            indent_str, ident, ident
2136                        )
2137                        .unwrap();
2138                    }
2139                } else if !inner_boxed_binding_names.contains(binding_name) {
2140                    writeln!(
2141                        output,
2142                        "{}        let {}{} = {}.clone();",
2143                        indent_str,
2144                        written(binding_name),
2145                        ident,
2146                        ident
2147                    )
2148                    .unwrap();
2149                }
2150            }
2151        }
2152
2153        for stmt in arm.body {
2154            // Phase 102: Handle inner Inspect statements with boxed bindings
2155            // Note: Since we now dereference boxed bindings at the start of the arm,
2156            // inner matches don't need the `*` dereference operator.
2157            let inner_stmt_code = if let Stmt::Inspect {
2158                target: inner_target,
2159                ..
2160            } = stmt
2161            {
2162                // Check if the inner target is a boxed binding (already dereferenced above)
2163                // Use name comparison since symbols may differ between binding and reference
2164                if let Expr::Identifier(sym) = inner_target {
2165                    let target_name = interner.resolve(*sym);
2166                    if inner_boxed_binding_names.contains(target_name) {
2167                        // Generate match (binding was already dereferenced at arm start)
2168                        let mut inner_output = String::new();
2169                        writeln!(
2170                            inner_output,
2171                            "{}match {} {{",
2172                            "    ".repeat(indent + 2),
2173                            escape_rust_ident(target_name)
2174                        )
2175                        .unwrap();
2176
2177                        if let Stmt::Inspect {
2178                            arms: inner_arms, ..
2179                        } = stmt
2180                        {
2181                            for inner_arm in inner_arms.iter() {
2182                                let (pattern, prelude) =
2183                                    inspect_arm_pattern(inner_arm, registry, interner);
2184                                let inner_indent = "    ".repeat(indent + 2);
2185                                writeln!(inner_output, "{inner_indent}    {pattern} => {{")
2186                                    .unwrap();
2187                                if !prelude.is_empty() {
2188                                    writeln!(inner_output, "{inner_indent}        {prelude}")
2189                                        .unwrap();
2190                                }
2191
2192                                ctx.push_scope();
2193                                for inner_stmt in inner_arm.body {
2194                                    inner_output.push_str(&codegen_stmt(
2195                                        inner_stmt,
2196                                        interner,
2197                                        indent + 4,
2198                                        mutable_vars,
2199                                        ctx,
2200                                        lww_fields,
2201                                        mv_fields,
2202                                        synced_vars,
2203                                        var_caps,
2204                                        async_functions,
2205                                        pipe_vars,
2206                                        boxed_fields,
2207                                        registry,
2208                                        type_env,
2209                                    ));
2210                                }
2211                                ctx.pop_scope();
2212                                writeln!(inner_output, "{}    }}", "    ".repeat(indent + 2))
2213                                    .unwrap();
2214                            }
2215                        }
2216                        writeln!(inner_output, "{}}}", "    ".repeat(indent + 2)).unwrap();
2217                        inner_output
2218                    } else {
2219                        codegen_stmt(
2220                            stmt,
2221                            interner,
2222                            indent + 2,
2223                            mutable_vars,
2224                            ctx,
2225                            lww_fields,
2226                            mv_fields,
2227                            synced_vars,
2228                            var_caps,
2229                            async_functions,
2230                            pipe_vars,
2231                            boxed_fields,
2232                            registry,
2233                            type_env,
2234                        )
2235                    }
2236                } else {
2237                    codegen_stmt(
2238                        stmt,
2239                        interner,
2240                        indent + 2,
2241                        mutable_vars,
2242                        ctx,
2243                        lww_fields,
2244                        mv_fields,
2245                        synced_vars,
2246                        var_caps,
2247                        async_functions,
2248                        pipe_vars,
2249                        boxed_fields,
2250                        registry,
2251                        type_env,
2252                    )
2253                }
2254            } else {
2255                codegen_stmt(
2256                    stmt,
2257                    interner,
2258                    indent + 2,
2259                    mutable_vars,
2260                    ctx,
2261                    lww_fields,
2262                    mv_fields,
2263                    synced_vars,
2264                    var_caps,
2265                    async_functions,
2266                    pipe_vars,
2267                    boxed_fields,
2268                    registry,
2269                    type_env,
2270                )
2271            };
2272            output.push_str(&inner_stmt_code);
2273        }
2274        ctx.pop_scope();
2275        writeln!(output, "{}    }}", indent_str).unwrap();
2276    }
2277
2278    writeln!(output, "{}}}", indent_str).unwrap();
2279    output
2280}
2281
2282/// Whether a field's declared type is one of the program's own enums.
2283fn field_is_user_enum(ty: &FieldType, registry: &TypeRegistry) -> bool {
2284    let name = match ty {
2285        FieldType::Named(s) | FieldType::Primitive(s) => *s,
2286        FieldType::Generic { base, .. } => *base,
2287        _ => return false,
2288    };
2289    matches!(registry.get(name), Some(TypeDef::Enum { .. }))
2290}
2291
2292/// The enum an `Inspect` arm matches: the one the source names, or the one the registry says owns the variant.
2293fn enum_name_of_arm(
2294    arm: &MatchArm,
2295    registry: &TypeRegistry,
2296    interner: &Interner,
2297) -> Option<String> {
2298    arm.enum_name
2299        .map(|e| interner.resolve(e).to_string())
2300        .or_else(|| {
2301            arm.variant.and_then(|v| {
2302                registry
2303                    .find_variant(v)
2304                    .map(|(e, _)| interner.resolve(e).to_string())
2305            })
2306        })
2307}
2308
2309/// The pattern an `Inspect` arm matches with, binding each of its names by `ref` into the scrutinee, and the
2310/// statements that bind the names a variant boxed whole holds in its box ([`super::types::VariantShape`]).
2311fn inspect_arm_pattern(
2312    arm: &MatchArm,
2313    registry: &TypeRegistry,
2314    interner: &Interner,
2315) -> (String, String) {
2316    let Some(variant) = arm.variant else {
2317        return ("_".to_string(), String::new());
2318    };
2319    let variant_name = interner.resolve(variant);
2320    // ★ AN UNNAMED ARM IS RESOLVED FROM THE REGISTRY, not left bare. `Inspect` arms carry the enum only when the
2321    // source named it, and a COMPILER-WRITTEN arm (the derived JSON decoder's `When JOk (v)`) has nothing to carry —
2322    // so the pattern came out as a bare `JErr { … }`, which Rust reads as a struct that does not exist. The
2323    // tree-walker resolves a variant by name and never noticed; only a BUILD did, with an error pointing at
2324    // generated code the author never wrote. The path is the SANITIZED ident, so a cross-module enum
2325    // (`Colors::Filter`) matches as `Colors__Filter::Variant`.
2326    let enum_name = enum_name_of_arm(arm, registry, interner);
2327    let path = match enum_name.as_deref() {
2328        Some(e) => format!("{}::{}", super::types::rust_type_ident(e), variant_name),
2329        None => variant_name.to_string(),
2330    };
2331    if arm.bindings.is_empty() {
2332        return (path, String::new());
2333    }
2334    if variant_name == "Some" {
2335        // `Option::Some` maps to Rust's std `Option` — a TUPLE variant (`Some(T)`, matching the `Some(value)`
2336        // constructor emission), so it needs tuple-pattern syntax `Some(ref v)`, never the struct-variant
2337        // `Some { value: ref v }` a user enum would use (that is E0769). `None` rides the unit-variant arm above.
2338        let binding = escape_rust_ident(interner.resolve(arm.bindings[0].1));
2339        return (format!("Some(ref {binding})"), String::new());
2340    }
2341    let binds: Vec<(String, String)> = arm
2342        .bindings
2343        .iter()
2344        .map(|(f, b)| {
2345            (
2346                escape_rust_ident(interner.resolve(*f)),
2347                escape_rust_ident(interner.resolve(*b)),
2348            )
2349        })
2350        .collect();
2351    let variant_def = match arm.enum_name {
2352        Some(e) => registry.variant_in(e, variant),
2353        None => registry.find_variant(variant).map(|(_, v)| v),
2354    };
2355    let shape = match (variant_def, enum_name.as_deref()) {
2356        (Some(v), Some(e)) => super::types::VariantShape::of(v, e, interner),
2357        _ => super::types::VariantShape::InPlace,
2358    };
2359    shape.pattern(&path, &binds, true)
2360}
2361
2362/// Whether the field `binding` is bound from in `arm` is stored boxed (a recursive field).
2363fn arm_binding_is_boxed(
2364    arm: &MatchArm,
2365    binding: Symbol,
2366    enum_name: Option<&str>,
2367    boxed_fields: &HashSet<(String, String, String)>,
2368    interner: &Interner,
2369) -> bool {
2370    let (Some(enum_name), Some(variant)) = (enum_name, arm.variant) else {
2371        return false;
2372    };
2373    arm.bindings.iter().any(|(field, b)| {
2374        *b == binding
2375            && boxed_fields.contains(&(
2376                enum_name.to_string(),
2377                interner.resolve(variant).to_string(),
2378                interner.resolve(*field).to_string(),
2379            ))
2380    })
2381}
2382
2383/// The `Concurrent` arm of [`codegen_stmt`]: an arm of [`codegen_stmt`], in a frame of its own — see [`codegen_let_stmt`].
2384#[inline(never)]
2385#[allow(clippy::too_many_arguments)]
2386fn codegen_concurrent_stmt<'a>(
2387    mut output: String,
2388    tasks: &Block<'a>,
2389    interner: &Interner,
2390    indent: usize,
2391    mutable_vars: &HashSet<Symbol>,
2392    ctx: &mut RefinementContext<'a>,
2393    lww_fields: &HashSet<(String, String)>,
2394    mv_fields: &HashSet<(String, String)>,
2395    synced_vars: &mut HashSet<Symbol>,
2396    var_caps: &HashMap<Symbol, VariableCapabilities>,
2397    async_functions: &HashSet<Symbol>,
2398    pipe_vars: &HashSet<Symbol>,
2399    boxed_fields: &HashSet<(String, String, String)>,
2400    registry: &TypeRegistry,
2401    type_env: &crate::analysis::types::TypeEnv,
2402    indent_str: &str,
2403) -> String {
2404    // Collect Let statements to generate tuple destructuring
2405    let let_bindings: Vec<_> = tasks
2406        .iter()
2407        .filter_map(|s| {
2408            if let Stmt::Let { var, .. } = s {
2409                Some(interner.resolve(*var).to_string())
2410            } else {
2411                None
2412            }
2413        })
2414        .collect();
2415
2416    // Collect variables DEFINED in this block (to exclude from cloning)
2417    let defined_vars: HashSet<Symbol> = tasks
2418        .iter()
2419        .filter_map(|s| {
2420            if let Stmt::Let { var, .. } = s {
2421                Some(*var)
2422            } else {
2423                None
2424            }
2425        })
2426        .collect();
2427
2428    // Check if there are intra-block dependencies (a later task uses a var from earlier task)
2429    // If so, fall back to sequential execution
2430    let mut has_intra_dependency = false;
2431    let mut seen_defs: HashSet<Symbol> = HashSet::new();
2432    for s in *tasks {
2433        // Check if this task uses any variable defined by previous tasks in this block
2434        let mut used_in_task: HashSet<Symbol> = HashSet::new();
2435        collect_stmt_identifiers(s, &mut used_in_task);
2436        for used_var in &used_in_task {
2437            if seen_defs.contains(used_var) {
2438                has_intra_dependency = true;
2439                break;
2440            }
2441        }
2442        // Track variables defined by this task
2443        if let Stmt::Let { var, .. } = s {
2444            seen_defs.insert(*var);
2445        }
2446        if has_intra_dependency {
2447            break;
2448        }
2449    }
2450
2451    // Collect ALL variables used in task expressions (not just Call args)
2452    // Exclude variables defined within this block
2453    let mut used_syms: HashSet<Symbol> = HashSet::new();
2454    for s in *tasks {
2455        collect_stmt_identifiers(s, &mut used_syms);
2456    }
2457    // Remove variables that are defined in this block
2458    for def_var in &defined_vars {
2459        used_syms.remove(def_var);
2460    }
2461    let used_vars: HashSet<String> = used_syms
2462        .iter()
2463        .map(|sym| interner.resolve(*sym).to_string())
2464        .collect();
2465
2466    // If there are intra-block dependencies, execute sequentially
2467    if has_intra_dependency {
2468        // Generate sequential Let bindings
2469        for stmt in *tasks {
2470            output.push_str(&codegen_stmt(
2471                stmt,
2472                interner,
2473                indent,
2474                mutable_vars,
2475                ctx,
2476                lww_fields,
2477                mv_fields,
2478                synced_vars,
2479                var_caps,
2480                async_functions,
2481                pipe_vars,
2482                boxed_fields,
2483                registry,
2484                type_env,
2485            ));
2486        }
2487    } else {
2488        // Generate concurrent execution with tokio::join!
2489        if !let_bindings.is_empty() {
2490            // Generate tuple destructuring for concurrent Let bindings
2491            writeln!(
2492                output,
2493                "{}let ({}) = tokio::join!(",
2494                indent_str,
2495                let_bindings.join(", ")
2496            )
2497            .unwrap();
2498        } else {
2499            writeln!(output, "{}tokio::join!(", indent_str).unwrap();
2500        }
2501
2502        for (i, stmt) in tasks.iter().enumerate() {
2503            // For Let statements, generate only the VALUE so the async block returns it
2504            // For Call statements, generate the call with .await
2505            let inner_code = match stmt {
2506                Stmt::Let { value, .. } => {
2507                    // Return the value expression directly (not "let x = value;")
2508                    // Phase 54+: Use codegen_expr_with_async to handle all nested async calls
2509                    codegen_expr_with_async(
2510                        value,
2511                        interner,
2512                        synced_vars,
2513                        async_functions,
2514                        ctx.get_variable_types(),
2515                    )
2516                }
2517                Stmt::Call { function, args } => {
2518                    let func_name = interner.resolve(*function);
2519                    let args_str: Vec<String> = args
2520                        .iter()
2521                        .map(|a| {
2522                            codegen_expr_with_async(
2523                                a,
2524                                interner,
2525                                synced_vars,
2526                                async_functions,
2527                                ctx.get_variable_types(),
2528                            )
2529                        })
2530                        .collect();
2531                    // Only add .await for async functions
2532                    let await_suffix = if async_functions.contains(function) {
2533                        ".await"
2534                    } else {
2535                        ""
2536                    };
2537                    format!("{}({}){}", func_name, args_str.join(", "), await_suffix)
2538                }
2539                _ => {
2540                    // Fallback for other statement types
2541                    let inner = codegen_stmt(
2542                        stmt,
2543                        interner,
2544                        indent + 1,
2545                        mutable_vars,
2546                        ctx,
2547                        lww_fields,
2548                        mv_fields,
2549                        synced_vars,
2550                        var_caps,
2551                        async_functions,
2552                        pipe_vars,
2553                        boxed_fields,
2554                        registry,
2555                        type_env,
2556                    );
2557                    inner.trim().to_string()
2558                }
2559            };
2560
2561            // For tasks that use shared variables, wrap in a block that clones them
2562            if !used_vars.is_empty() && i < tasks.len() - 1 {
2563                // Clone variables for all tasks except the last one
2564                let clones: Vec<String> = used_vars
2565                    .iter()
2566                    .map(|v| format!("let {} = {}.clone();", v, v))
2567                    .collect();
2568                write!(
2569                    output,
2570                    "{}    {{ {} async move {{ {} }} }}",
2571                    indent_str,
2572                    clones.join(" "),
2573                    inner_code
2574                )
2575                .unwrap();
2576            } else {
2577                // Last task can use original variables
2578                write!(output, "{}    async {{ {} }}", indent_str, inner_code).unwrap();
2579            }
2580
2581            if i < tasks.len() - 1 {
2582                writeln!(output, ",").unwrap();
2583            } else {
2584                writeln!(output).unwrap();
2585            }
2586        }
2587
2588        writeln!(output, "{});", indent_str).unwrap();
2589    }
2590    output
2591}
2592
2593/// The `Parallel` arm of [`codegen_stmt`]: an arm of [`codegen_stmt`], in a frame of its own — see [`codegen_let_stmt`].
2594#[inline(never)]
2595#[allow(clippy::too_many_arguments)]
2596fn codegen_parallel_stmt<'a>(
2597    mut output: String,
2598    tasks: &Block<'a>,
2599    interner: &Interner,
2600    indent: usize,
2601    mutable_vars: &HashSet<Symbol>,
2602    ctx: &mut RefinementContext<'a>,
2603    lww_fields: &HashSet<(String, String)>,
2604    mv_fields: &HashSet<(String, String)>,
2605    synced_vars: &mut HashSet<Symbol>,
2606    var_caps: &HashMap<Symbol, VariableCapabilities>,
2607    async_functions: &HashSet<Symbol>,
2608    pipe_vars: &HashSet<Symbol>,
2609    boxed_fields: &HashSet<(String, String, String)>,
2610    registry: &TypeRegistry,
2611    type_env: &crate::analysis::types::TypeEnv,
2612    indent_str: &str,
2613) -> String {
2614    if tasks.len() < 2 {
2615        for stmt in tasks.iter() {
2616            output.push_str(&codegen_stmt(
2617                stmt,
2618                interner,
2619                indent,
2620                mutable_vars,
2621                ctx,
2622                lww_fields,
2623                mv_fields,
2624                synced_vars,
2625                var_caps,
2626                async_functions,
2627                pipe_vars,
2628                boxed_fields,
2629                registry,
2630                type_env,
2631            ));
2632        }
2633        return output;
2634    }
2635    let names = RustNames::new(interner);
2636    // Each task as the body of a pool closure, and the pattern its value binds: a `Let` returns its value into
2637    // its name, any other task returns nothing and binds `_`.
2638    let leaves: Vec<(String, String)> = tasks
2639        .iter()
2640        .map(|stmt| match stmt {
2641            Stmt::Let {
2642                var,
2643                value,
2644                mutable,
2645                ..
2646            } => {
2647                let code = super::types::type_silent_int_i64(value).unwrap_or_else(|| {
2648                    codegen_expr_with_async(
2649                        value,
2650                        interner,
2651                        synced_vars,
2652                        async_functions,
2653                        ctx.get_variable_types(),
2654                    )
2655                });
2656                let name = names.ident(*var);
2657                let pattern = if *mutable || mutable_vars.contains(var) {
2658                    format!("mut {name}")
2659                } else {
2660                    name.to_string()
2661                };
2662                (format!("{{ {code} }}"), pattern)
2663            }
2664            _ => {
2665                let inner = codegen_stmt(
2666                    stmt,
2667                    interner,
2668                    indent + 1,
2669                    mutable_vars,
2670                    ctx,
2671                    lww_fields,
2672                    mv_fields,
2673                    synced_vars,
2674                    var_caps,
2675                    async_functions,
2676                    pipe_vars,
2677                    boxed_fields,
2678                    registry,
2679                    type_env,
2680                );
2681                (format!("{{ {} }}", inner.trim()), "_".to_string())
2682            }
2683        })
2684        .collect();
2685    // The tasks run as one balanced tree of `rayon::join`s on the pool: every task may run beside every other,
2686    // each closure borrows what it reads, and the tree's value is a nested pair the pattern mirrors.
2687    fn tree(leaves: &[(String, String)]) -> (String, String) {
2688        if let [(code, pattern)] = leaves {
2689            return (code.clone(), pattern.clone());
2690        }
2691        let (left, right) = leaves.split_at(leaves.len() / 2);
2692        let ((lc, lp), (rc, rp)) = (tree(left), tree(right));
2693        let pattern = if lp == "_" && rp == "_" {
2694            "_".to_string()
2695        } else {
2696            format!("({lp}, {rp})")
2697        };
2698        (format!("rayon::join(|| {lc}, || {rc})"), pattern)
2699    }
2700    let (left, right) = leaves.split_at(leaves.len() / 2);
2701    let ((lc, lp), (rc, rp)) = (tree(left), tree(right));
2702    if lp == "_" && rp == "_" {
2703        writeln!(output, "{indent_str}rayon::join(").unwrap();
2704    } else {
2705        writeln!(output, "{indent_str}let ({lp}, {rp}) = rayon::join(").unwrap();
2706    }
2707    writeln!(output, "{indent_str}    || {lc},").unwrap();
2708    writeln!(output, "{indent_str}    || {rc}").unwrap();
2709    writeln!(output, "{indent_str});").unwrap();
2710    output
2711}
2712
2713/// The `Zone` arm of [`codegen_stmt`]: an arm of [`codegen_stmt`], in a frame of its own — see [`codegen_let_stmt`].
2714#[inline(never)]
2715#[allow(clippy::too_many_arguments)]
2716fn codegen_zone_stmt<'a>(
2717    mut output: String,
2718    name: &Symbol,
2719    capacity: &Option<usize>,
2720    source_file: &Option<ZoneSource>,
2721    body: &Block<'a>,
2722    interner: &Interner,
2723    indent: usize,
2724    mutable_vars: &HashSet<Symbol>,
2725    ctx: &mut RefinementContext<'a>,
2726    lww_fields: &HashSet<(String, String)>,
2727    mv_fields: &HashSet<(String, String)>,
2728    synced_vars: &mut HashSet<Symbol>,
2729    var_caps: &HashMap<Symbol, VariableCapabilities>,
2730    async_functions: &HashSet<Symbol>,
2731    pipe_vars: &HashSet<Symbol>,
2732    boxed_fields: &HashSet<(String, String, String)>,
2733    registry: &TypeRegistry,
2734    type_env: &crate::analysis::types::TypeEnv,
2735    indent_str: &str,
2736) -> String {
2737    let zone_name = interner.resolve(*name);
2738
2739    // Generate zone creation based on type
2740    if let Some(src) = source_file {
2741        // Memory-mapped file zone — literal path is quoted; a variable path
2742        // is passed by reference (`new_mapped` takes `AsRef<Path>`).
2743        use crate::ast::stmt::ZoneSource;
2744        let path_expr = match src {
2745            ZoneSource::Literal(p) => format!("\"{}\"", interner.resolve(*p)),
2746            ZoneSource::Variable(v) => format!("&{}", interner.resolve(*v)),
2747        };
2748        writeln!(
2749            output,
2750            "{}let {} = logicaffeine_system::memory::Zone::new_mapped({}).expect(\"Failed to map file\");",
2751            indent_str, zone_name, path_expr
2752        ).unwrap();
2753    } else {
2754        // Heap arena zone
2755        let cap = capacity.unwrap_or(4096); // Default 4KB
2756        writeln!(
2757            output,
2758            "{}let {} = logicaffeine_system::memory::Zone::new_heap({});",
2759            indent_str, zone_name, cap
2760        )
2761        .unwrap();
2762    }
2763
2764    // The zone is a labeled block a `Break` or a `Return` inside it leaves (`control`).
2765    let exit = super::control::break_label().expect("a zone is a boundary");
2766    writeln!(output, "{indent_str}'{exit}: {{").unwrap();
2767    ctx.push_scope();
2768
2769    // Generate body statements
2770    for stmt in *body {
2771        output.push_str(&codegen_stmt(
2772            stmt,
2773            interner,
2774            indent + 1,
2775            mutable_vars,
2776            ctx,
2777            lww_fields,
2778            mv_fields,
2779            synced_vars,
2780            var_caps,
2781            async_functions,
2782            pipe_vars,
2783            boxed_fields,
2784            registry,
2785            type_env,
2786        ));
2787    }
2788
2789    ctx.pop_scope();
2790    writeln!(output, "{}}}", indent_str).unwrap();
2791    output
2792}
2793
2794/// The `If` arm of [`codegen_stmt`]: an arm of [`codegen_stmt`], in a frame of its own — see [`codegen_let_stmt`].
2795#[inline(never)]
2796#[allow(clippy::too_many_arguments)]
2797/// Opt::WideAccumulator analysis — the vars safe to widen to `i128` (see the Opt doc). A qualifier
2798/// has EXACTLY one `Let X be 0` (outside any loop), is incremented ONLY by `Set X to X + 1` all inside
2799/// ONE counted loop with an i64 bound (⟹ X ≤ trip ≤ i64::MAX), and is read ONLY by a bare `Show X`.
2800/// ANY other appearance of X disqualifies it — conservative, so we never widen a var whose value is
2801/// needed elsewhere (which would at worst be a loud i128/i64 type error, never a silent wrong answer).
2802fn collect_count_accumulators(
2803    stmts: &[Stmt],
2804    bignum_vars: &std::collections::HashSet<Symbol>,
2805    restrict_reads: bool,
2806    allow_length_bound: bool,
2807    pure_calls: &std::collections::HashSet<Symbol>,
2808) -> std::collections::HashSet<Symbol> {
2809    use std::collections::{HashMap, HashSet};
2810    fn is_zero(e: &Expr) -> bool {
2811        matches!(e, Expr::Literal(Literal::Number(0)))
2812    }
2813    fn is_plus1(e: &Expr, x: Symbol) -> bool {
2814        matches!(e, Expr::BinaryOp { op: BinaryOpKind::Add, left, right }
2815            if matches!(left, Expr::Identifier(l) if *l == x)
2816                && matches!(right, Expr::Literal(Literal::Number(1))))
2817    }
2818    // A `while <counter> </<= <bound>` whose bound is provably i64 (a literal, a length, or a
2819    // non-bignum var), so its trip count is ≤ i64::MAX.
2820    fn counted_i64(cond: &Expr, bignum: &HashSet<Symbol>, allow_length_bound: bool) -> bool {
2821        if let Expr::BinaryOp { op, left, right } = cond {
2822            if matches!(op, BinaryOpKind::Lt | BinaryOpKind::LtEq)
2823                && matches!(left, Expr::Identifier(_))
2824            {
2825                return match right {
2826                    Expr::Literal(Literal::Number(_)) => true,
2827                    Expr::Identifier(b) => !bignum.contains(b),
2828                    Expr::Length { .. } => allow_length_bound,
2829                    _ => false,
2830                };
2831            }
2832        }
2833        false
2834    }
2835    struct S {
2836        zero_let: HashSet<Symbol>,                // has a top-level `Let X be 0`
2837        bad_let: HashSet<Symbol>,                 // >1 Let, or a Let that isn't a top-level `be 0`
2838        inc_loop: HashMap<Symbol, Option<usize>>, // X → the ONE counted-loop id it's `+1`-incremented in (None = multiple/bad)
2839        disq: HashSet<Symbol>,                    // appeared somewhere disallowed
2840        bail: bool, // an unrecognized statement kind is present → widen nothing (safe)
2841    }
2842    // Every name `e` reads, at any depth: an item's index, a call's argument and a field's owner read their names
2843    // as surely as an operand does, and a widened accumulator read there would meet an i64 it cannot add to.
2844    fn disq_reads(e: &Expr, s: &mut S, restrict_reads: bool) {
2845        if !restrict_reads {
2846            return;
2847        }
2848        let mut stack = vec![e];
2849        while let Some(x) = stack.pop() {
2850            if let Expr::Identifier(r) = x {
2851                s.disq.insert(*r);
2852            }
2853            stack.extend(logicaffeine_language::ast_depth::expr_children(x));
2854        }
2855    }
2856    // `loop_ctx = Some(id)` ⟺ we are directly inside a depth-1 counted-i64 loop (its body); None
2857    // otherwise (top level, a nested loop, or a non-counted loop) — increments there are not clean.
2858    fn walk(
2859        stmts: &[Stmt],
2860        loop_ctx: Option<usize>,
2861        loop_depth: usize,
2862        next_id: &mut usize,
2863        bignum: &HashSet<Symbol>,
2864        restrict_reads: bool,
2865        allow_length_bound: bool,
2866        s: &mut S,
2867    ) {
2868        for st in stmts {
2869            match st {
2870                Stmt::Let { var, value, .. } => {
2871                    if loop_ctx.is_none() && is_zero(value) {
2872                        if !s.zero_let.insert(*var) {
2873                            s.bad_let.insert(*var);
2874                        }
2875                    } else {
2876                        s.bad_let.insert(*var);
2877                    }
2878                    disq_reads(value, s, restrict_reads); // any var READ in a Let RHS is a non-Show read
2879                }
2880                Stmt::Set { target, value } => {
2881                    if let Some(id) = loop_ctx {
2882                        if is_plus1(value, *target) {
2883                            match s.inc_loop.get(target) {
2884                                None => {
2885                                    s.inc_loop.insert(*target, Some(id));
2886                                }
2887                                Some(Some(prev)) if *prev == id => {}
2888                                _ => {
2889                                    s.inc_loop.insert(*target, None);
2890                                }
2891                            }
2892                            continue; // the `X` read inside `X + 1` is the allowed one
2893                        }
2894                    }
2895                    s.disq.insert(*target);
2896                    disq_reads(value, s, restrict_reads);
2897                }
2898                Stmt::Show { object, .. } => {
2899                    if !matches!(object, Expr::Identifier(_)) {
2900                        disq_reads(object, s, restrict_reads); // only a BARE `Show X` is an allowed read
2901                    }
2902                }
2903                Stmt::If {
2904                    cond,
2905                    then_block,
2906                    else_block,
2907                } => {
2908                    disq_reads(cond, s, restrict_reads);
2909                    walk(
2910                        then_block,
2911                        loop_ctx,
2912                        loop_depth,
2913                        next_id,
2914                        bignum,
2915                        restrict_reads,
2916                        allow_length_bound,
2917                        s,
2918                    );
2919                    if let Some(eb) = else_block {
2920                        walk(
2921                            eb,
2922                            loop_ctx,
2923                            loop_depth,
2924                            next_id,
2925                            bignum,
2926                            restrict_reads,
2927                            allow_length_bound,
2928                            s,
2929                        );
2930                    }
2931                }
2932                Stmt::While { cond, body, .. } => {
2933                    disq_reads(cond, s, restrict_reads);
2934                    let inner = if loop_depth == 0 && counted_i64(cond, bignum, allow_length_bound)
2935                    {
2936                        let id = *next_id;
2937                        *next_id += 1;
2938                        Some(id)
2939                    } else {
2940                        None
2941                    };
2942                    walk(
2943                        body,
2944                        inner,
2945                        loop_depth + 1,
2946                        next_id,
2947                        bignum,
2948                        restrict_reads,
2949                        allow_length_bound,
2950                        s,
2951                    );
2952                }
2953                Stmt::Repeat { iterable, body, .. } => {
2954                    disq_reads(iterable, s, restrict_reads);
2955                    walk(
2956                        body,
2957                        None,
2958                        loop_depth + 1,
2959                        next_id,
2960                        bignum,
2961                        restrict_reads,
2962                        allow_length_bound,
2963                        s,
2964                    );
2965                }
2966                Stmt::Zone { body, .. } => {
2967                    walk(
2968                        body,
2969                        None,
2970                        loop_depth + 1,
2971                        next_id,
2972                        bignum,
2973                        restrict_reads,
2974                        allow_length_bound,
2975                        s,
2976                    );
2977                }
2978                Stmt::Inspect { target, arms, .. } => {
2979                    disq_reads(target, s, restrict_reads);
2980                    for arm in arms.iter() {
2981                        walk(
2982                            arm.body,
2983                            None,
2984                            loop_depth,
2985                            next_id,
2986                            bignum,
2987                            restrict_reads,
2988                            allow_length_bound,
2989                            s,
2990                        );
2991                    }
2992                }
2993                Stmt::Return { value } => {
2994                    if let Some(v) = value {
2995                        disq_reads(v, s, restrict_reads);
2996                    }
2997                }
2998                Stmt::Push { value, collection } => {
2999                    disq_reads(value, s, restrict_reads);
3000                    disq_reads(collection, s, restrict_reads);
3001                }
3002                Stmt::Call { args, .. } => {
3003                    // The effect walk admitted only proven-pure callees and arguments.
3004                    for arg in args.iter() {
3005                        disq_reads(arg, s, restrict_reads);
3006                    }
3007                }
3008                Stmt::Break => {}
3009                // A function definition at the top level is not part of THIS body's executable code
3010                // (its body is analyzed on its own); skip so a program with helper fns still widens Main.
3011                Stmt::FunctionDef { .. } => {}
3012                _ => {
3013                    // An unrecognized statement kind might read a candidate in a way we don't model —
3014                    // widen NOTHING in this body rather than risk it (safe + rare).
3015                    s.bail = true;
3016                }
3017            }
3018        }
3019    }
3020    // Expression calls can mutate a count, its induction variable, or its bound.
3021    // Without an effect summary none of those visible updates is a complete proof.
3022    let mut effectful = false;
3023    logicaffeine_language::ast_depth::walk_nodes(stmts, |node| {
3024        use logicaffeine_language::ast_depth::{Visited, Walk};
3025        match node {
3026            Visited::Stmt(Stmt::FunctionDef { .. }) | Visited::Expr(Expr::Closure { .. }) => {
3027                Walk::Past
3028            }
3029            Visited::Expr(Expr::Call { function, .. })
3030            | Visited::Stmt(Stmt::Call { function, .. })
3031                if !pure_calls.contains(function) =>
3032            {
3033                effectful = true;
3034                Walk::Past
3035            }
3036            Visited::Expr(Expr::CallExpr { .. } | Expr::Escape { .. }) => {
3037                effectful = true;
3038                Walk::Past
3039            }
3040            _ => Walk::Into,
3041        }
3042    });
3043    if effectful {
3044        return HashSet::new();
3045    }
3046    let mut s = S {
3047        zero_let: HashSet::new(),
3048        bad_let: HashSet::new(),
3049        inc_loop: HashMap::new(),
3050        disq: HashSet::new(),
3051        bail: false,
3052    };
3053    let mut next_id = 0usize;
3054    walk(
3055        stmts,
3056        None,
3057        0,
3058        &mut next_id,
3059        bignum_vars,
3060        restrict_reads,
3061        allow_length_bound,
3062        &mut s,
3063    );
3064    if s.bail {
3065        return HashSet::new();
3066    }
3067    s.zero_let
3068        .iter()
3069        .copied()
3070        .filter(|x| {
3071            !s.bad_let.contains(x)
3072                && !s.disq.contains(x)
3073                && matches!(s.inc_loop.get(x), Some(Some(_)))
3074        })
3075        .collect()
3076}
3077
3078pub(crate) fn collect_wide_accumulators(
3079    stmts: &[Stmt],
3080    bignum_vars: &std::collections::HashSet<Symbol>,
3081    pure_calls: &std::collections::HashSet<Symbol>,
3082) -> std::collections::HashSet<Symbol> {
3083    collect_count_accumulators(stmts, bignum_vars, true, false, pure_calls)
3084}
3085
3086/// Integer accumulators whose `+1` cannot overflow: they start at zero and are changed only inside
3087/// one i64-bounded counted loop, so their value is at most that loop's trip count. Unlike the
3088/// WideAccumulator set, reads need not be restricted because this proof changes no storage type.
3089pub(crate) fn collect_bounded_count_accumulators(
3090    stmts: &[Stmt],
3091    bignum_vars: &std::collections::HashSet<Symbol>,
3092) -> std::collections::HashSet<Symbol> {
3093    collect_bounded_count_accumulators_with_purity(stmts, bignum_vars, &Default::default())
3094}
3095
3096/// The same count proof, with calls admitted by the whole program's shared purity analysis.
3097pub(crate) fn collect_bounded_count_accumulators_with_purity(
3098    stmts: &[Stmt],
3099    bignum_vars: &std::collections::HashSet<Symbol>,
3100    pure_calls: &std::collections::HashSet<Symbol>,
3101) -> std::collections::HashSet<Symbol> {
3102    use std::collections::{HashMap, HashSet};
3103
3104    fn is_plus1(e: &Expr, x: Symbol) -> bool {
3105        matches!(e, Expr::BinaryOp { op: BinaryOpKind::Add, left, right }
3106            if matches!(left, Expr::Identifier(l) if *l == x)
3107                && matches!(right, Expr::Literal(Literal::Number(1))))
3108    }
3109
3110    fn counter_advances_once(body: &[Stmt], counter: Symbol) -> bool {
3111        fn walk(block: &[Stmt], counter: Symbol, direct: bool, count: &mut usize, bad: &mut bool) {
3112            for stmt in block {
3113                match stmt {
3114                    Stmt::Set { target, value } if *target == counter => {
3115                        if direct && is_plus1(value, counter) {
3116                            *count += 1;
3117                        } else {
3118                            *bad = true;
3119                        }
3120                    }
3121                    Stmt::Let { var, .. } if *var == counter => *bad = true,
3122                    Stmt::If {
3123                        then_block,
3124                        else_block,
3125                        ..
3126                    } => {
3127                        walk(then_block, counter, false, count, bad);
3128                        if let Some(eb) = else_block {
3129                            walk(eb, counter, false, count, bad);
3130                        }
3131                    }
3132                    Stmt::While { body, .. }
3133                    | Stmt::Repeat { body, .. }
3134                    | Stmt::Zone { body, .. } => walk(body, counter, false, count, bad),
3135                    Stmt::Inspect { arms, .. } => {
3136                        for arm in arms.iter() {
3137                            walk(arm.body, counter, false, count, bad);
3138                        }
3139                    }
3140                    Stmt::FunctionDef { .. } => {}
3141                    _ => {}
3142                }
3143            }
3144        }
3145        let (mut count, mut bad) = (0, false);
3146        walk(body, counter, true, &mut count, &mut bad);
3147        !bad && count == 1
3148    }
3149
3150    fn certified_loop(
3151        cond: &Expr,
3152        body: &[Stmt],
3153        bignum: &HashSet<Symbol>,
3154        nonnegative: &HashSet<Symbol>,
3155        positive: &HashSet<Symbol>,
3156    ) -> bool {
3157        let Expr::BinaryOp { op, left, right } = cond else {
3158            return false;
3159        };
3160        let Expr::Identifier(counter) = left else {
3161            return false;
3162        };
3163        if !nonnegative.contains(counter) || !counter_advances_once(body, *counter) {
3164            return false;
3165        }
3166        match (op, right) {
3167            (BinaryOpKind::Lt, Expr::Literal(Literal::Number(_))) => true,
3168            (BinaryOpKind::Lt, Expr::Identifier(bound)) => !bignum.contains(bound),
3169            (BinaryOpKind::Lt, Expr::Length { .. }) => true,
3170            (BinaryOpKind::LtEq, Expr::Literal(Literal::Number(bound))) => {
3171                *bound < i64::MAX || positive.contains(counter)
3172            }
3173            (BinaryOpKind::LtEq, Expr::Identifier(bound)) => {
3174                positive.contains(counter) && !bignum.contains(bound)
3175            }
3176            (BinaryOpKind::LtEq, Expr::Length { .. }) => true,
3177            _ => false,
3178        }
3179    }
3180
3181    fn plus1_sites(block: &[Stmt], out: &mut HashMap<Symbol, usize>) {
3182        for stmt in block {
3183            match stmt {
3184                Stmt::Set { target, value } if is_plus1(value, *target) => {
3185                    *out.entry(*target).or_insert(0) += 1;
3186                }
3187                Stmt::If {
3188                    then_block,
3189                    else_block,
3190                    ..
3191                } => {
3192                    plus1_sites(then_block, out);
3193                    if let Some(eb) = else_block {
3194                        plus1_sites(eb, out);
3195                    }
3196                }
3197                Stmt::Zone { body, .. } => plus1_sites(body, out),
3198                Stmt::Inspect { arms, .. } => {
3199                    for arm in arms.iter() {
3200                        plus1_sites(arm.body, out);
3201                    }
3202                }
3203                // A nested loop's sites do not run at most once per outer iteration.
3204                Stmt::While { .. } | Stmt::Repeat { .. } | Stmt::FunctionDef { .. } => {}
3205                _ => {}
3206            }
3207        }
3208    }
3209
3210    fn visit_loops(
3211        block: &[Stmt],
3212        bignum: &HashSet<Symbol>,
3213        nonnegative: &HashSet<Symbol>,
3214        positive: &HashSet<Symbol>,
3215        certified: &mut HashSet<Symbol>,
3216    ) {
3217        let mut positive = positive.clone();
3218        for stmt in block {
3219            match stmt {
3220                Stmt::While { cond, body, .. } => {
3221                    if certified_loop(cond, body, bignum, nonnegative, &positive) {
3222                        let mut sites = HashMap::new();
3223                        plus1_sites(body, &mut sites);
3224                        certified.extend(
3225                            sites
3226                                .into_iter()
3227                                .filter_map(|(target, n)| (n == 1).then_some(target)),
3228                        );
3229                    }
3230                    visit_loops(body, bignum, nonnegative, &positive, certified);
3231                }
3232                Stmt::If {
3233                    then_block,
3234                    else_block,
3235                    ..
3236                } => {
3237                    visit_loops(then_block, bignum, nonnegative, &positive, certified);
3238                    if let Some(eb) = else_block {
3239                        visit_loops(eb, bignum, nonnegative, &positive, certified);
3240                    }
3241                }
3242                Stmt::Repeat { body, .. } | Stmt::Zone { body, .. } => {
3243                    visit_loops(body, bignum, nonnegative, &positive, certified)
3244                }
3245                Stmt::Inspect { arms, .. } => {
3246                    for arm in arms.iter() {
3247                        visit_loops(arm.body, bignum, nonnegative, &positive, certified);
3248                    }
3249                }
3250                Stmt::FunctionDef { .. } => {}
3251                _ => {}
3252            }
3253            // Only a dominating positive literal, preserved by +1, proves a
3254            // strictly positive start. Writes in branches or loops invalidate it.
3255            match stmt {
3256                Stmt::Let { var, value, .. } | Stmt::Set { target: var, value } if matches!(value, Expr::Literal(Literal::Number(n)) if *n > 0) =>
3257                {
3258                    positive.insert(*var);
3259                }
3260                Stmt::Set { target, value } if is_plus1(value, *target) => {}
3261                _ => {
3262                    logicaffeine_language::ast_depth::walk_nodes(
3263                        std::slice::from_ref(stmt),
3264                        |node| {
3265                            use logicaffeine_language::ast_depth::{Visited, Walk};
3266                            match node {
3267                                Visited::Stmt(Stmt::FunctionDef { .. })
3268                                | Visited::Expr(Expr::Closure { .. }) => Walk::Past,
3269                                Visited::Stmt(
3270                                    Stmt::Let { var, .. } | Stmt::Set { target: var, .. },
3271                                ) => {
3272                                    positive.remove(var);
3273                                    Walk::Into
3274                                }
3275                                _ => Walk::Into,
3276                            }
3277                        },
3278                    );
3279                }
3280            }
3281        }
3282    }
3283
3284    let candidates = collect_count_accumulators(stmts, bignum_vars, false, true, pure_calls);
3285    let nonnegative = super::expr::collect_always_nonneg(stmts);
3286    let mut certified = HashSet::new();
3287    visit_loops(
3288        stmts,
3289        bignum_vars,
3290        &nonnegative,
3291        &HashSet::new(),
3292        &mut certified,
3293    );
3294    candidates.intersection(&certified).copied().collect()
3295}
3296
3297fn codegen_if_stmt<'a>(
3298    mut output: String,
3299    cond: &&'a Expr<'a>,
3300    then_block: &Block<'a>,
3301    else_block: &Option<Block<'a>>,
3302    interner: &Interner,
3303    indent: usize,
3304    mutable_vars: &HashSet<Symbol>,
3305    ctx: &mut RefinementContext<'a>,
3306    lww_fields: &HashSet<(String, String)>,
3307    mv_fields: &HashSet<(String, String)>,
3308    synced_vars: &mut HashSet<Symbol>,
3309    var_caps: &HashMap<Symbol, VariableCapabilities>,
3310    async_functions: &HashSet<Symbol>,
3311    pipe_vars: &HashSet<Symbol>,
3312    boxed_fields: &HashSet<(String, String, String)>,
3313    registry: &TypeRegistry,
3314    type_env: &crate::analysis::types::TypeEnv,
3315    indent_str: &str,
3316) -> String {
3317    // Opt::ProbeFuse: `If m contains k:` over a branch that reads `item k of m` asks the map once.
3318    if let Some(fusion) = probe_fusion(
3319        cond,
3320        then_block,
3321        interner,
3322        synced_vars,
3323        async_functions,
3324        ctx,
3325    ) {
3326        let fused_head = format!(
3327            "{}if let Some::<{}>({}) = {}.get(&({})) {{",
3328            indent_str, fusion.value_ty, fusion.probe.name, fusion.map, fusion.key
3329        );
3330        let (out, served) = codegen_if_arms(
3331            output,
3332            fused_head.clone(),
3333            then_block,
3334            Some(fusion.probe),
3335            else_block,
3336            interner,
3337            indent,
3338            mutable_vars,
3339            ctx,
3340            lww_fields,
3341            mv_fields,
3342            synced_vars,
3343            var_caps,
3344            async_functions,
3345            pipe_vars,
3346            boxed_fields,
3347            registry,
3348            type_env,
3349            indent_str,
3350        );
3351        if served == 0 {
3352            let plain_head = format!(
3353                "{}if {}.logos_contains(&({})) {{",
3354                indent_str, fusion.map, fusion.key
3355            );
3356            return out.replacen(&fused_head, &plain_head, 1);
3357        }
3358        crate::optimize::mark_fired(crate::optimization::Opt::ProbeFuse);
3359        return out;
3360    }
3361    // Opt::BranchlessAccumulate: `if <cond> { X = X + <literal k> }` (no else, X a plain integer
3362    // accumulator) -> `X = logos_add_i64(X, (<cond>) as i64 * k)`. Removes the data-dependent branch
3363    // that blocks loop vectorization. Byte-identical: `cond ∈ {0,1}`, evaluated exactly once either way.
3364    if else_block.is_none()
3365        && then_block.len() == 1
3366        && crate::optimize::active_config().is_on(crate::optimization::Opt::BranchlessAccumulate)
3367    {
3368        if let Some(Stmt::Set { target, value }) = then_block.first() {
3369            if let Expr::BinaryOp {
3370                op: BinaryOpKind::Add,
3371                left,
3372                right,
3373            } = value
3374            {
3375                let self_add = matches!(left, Expr::Identifier(l) if *l == *target);
3376                if let (true, Expr::Literal(Literal::Number(k))) = (self_add, right) {
3377                    // X must be a plain integer accumulator (i64 add helper), not bignum/float/text —
3378                    // conservative: bail on any non-plain type so the add semantics match the normal path.
3379                    let plain_i64 = match ctx.get_variable_types().get(target) {
3380                        None => true,
3381                        Some(t) => {
3382                            !(t.contains("bigint")
3383                                || t.contains("LogosInt")
3384                                || t == "f64"
3385                                || t == "String"
3386                                || t == "Text"
3387                                || t.contains("__"))
3388                        }
3389                    };
3390                    if plain_i64 {
3391                        crate::optimize::mark_fired(crate::optimization::Opt::BranchlessAccumulate);
3392                        let cs = codegen_expr_with_async_oracle(
3393                            cond,
3394                            interner,
3395                            synced_vars,
3396                            async_functions,
3397                            ctx.get_variable_types(),
3398                            ctx.oracle(),
3399                        );
3400                        let cs = truthy_cond_wrap(cond, cs, interner, ctx.get_variable_types());
3401                        let xn = RustNames::new(interner).ident(*target);
3402                        // Opt::WideAccumulator: an i128 accumulator uses a PLAIN add (no checked branch,
3403                        // so the count vectorizes); a plain i64 accumulator keeps the checked helper.
3404                        if super::expr::is_wide_acc(*target)
3405                            && crate::optimize::active_config()
3406                                .is_on(crate::optimization::Opt::WideAccumulator)
3407                        {
3408                            crate::optimize::mark_fired(crate::optimization::Opt::WideAccumulator);
3409                            let delta = if *k == 1 {
3410                                format!("(({}) as i128)", cs)
3411                            } else {
3412                                format!("(({}) as i128 * {})", cs, k)
3413                            };
3414                            writeln!(output, "{}{} = {} + {};", indent_str, xn, xn, delta).unwrap();
3415                        } else {
3416                            let delta = if *k == 1 {
3417                                format!("(({}) as i64)", cs)
3418                            } else {
3419                                format!("(({}) as i64 * {})", cs, k)
3420                            };
3421                            writeln!(
3422                                output,
3423                                "{}{} = logos_add_i64({}, {});",
3424                                indent_str, xn, xn, delta
3425                            )
3426                            .unwrap();
3427                        }
3428                        return output;
3429                    }
3430                }
3431            }
3432        }
3433    }
3434    // Opt::BranchlessSelect: both arms ahead of the choice and `cond` selecting, while every arm's guard holds;
3435    // the branch itself, one level in, when one does not.
3436    if let Some(select) = branchless_select(
3437        then_block,
3438        else_block,
3439        interner,
3440        synced_vars,
3441        async_functions,
3442        ctx,
3443    ) {
3444        crate::optimize::mark_fired(crate::optimization::Opt::BranchlessSelect);
3445        let cond_str = codegen_expr_with_async_oracle(
3446            cond,
3447            interner,
3448            synced_vars,
3449            async_functions,
3450            ctx.get_variable_types(),
3451            ctx.oracle(),
3452        );
3453        let cond_str = truthy_cond_wrap(cond, cond_str, interner, ctx.get_variable_types());
3454        let target = RustNames::new(interner).ident(select.target);
3455        writeln!(output, "{}if {} {{", indent_str, select.guard).unwrap();
3456        writeln!(
3457            output,
3458            "{}    let __select_then: i64 = {};",
3459            indent_str, select.then_word
3460        )
3461        .unwrap();
3462        writeln!(
3463            output,
3464            "{}    let __select_else: i64 = {};",
3465            indent_str, select.else_word
3466        )
3467        .unwrap();
3468        writeln!(
3469            output,
3470            "{}    {} = if {} {{ __select_then }} else {{ __select_else }};",
3471            indent_str, target, cond_str
3472        )
3473        .unwrap();
3474        writeln!(output, "{}}} else {{", indent_str).unwrap();
3475        let output = codegen_if_branches(
3476            output,
3477            cond,
3478            then_block,
3479            else_block,
3480            interner,
3481            indent + 1,
3482            mutable_vars,
3483            ctx,
3484            lww_fields,
3485            mv_fields,
3486            synced_vars,
3487            var_caps,
3488            async_functions,
3489            pipe_vars,
3490            boxed_fields,
3491            registry,
3492            type_env,
3493            &"    ".repeat(indent + 1),
3494        );
3495        return output + &format!("{}}}\n", indent_str);
3496    }
3497    codegen_if_branches(
3498        output,
3499        cond,
3500        then_block,
3501        else_block,
3502        interner,
3503        indent,
3504        mutable_vars,
3505        ctx,
3506        lww_fields,
3507        mv_fields,
3508        synced_vars,
3509        var_caps,
3510        async_functions,
3511        pipe_vars,
3512        boxed_fields,
3513        registry,
3514        type_env,
3515        indent_str,
3516    )
3517}
3518
3519/// `If m contains k:` as one lookup ([`probe_fusion`]): the map and key as Rust, the map's value type, and the probe
3520/// that answers the branch's reads of `item k of m`.
3521struct ProbeFusion {
3522    map: String,
3523    key: String,
3524    value_ty: String,
3525    probe: super::probe::Probe,
3526}
3527
3528/// `If m contains k:` as `if let Some(p) = m.get(&k)`, its branch reading `item k of m` as `p`
3529/// ([`super::probe`]): `m` a map whose `get` answers an `Int`, `Real` or `Bool` by value, `k` a name or a literal of
3530/// the map's key type, and a branch that calls nothing and writes neither `m` nor `k`, so every read of `item k of m`
3531/// in it reads what the test found.
3532fn probe_fusion<'a>(
3533    cond: &Expr<'a>,
3534    then_block: &Block<'a>,
3535    interner: &Interner,
3536    synced_vars: &HashSet<Symbol>,
3537    async_functions: &HashSet<Symbol>,
3538    ctx: &RefinementContext<'a>,
3539) -> Option<ProbeFusion> {
3540    if !crate::optimize::active_config().is_on(crate::optimization::Opt::ProbeFuse) {
3541        return None;
3542    }
3543    let Expr::Contains {
3544        collection: map_expr @ Expr::Identifier(map),
3545        value: key,
3546    } = cond
3547    else {
3548        return None;
3549    };
3550    let probe_key = super::probe::ProbeKey::of(key)?;
3551    let writes = crate::optimize::writes::WriteSet::of_block(then_block);
3552    if writes.is_opaque()
3553        || writes.has_calls()
3554        || writes.may_write(*map)
3555        || matches!(probe_key, super::probe::ProbeKey::Name(k) if writes.may_write(k))
3556    {
3557        return None;
3558    }
3559    let types = ctx.get_variable_types();
3560    let map_ty = types
3561        .get(map)?
3562        .split("|__hl:")
3563        .next()?
3564        .trim_start_matches("&mut ")
3565        .trim_start_matches('&')
3566        .to_string();
3567    let (key_ty, value_ty) = if map_ty.starts_with("LogosI64Map")
3568        || map_ty.starts_with("LogosI32Map")
3569        || map_ty.starts_with("LogosDenseI64Map")
3570    {
3571        ("i64".to_string(), "i64".to_string())
3572    } else {
3573        let args = map_ty.strip_prefix("LogosMap<")?.strip_suffix('>')?;
3574        let mut depth = 0i32;
3575        let comma = args.char_indices().find(|&(_, c)| {
3576            match c {
3577                '<' | '(' | '[' => depth += 1,
3578                '>' | ')' | ']' => depth -= 1,
3579                _ => {}
3580            }
3581            c == ',' && depth == 0
3582        })?;
3583        (
3584            args[..comma.0].trim().to_string(),
3585            args[comma.0 + 1..].trim().to_string(),
3586        )
3587    };
3588    if !matches!(value_ty.as_str(), "i64" | "f64" | "bool") {
3589        return None;
3590    }
3591    let key_fits = match probe_key {
3592        super::probe::ProbeKey::Int(_) => key_ty == "i64",
3593        super::probe::ProbeKey::Text(_) => key_ty == "String",
3594        super::probe::ProbeKey::Name(_) if key_ty == "i64" => {
3595            super::types::infer_numeric_type(key, interner, types) == "i64"
3596        }
3597        super::probe::ProbeKey::Name(k) => types.get(&k).is_some_and(|t| *t == key_ty),
3598    };
3599    if !key_fits {
3600        return None;
3601    }
3602    let emit = |e: &Expr<'a>| {
3603        codegen_expr_with_async_oracle(
3604            e,
3605            interner,
3606            synced_vars,
3607            async_functions,
3608            types,
3609            ctx.oracle(),
3610        )
3611    };
3612    Some(ProbeFusion {
3613        map: emit(map_expr),
3614        key: emit(key),
3615        value_ty,
3616        probe: super::probe::Probe {
3617            map: *map,
3618            key: probe_key,
3619            name: super::probe::fresh_name(),
3620            reads: 0,
3621        },
3622    })
3623}
3624
3625/// A two-armed assignment `Opt::BranchlessSelect` computes as a select: the guard under which both arms' machine
3626/// words are exact, the two words, and the name both arms assign.
3627struct BranchlessSelect {
3628    guard: String,
3629    then_word: String,
3630    else_word: String,
3631    target: Symbol,
3632}
3633
3634/// `If c: Set x to a. Otherwise: Set x to b.` as a [`BranchlessSelect`], for an `x` held in a machine word and arms
3635/// that may be computed ahead of the choice ([`super::expr::select_arm`]). `None` as well when neither arm has a
3636/// guard: a branch between two raw arms is one the compiler already turns into a select.
3637fn branchless_select<'a>(
3638    then_block: &Block<'a>,
3639    else_block: &Option<Block<'a>>,
3640    interner: &Interner,
3641    synced_vars: &HashSet<Symbol>,
3642    async_functions: &HashSet<Symbol>,
3643    ctx: &RefinementContext<'a>,
3644) -> Option<BranchlessSelect> {
3645    if !crate::optimize::active_config().is_on(crate::optimization::Opt::BranchlessSelect) {
3646        return None;
3647    }
3648    let (
3649        [Stmt::Set {
3650            target,
3651            value: then_value,
3652        }],
3653        Some(
3654            [Stmt::Set {
3655                target: else_target,
3656                value: else_value,
3657            }],
3658        ),
3659    ) = (&then_block[..], else_block.as_deref())
3660    else {
3661        return None;
3662    };
3663    if target != else_target {
3664        return None;
3665    }
3666    let word = ctx
3667        .get_variable_types()
3668        .get(target)
3669        .map(|t| t.split("|__hl:").next().unwrap_or(t.as_str()));
3670    if word != Some("i64") {
3671        return None;
3672    }
3673    let arm = |value| {
3674        super::expr::select_arm(
3675            value,
3676            interner,
3677            synced_vars,
3678            async_functions,
3679            ctx.get_variable_types(),
3680            ctx.oracle(),
3681        )
3682    };
3683    let (then_arm, else_arm) = (arm(then_value)?, arm(else_value)?);
3684    let guard = match (then_arm.guard, else_arm.guard) {
3685        (None, None) => return None,
3686        (Some(g), None) | (None, Some(g)) => g,
3687        (Some(a), Some(b)) if a == b => a,
3688        (Some(a), Some(b)) => format!("({a}) && ({b})"),
3689    };
3690    Some(BranchlessSelect {
3691        guard,
3692        then_word: then_arm.fast,
3693        else_word: else_arm.fast,
3694        target: *target,
3695    })
3696}
3697
3698/// The `If` statement as its branch: the condition, the then-block, and the else-block when there is one.
3699#[allow(clippy::too_many_arguments)]
3700fn codegen_if_branches<'a>(
3701    output: String,
3702    cond: &&'a Expr<'a>,
3703    then_block: &Block<'a>,
3704    else_block: &Option<Block<'a>>,
3705    interner: &Interner,
3706    indent: usize,
3707    mutable_vars: &HashSet<Symbol>,
3708    ctx: &mut RefinementContext<'a>,
3709    lww_fields: &HashSet<(String, String)>,
3710    mv_fields: &HashSet<(String, String)>,
3711    synced_vars: &mut HashSet<Symbol>,
3712    var_caps: &HashMap<Symbol, VariableCapabilities>,
3713    async_functions: &HashSet<Symbol>,
3714    pipe_vars: &HashSet<Symbol>,
3715    boxed_fields: &HashSet<(String, String, String)>,
3716    registry: &TypeRegistry,
3717    type_env: &crate::analysis::types::TypeEnv,
3718    indent_str: &str,
3719) -> String {
3720    let cond_str = codegen_expr_with_async_oracle(
3721        cond,
3722        interner,
3723        synced_vars,
3724        async_functions,
3725        ctx.get_variable_types(),
3726        ctx.oracle(),
3727    );
3728    let cond_str = truthy_cond_wrap(cond, cond_str, interner, ctx.get_variable_types());
3729    let head = format!("{}if {} {{", indent_str, cond_str);
3730    let (output, _) = codegen_if_arms(
3731        output,
3732        head,
3733        then_block,
3734        None,
3735        else_block,
3736        interner,
3737        indent,
3738        mutable_vars,
3739        ctx,
3740        lww_fields,
3741        mv_fields,
3742        synced_vars,
3743        var_caps,
3744        async_functions,
3745        pipe_vars,
3746        boxed_fields,
3747        registry,
3748        type_env,
3749        indent_str,
3750    );
3751    output
3752}
3753
3754/// The `If` statement's two arms under `head`, its opening line: `then_stmts` and the else-block when there is one.
3755/// `probe` answers the then-arm's reads of its map for its key ([`super::probe`]); the count is the reads it served.
3756#[allow(clippy::too_many_arguments)]
3757fn codegen_if_arms<'a>(
3758    mut output: String,
3759    head: String,
3760    then_stmts: &[Stmt<'a>],
3761    probe: Option<super::probe::Probe>,
3762    else_block: &Option<Block<'a>>,
3763    interner: &Interner,
3764    indent: usize,
3765    mutable_vars: &HashSet<Symbol>,
3766    ctx: &mut RefinementContext<'a>,
3767    lww_fields: &HashSet<(String, String)>,
3768    mv_fields: &HashSet<(String, String)>,
3769    synced_vars: &mut HashSet<Symbol>,
3770    var_caps: &HashMap<Symbol, VariableCapabilities>,
3771    async_functions: &HashSet<Symbol>,
3772    pipe_vars: &HashSet<Symbol>,
3773    boxed_fields: &HashSet<(String, String, String)>,
3774    registry: &TypeRegistry,
3775    type_env: &crate::analysis::types::TypeEnv,
3776    indent_str: &str,
3777) -> (String, usize) {
3778    writeln!(output, "{}", head).unwrap();
3779    ctx.push_scope();
3780    let mut then_code = String::new();
3781    let mut emit_then = || {
3782        let block_refs: Vec<&Stmt> = then_stmts.iter().collect();
3783        let mut bi = 0;
3784        while bi < block_refs.len() {
3785            if let Some((code, skip)) = super::peephole::try_block_peepholes(
3786                &block_refs,
3787                bi,
3788                interner,
3789                indent + 1,
3790                mutable_vars,
3791                ctx,
3792                lww_fields,
3793                mv_fields,
3794                synced_vars,
3795                var_caps,
3796                async_functions,
3797                pipe_vars,
3798                boxed_fields,
3799                registry,
3800                type_env,
3801            ) {
3802                then_code.push_str(&code);
3803                bi += 1 + skip;
3804                continue;
3805            }
3806            then_code.push_str(&codegen_stmt(
3807                block_refs[bi],
3808                interner,
3809                indent + 1,
3810                mutable_vars,
3811                ctx,
3812                lww_fields,
3813                mv_fields,
3814                synced_vars,
3815                var_caps,
3816                async_functions,
3817                pipe_vars,
3818                boxed_fields,
3819                registry,
3820                type_env,
3821            ));
3822            bi += 1;
3823        }
3824    };
3825    let served = match probe {
3826        Some(probe) => super::probe::within(probe, emit_then).1,
3827        None => {
3828            emit_then();
3829            0
3830        }
3831    };
3832    output.push_str(&then_code);
3833    ctx.pop_scope();
3834    if let Some(else_stmts) = else_block {
3835        writeln!(output, "{}}} else {{", indent_str).unwrap();
3836        ctx.push_scope();
3837        {
3838            let block_refs: Vec<&Stmt> = else_stmts.iter().collect();
3839            let mut bi = 0;
3840            while bi < block_refs.len() {
3841                if let Some((code, skip)) = super::peephole::try_block_peepholes(
3842                    &block_refs,
3843                    bi,
3844                    interner,
3845                    indent + 1,
3846                    mutable_vars,
3847                    ctx,
3848                    lww_fields,
3849                    mv_fields,
3850                    synced_vars,
3851                    var_caps,
3852                    async_functions,
3853                    pipe_vars,
3854                    boxed_fields,
3855                    registry,
3856                    type_env,
3857                ) {
3858                    output.push_str(&code);
3859                    bi += 1 + skip;
3860                    continue;
3861                }
3862                output.push_str(&codegen_stmt(
3863                    block_refs[bi],
3864                    interner,
3865                    indent + 1,
3866                    mutable_vars,
3867                    ctx,
3868                    lww_fields,
3869                    mv_fields,
3870                    synced_vars,
3871                    var_caps,
3872                    async_functions,
3873                    pipe_vars,
3874                    boxed_fields,
3875                    registry,
3876                    type_env,
3877                ));
3878                bi += 1;
3879            }
3880        }
3881        ctx.pop_scope();
3882    }
3883    writeln!(output, "{}}}", indent_str).unwrap();
3884    (output, served)
3885}
3886
3887/// The `Show` arm of [`codegen_stmt`]: an arm of [`codegen_stmt`], in a frame of its own — see [`codegen_let_stmt`].
3888#[inline(never)]
3889#[allow(clippy::too_many_arguments)]
3890fn codegen_show_stmt<'a>(
3891    mut output: String,
3892    object: &&'a Expr<'a>,
3893    recipient: &&'a Expr<'a>,
3894    interner: &Interner,
3895    ctx: &mut RefinementContext<'a>,
3896    synced_vars: &mut HashSet<Symbol>,
3897    async_functions: &HashSet<Symbol>,
3898    registry: &TypeRegistry,
3899    indent_str: &str,
3900    names: &RustNames,
3901) -> String {
3902    // OPT: Show single-char u8 variable → println!("{}", ch as char)
3903    if let Expr::Identifier(sym) = object {
3904        if ctx
3905            .get_variable_types()
3906            .get(sym)
3907            .map_or(false, |t| t == "__single_char_u8")
3908        {
3909            let var_name = names.ident(*sym);
3910            writeln!(
3911                output,
3912                "{}logicaffeine_system::io::println({} as char);",
3913                indent_str, var_name
3914            )
3915            .unwrap();
3916            return output;
3917        }
3918    }
3919    // Opt::WideAccumulator: `Show X` where X is an i128-widened accumulator — narrow `as i64` at the
3920    // sink (X ≤ trip ≤ i64::MAX, so exact) and print via the same recipient helper.
3921    if let Expr::Identifier(sym) = object {
3922        if crate::optimize::active_config().is_on(crate::optimization::Opt::WideAccumulator)
3923            && super::expr::is_wide_acc(*sym)
3924        {
3925            let recv = if let Expr::Identifier(r) = recipient {
3926                super::expr::called_function_path(*r, names.ident(*r), ctx.get_variable_types())
3927            } else {
3928                "show".to_string()
3929            };
3930            let var_name = names.ident(*sym);
3931            let narrowed = format!("(({}) as i64)", var_name);
3932            writeln!(
3933                output,
3934                "{}{}({});",
3935                indent_str,
3936                recv,
3937                super::expr::lend_to(recipient, &narrowed)
3938            )
3939            .unwrap();
3940            return output;
3941        }
3942    }
3943    // Optimization: Show with InterpolatedString → println! directly
3944    if let Expr::InterpolatedString(parts) = object {
3945        let recv_name = if let Expr::Identifier(sym) = recipient {
3946            interner.resolve(*sym).to_string()
3947        } else {
3948            String::new()
3949        };
3950        if recv_name == "show" {
3951            // Emit println! directly — no intermediate String allocation
3952            let mut fmt_str = String::new();
3953            let mut args = Vec::new();
3954            for part in parts {
3955                match part {
3956                    crate::ast::stmt::StringPart::Literal(sym) => {
3957                        let text = interner.resolve(*sym);
3958                        for ch in text.chars() {
3959                            match ch {
3960                                '{' => fmt_str.push_str("{{"),
3961                                '}' => fmt_str.push_str("}}"),
3962                                '\n' => fmt_str.push_str("\\n"),
3963                                '\t' => fmt_str.push_str("\\t"),
3964                                '\r' => fmt_str.push_str("\\r"),
3965                                // `"`/`\` sit inside the `println!("…")` literal — escape them or an
3966                                // embedded quote (`"key \"{k}\""`) closes the string early.
3967                                '"' => fmt_str.push_str("\\\""),
3968                                '\\' => fmt_str.push_str("\\\\"),
3969                                _ => fmt_str.push(ch),
3970                            }
3971                        }
3972                    }
3973                    crate::ast::stmt::StringPart::Expr {
3974                        value,
3975                        format_spec,
3976                        debug,
3977                    } => {
3978                        if *debug {
3979                            let debug_prefix = expr_debug_prefix(value, interner);
3980                            for ch in debug_prefix.chars() {
3981                                match ch {
3982                                    '{' => fmt_str.push_str("{{"),
3983                                    '}' => fmt_str.push_str("}}"),
3984                                    '"' => fmt_str.push_str("\\\""),
3985                                    '\\' => fmt_str.push_str("\\\\"),
3986                                    _ => fmt_str.push(ch),
3987                                }
3988                            }
3989                            fmt_str.push('=');
3990                        }
3991                        let arg_str = codegen_expr_with_async_and_strings(
3992                            value,
3993                            interner,
3994                            synced_vars,
3995                            async_functions,
3996                            ctx.get_string_vars(),
3997                            ctx.get_variable_types(),
3998                            ctx.get_fast_div(),
3999                            registry,
4000                        );
4001                        let (piece, arg) = super::expr::interpolation_hole(
4002                            format_spec.map(|s| interner.resolve(s)),
4003                            &arg_str,
4004                        );
4005                        fmt_str.push_str(&piece);
4006                        args.push(arg);
4007                    }
4008                }
4009            }
4010            writeln!(
4011                output,
4012                "{}logicaffeine_system::io::println(format_args!(\"{}\"{}));",
4013                indent_str,
4014                fmt_str,
4015                args.iter().map(|a| format!(", {}", a)).collect::<String>()
4016            )
4017            .unwrap();
4018        } else {
4019            let obj_str = codegen_expr_with_async_and_strings(
4020                object,
4021                interner,
4022                synced_vars,
4023                async_functions,
4024                ctx.get_string_vars(),
4025                ctx.get_variable_types(),
4026                ctx.get_fast_div(),
4027                registry,
4028            );
4029            let recv_str = recipient_path(
4030                recipient,
4031                interner,
4032                synced_vars,
4033                async_functions,
4034                ctx.get_variable_types(),
4035            );
4036            writeln!(
4037                output,
4038                "{}{}({});",
4039                indent_str,
4040                recv_str,
4041                super::expr::lend_to(recipient, &obj_str)
4042            )
4043            .unwrap();
4044        }
4045    } else {
4046        // Showing lends: the recipient reads the value and the caller keeps it (see `lend_to`).
4047        // Use string_vars for proper concatenation of string variables
4048        let obj_str = codegen_expr_with_async_and_strings(
4049            object,
4050            interner,
4051            synced_vars,
4052            async_functions,
4053            ctx.get_string_vars(),
4054            ctx.get_variable_types(),
4055            ctx.get_fast_div(),
4056            registry,
4057        );
4058        let recv_str = recipient_path(
4059            recipient,
4060            interner,
4061            synced_vars,
4062            async_functions,
4063            ctx.get_variable_types(),
4064        );
4065        writeln!(
4066            output,
4067            "{}{}({});",
4068            indent_str,
4069            recv_str,
4070            super::expr::lend_to(recipient, &obj_str)
4071        )
4072        .unwrap();
4073    }
4074    output
4075}
4076
4077/// The function a `Show x to f` / `Give x to f` hands its value to: the program's function by its
4078/// call path (`crate::f` where a local named `f` would shadow it), or any other callee expression.
4079fn recipient_path(
4080    recipient: &Expr,
4081    interner: &Interner,
4082    synced_vars: &HashSet<Symbol>,
4083    async_functions: &HashSet<Symbol>,
4084    variable_types: &HashMap<Symbol, String>,
4085) -> String {
4086    match recipient {
4087        Expr::Identifier(f) => super::expr::called_function_path(
4088            *f,
4089            RustNames::new(interner).ident(*f),
4090            variable_types,
4091        ),
4092        other => codegen_expr_with_async(
4093            other,
4094            interner,
4095            synced_vars,
4096            async_functions,
4097            variable_types,
4098        ),
4099    }
4100}
4101
4102/// The Rust type a `Let p be a PeerAgent at …` binding holds.
4103const PEER_AGENT_TYPE: &str = "logicaffeine_system::network::PeerAgent";
4104
4105/// The `Call` arm of [`codegen_stmt`]: an arm of [`codegen_stmt`], in a frame of its own — see [`codegen_let_stmt`].
4106#[inline(never)]
4107#[allow(clippy::too_many_arguments)]
4108fn codegen_call_stmt<'a>(
4109    mut output: String,
4110    function: &Symbol,
4111    fish: &str,
4112    args: &[&'a Expr<'a>],
4113    interner: &Interner,
4114    ctx: &mut RefinementContext<'a>,
4115    synced_vars: &mut HashSet<Symbol>,
4116    async_functions: &HashSet<Symbol>,
4117    indent_str: &str,
4118    names: &RustNames,
4119) -> String {
4120    let func_name = super::expr::called_function_path(
4121        *function,
4122        names.ident(*function),
4123        ctx.get_variable_types(),
4124    );
4125    let ecx = super::expr::ExprCtx {
4126        async_functions,
4127        variable_types: ctx.get_variable_types(),
4128        ..super::expr::ExprCtx::bare(interner, synced_vars)
4129    };
4130    if let Some(code) = super::tower::extension_call(*function, args, &ecx) {
4131        writeln!(output, "{}{};", indent_str, code).unwrap();
4132        return output;
4133    }
4134    let args_str: Vec<String> = super::expr::call_arguments(*function, args, &ecx);
4135    let await_suffix = if async_functions.contains(function) {
4136        ".await"
4137    } else {
4138        ""
4139    };
4140    let path = format!("{func_name}{fish}");
4141    let call = super::expr::sequenced_call(
4142        &path,
4143        *function,
4144        args,
4145        args_str,
4146        await_suffix,
4147        ctx.get_variable_types(),
4148    );
4149    writeln!(output, "{}{};", indent_str, call).unwrap();
4150    output
4151}
4152
4153/// The `Push` arm of [`codegen_stmt`]: an arm of [`codegen_stmt`], in a frame of its own — see [`codegen_let_stmt`].
4154#[inline(never)]
4155#[allow(clippy::too_many_arguments)]
4156fn codegen_push_stmt<'a>(
4157    mut output: String,
4158    value: &&'a Expr<'a>,
4159    collection: &&'a Expr<'a>,
4160    interner: &Interner,
4161    ctx: &mut RefinementContext<'a>,
4162    synced_vars: &mut HashSet<Symbol>,
4163    async_functions: &HashSet<Symbol>,
4164    boxed_fields: &HashSet<(String, String, String)>,
4165    registry: &TypeRegistry,
4166    indent_str: &str,
4167    names: &RustNames,
4168) -> String {
4169    if let Expr::Identifier(coll_sym) = collection {
4170        if ctx
4171            .get_variable_types()
4172            .get(coll_sym)
4173            .is_some_and(|t| t == super::tower::VALUE)
4174        {
4175            let pushed = super::tower::statement_value(
4176                value,
4177                interner,
4178                synced_vars,
4179                async_functions,
4180                boxed_fields,
4181                registry,
4182                ctx.get_variable_types(),
4183            );
4184            writeln!(
4185                output,
4186                "{}logicaffeine_data::failure::answered({}.push_value({}));",
4187                indent_str,
4188                names.ident(*coll_sym),
4189                pushed
4190            )
4191            .unwrap();
4192            return output;
4193        }
4194    }
4195    // O3: an init push into a scalarized `[T; N]` array becomes an
4196    // indexed store at the next fill position (detection proved
4197    // exactly N straight-line pushes precede any other use).
4198    if let Expr::Identifier(coll_sym) = collection {
4199        // Text write-side byte builder (Opt::TextFromBytesBuilder): `out` is a bare `Vec<u8>`, so
4200        // a push truncates the i64 byte value and appends it directly — no `LogosSeq`, no borrow,
4201        // matching the `v as u8` the runtime `text_from_bytes` used to do in a separate pass.
4202        if ctx
4203            .get_variable_types()
4204            .get(coll_sym)
4205            .map_or(false, |t| t == "ByteBuilder")
4206        {
4207            let val_str = codegen_expr_boxed_with_types_oracle(
4208                value,
4209                interner,
4210                synced_vars,
4211                boxed_fields,
4212                registry,
4213                async_functions,
4214                ctx.get_string_vars(),
4215                ctx.get_variable_types(),
4216                ctx.get_fast_div(),
4217                ctx.oracle(),
4218            );
4219            writeln!(
4220                output,
4221                "{}{}.push(({}) as u8);",
4222                indent_str,
4223                names.ident(*coll_sym),
4224                val_str
4225            )
4226            .unwrap();
4227            return output;
4228        }
4229        // Loop-built `[T; N]` return buffer (the digest): a push in the fill loop becomes a store
4230        // through the RUNTIME cursor — `out[cursor] = value; cursor += 1` — not the compile-time O3
4231        // fill (which would write slot 0 every iteration).
4232        if let Some(cursor) = ctx.loop_fill_cursor(*coll_sym).map(|s| s.to_string()) {
4233            let val_str = codegen_expr_boxed_with_types_oracle(
4234                value,
4235                interner,
4236                synced_vars,
4237                boxed_fields,
4238                registry,
4239                async_functions,
4240                ctx.get_string_vars(),
4241                ctx.get_variable_types(),
4242                ctx.get_fast_div(),
4243                ctx.oracle(),
4244            );
4245            let coll_name = names.ident(*coll_sym);
4246            writeln!(
4247                output,
4248                "{}{}[{}] = {}; {} += 1;",
4249                indent_str, coll_name, cursor, val_str, cursor
4250            )
4251            .unwrap();
4252            return output;
4253        }
4254        // Affine read-only array: the array is deleted, so its build push
4255        // emits nothing (reads substitute the closed form instead).
4256        if ctx.affine_array(*coll_sym).is_some() {
4257            return output;
4258        }
4259        // AoS interleaving: the k-th round-robin push of a member becomes
4260        // an indexed store into the backing's k-th row at this column.
4261        if let Some(tag) = parse_aos_tag(ctx.get_variable_types().get(coll_sym)) {
4262            let val_str = codegen_expr_boxed_with_types_oracle(
4263                value,
4264                interner,
4265                synced_vars,
4266                boxed_fields,
4267                registry,
4268                async_functions,
4269                ctx.get_string_vars(),
4270                ctx.get_variable_types(),
4271                ctx.get_fast_div(),
4272                ctx.oracle(),
4273            );
4274            let k = ctx.next_array_fill(*coll_sym);
4275            writeln!(
4276                output,
4277                "{}{}[{}][{}] = {};",
4278                indent_str, tag.backing, k, tag.col, val_str
4279            )
4280            .unwrap();
4281            return output;
4282        }
4283        if ctx.is_scalarized_array(*coll_sym) {
4284            let val_str = codegen_expr_boxed_with_types_oracle(
4285                value,
4286                interner,
4287                synced_vars,
4288                boxed_fields,
4289                registry,
4290                async_functions,
4291                ctx.get_string_vars(),
4292                ctx.get_variable_types(),
4293                ctx.get_fast_div(),
4294                ctx.oracle(),
4295            );
4296            let k = ctx.next_array_fill(*coll_sym);
4297            let coll_name = names.ident(*coll_sym);
4298            writeln!(output, "{}{}[{}] = {};", indent_str, coll_name, k, val_str).unwrap();
4299            return output;
4300        }
4301        // A1: inside a fill loop, the counted push of a sized
4302        // buffer-reuse buffer becomes an indexed write `buf[counter] =
4303        // val` (the buffer was `resize`d to the loop's trip count).
4304        if let Some((buf, counter)) = ctx.fill_loop().map(|(b, c)| (b, c.to_string())) {
4305            if buf == *coll_sym {
4306                let val_str = codegen_expr_boxed_with_types_oracle(
4307                    value,
4308                    interner,
4309                    synced_vars,
4310                    boxed_fields,
4311                    registry,
4312                    async_functions,
4313                    ctx.get_string_vars(),
4314                    ctx.get_variable_types(),
4315                    ctx.get_fast_div(),
4316                    ctx.oracle(),
4317                );
4318                let coll_name = names.ident(*coll_sym);
4319                // The buffer was `resize`d to this fill loop's trip count and
4320                // `counter` is its 0-based induction variable, so `counter < len`
4321                // holds by construction (a split-fill resizes to the full column
4322                // count, so every sub-loop counter stays under it). Hint it so LLVM
4323                // elides the bounds check on the DP-scan store — the "indexed
4324                // unchecked write" this transform is meant to be, matching the
4325                // append-only worklist path below. The `debug_assert` trips loudly
4326                // in tests if a future detection change ever breaks the invariant,
4327                // rather than the `assert_unchecked` going silently unsound.
4328                writeln!(output, "{}debug_assert!(({} as usize) < {}.len(), \"LOGOS fill-loop store out of range\");", indent_str, counter, coll_name).unwrap();
4329                writeln!(
4330                    output,
4331                    "{}unsafe {{ std::hint::assert_unchecked(({} as usize) < {}.len()); }}",
4332                    indent_str, counter, coll_name
4333                )
4334                .unwrap();
4335                writeln!(
4336                    output,
4337                    "{}{}[{} as usize] = {};",
4338                    indent_str, coll_name, counter, val_str
4339                )
4340                .unwrap();
4341                return output;
4342            }
4343        }
4344        // Append-only worklist: `q.push(x)` becomes a pre-sized buffer
4345        // write at a register tail — `q[tail] = x; tail += 1` — with NO
4346        // capacity check (the monotone visited-set bound proved
4347        // `tail < q.len()`). This is C's exact frontier code.
4348        if let Some(tail) = ctx.worklist(*coll_sym).map(|w| w.tail_var.clone()) {
4349            let val_str = codegen_expr_boxed_with_types_oracle(
4350                value,
4351                interner,
4352                synced_vars,
4353                boxed_fields,
4354                registry,
4355                async_functions,
4356                ctx.get_string_vars(),
4357                ctx.get_variable_types(),
4358                ctx.get_fast_div(),
4359                ctx.oracle(),
4360            );
4361            let coll_name = names.ident(*coll_sym);
4362            writeln!(
4363                output,
4364                "{}unsafe {{ std::hint::assert_unchecked({tail} < {coll_name}.len()); }}",
4365                indent_str
4366            )
4367            .unwrap();
4368            writeln!(output, "{}{coll_name}[{tail}] = {val_str};", indent_str).unwrap();
4369            writeln!(output, "{}{tail} += 1;", indent_str).unwrap();
4370            return output;
4371        }
4372    }
4373    let val_str = codegen_expr_boxed_with_types_oracle(
4374        value,
4375        interner,
4376        synced_vars,
4377        boxed_fields,
4378        registry,
4379        async_functions,
4380        ctx.get_string_vars(),
4381        ctx.get_variable_types(),
4382        ctx.get_fast_div(),
4383        ctx.oracle(),
4384    );
4385    // An item pushed onto a list of rationals is the rational it equals.
4386    let val_str = match super::rational::held_item(collection, super::rational::Typing { interner, variable_types: ctx.get_variable_types(), registry }) {
4387        Some(item) => rational_value(
4388            value,
4389            &item,
4390            interner,
4391            ctx,
4392            synced_vars,
4393            async_functions,
4394            boxed_fields,
4395            registry,
4396        )
4397        .unwrap_or(val_str),
4398        None => val_str,
4399    };
4400    let val_str = stored_value(value, val_str, ctx.get_variable_types());
4401    let val_str =
4402        value_taken_before_the_write(value, collection, val_str, ctx, indent_str, &mut output);
4403    let coll_str = codegen_expr_with_async(
4404        collection,
4405        interner,
4406        synced_vars,
4407        async_functions,
4408        ctx.get_variable_types(),
4409    );
4410    // MVS copy-on-write: a shared `LogosSeq` is deep-copied before this
4411    // in-place push so a value-semantics sibling is not mutated.
4412    emit_cow(collection, ctx, &names, &indent_str, &mut output);
4413    // A narrowed (`Vec<i32>`) sequence truncates on store — lossless,
4414    // since narrowing proved every pushed value fits i32.
4415    let narrowed_push = matches!(collection, Expr::Identifier(c) if ctx.is_narrowed(*c));
4416    if narrowed_push {
4417        // ★ A TYPED BINDING, NOT A CAST. Narrowing is lossless by proof, so the truncation is safe —
4418        // but a CAST CONSTRAINS NOTHING: `(expr) as i32` accepts any integer source type, and so does
4419        // `(expr) as i64`. When this store is the only use of a scalar, Rust has nothing left to infer
4420        // that scalar's type from and falls back to its default, `i32`. Only a typed BINDING
4421        // (`let n: i64 = expr;`) actually propagates the requirement back into the expression.
4422        //
4423        // MEASURED: `benchmarks/programs/prefix_sum/main.lg` seeds an LCG and pushes into `arr`. The
4424        // push was the one use pinning `seed` to `i64`; once `Opt::Narrow` proved `arr` fits `Vec<i32>`
4425        // and rewrote the push as `… as i32`, `seed` silently became `i32` and `seed * 1103515245`
4426        // overflowed on the first iteration — "attempt to multiply with overflow", failing
4427        // `counting_sort` and `prefix_sum` in `aot_native_corpus` (all 3 retries, and invisible in the
4428        // summary because a retried failure prints as a `TRY n FAIL` row).
4429        //
4430        // Anchoring to `i64` first says what is actually true — a LOGOS `Int` IS an i64, narrowed for
4431        // STORAGE — and keeps the value's width a property of the language rather than of whatever a
4432        // later pass leaves for inference to chew on. Fixing it here rather than at the `let` keeps the
4433        // blast radius at the pass that created the hazard.
4434        writeln!(
4435            output,
4436            "{}{}.push({{ let __nv: i64 = {}; __nv as i32 }});",
4437            indent_str, coll_str, val_str
4438        )
4439        .unwrap();
4440    } else {
4441        writeln!(output, "{}{}.push({});", indent_str, coll_str, val_str).unwrap();
4442    }
4443    output
4444}
4445
4446/// `value_str`, the value a place-write stores (`Set`, a field write, an indexed store, a push, an
4447/// add), as a value of its own: a write stores a COPY, so a binding stored whole — a record, a
4448/// Text, a shared list or map, a `mutable` parameter lent as `&mut`, anything not `Copy` — is
4449/// cloned, and stays the program's to read after the write (a clone of a binding dead after the
4450/// write is one LLVM elides). Moved as they are: a borrowed slice, already a view of a copy, and
4451/// a buffer the de-Rc and scalarizing passes own outright (`Vec`, `HashMap`, `[T; N]`) — those
4452/// passes admit a buffer only when nothing reads it after it is stored.
4453pub(super) fn stored_value(
4454    value: &Expr,
4455    value_str: String,
4456    variable_types: &HashMap<Symbol, String>,
4457) -> String {
4458    let bare = match value {
4459        Expr::Copy { expr } => *expr,
4460        other => other,
4461    };
4462    if matches!(bare, Expr::FieldAccess { .. })
4463        && super::expr::copies_out_of_a_lend(bare, variable_types)
4464    {
4465        return format!("{value_str}.clone()");
4466    }
4467    let Expr::Identifier(sym) = bare else {
4468        return value_str;
4469    };
4470    if super::expr::lent_by_sharing(*sym, variable_types) {
4471        return format!("{value_str}.deep_clone()");
4472    }
4473    let copies = match variable_types.get(sym) {
4474        Some(ty) => {
4475            let ty = ty.split("|__hl:").next().unwrap_or(ty.as_str());
4476            let moved = is_copy_type(ty)
4477                || ty.contains("__bigint")
4478                || ty.starts_with('&')
4479                || ty.starts_with("Vec<")
4480                || ty.starts_with("HashMap")
4481                || ty.starts_with("FxHashMap")
4482                || ty.starts_with('[');
4483            !moved || super::expr::mentions_generic_param(ty)
4484        }
4485        None => true,
4486    };
4487    if copies {
4488        format!("{value_str}.clone()")
4489    } else {
4490        value_str
4491    }
4492}
4493
4494/// `val_str`, the value a statement writes into `collection`. Every tier takes the value before it
4495/// touches the collection; when taking it lends the binding `collection` is rooted at, the value is
4496/// taken in a statement of its own (`__lent_value`), so the lend has ended by the time the write
4497/// borrows the collection.
4498fn value_taken_before_the_write(
4499    value: &Expr,
4500    collection: &Expr,
4501    val_str: String,
4502    ctx: &RefinementContext,
4503    indent_str: &str,
4504    output: &mut String,
4505) -> String {
4506    match get_root_identifier(collection) {
4507        Some(root) if super::expr::lends_binding(value, root, ctx.get_variable_types()) => {
4508            writeln!(output, "{}let __lent_value = {};", indent_str, val_str).unwrap();
4509            "__lent_value".to_string()
4510        }
4511        _ => val_str,
4512    }
4513}
4514
4515/// The `Return` arm of [`codegen_stmt`]: an arm of [`codegen_stmt`], in a frame of its own — see [`codegen_let_stmt`].
4516#[inline(never)]
4517#[allow(clippy::too_many_arguments)]
4518fn codegen_return_stmt<'a>(
4519    mut output: String,
4520    value: &Option<&'a Expr<'a>>,
4521    interner: &Interner,
4522    ctx: &mut RefinementContext<'a>,
4523    synced_vars: &mut HashSet<Symbol>,
4524    async_functions: &HashSet<Symbol>,
4525    boxed_fields: &HashSet<(String, String, String)>,
4526    registry: &TypeRegistry,
4527    indent_str: &str,
4528) -> String {
4529    // A function whose result holds a value-or-nothing returns `nothing`, another whole, or a value present.
4530    if let (Some(v), Some(held)) = (value, super::absent::returning()) {
4531        let ecx = operand_ctx(interner, ctx, synced_vars, async_functions, boxed_fields, registry);
4532        if let Some(code) = super::absent::stored(v, &held, &ecx) {
4533            writeln!(output, "{}return {};", indent_str, code).unwrap();
4534            return output;
4535        }
4536    }
4537    if let (Some(v), true) = (value, super::tower::emitting_a_reached_function()) {
4538        let code = super::tower::statement_value(
4539            v,
4540            interner,
4541            synced_vars,
4542            async_functions,
4543            boxed_fields,
4544            registry,
4545            ctx.get_variable_types(),
4546        );
4547        writeln!(output, "{}return {};", indent_str, code).unwrap();
4548        return output;
4549    }
4550    // A function whose result holds rationals returns an integer as the rational it equals.
4551    if let (Some(v), Some(held)) = (value, ctx.returns_rationals().cloned()) {
4552        if let Some(code) = rational_value(
4553            v,
4554            &held,
4555            interner,
4556            ctx,
4557            synced_vars,
4558            async_functions,
4559            boxed_fields,
4560            registry,
4561        ) {
4562            writeln!(output, "{}return {};", indent_str, code).unwrap();
4563            return output;
4564        }
4565    }
4566    if let Some(v) = value {
4567        // A `-> LogosInt` function returns its value un-narrowed (`.into()` is identity for a
4568        // LogosInt, and promotes a plain `i64`), so an overflowing result stays a BigInt.
4569        if ctx.returns_bigint() {
4570            // `Return p` of a bignum local is p's last use — move it out, no clone.
4571            let movable_ret = matches!(v, Expr::Identifier(sym) if ctx.is_bigint_var(*sym));
4572            if let Expr::Identifier(sym) = v {
4573                if movable_ret {
4574                    set_movable_last_use(Some(*sym));
4575                }
4576            }
4577            let raw = codegen_expr_boxed_with_types_oracle_tolerant(
4578                v,
4579                interner,
4580                synced_vars,
4581                boxed_fields,
4582                registry,
4583                async_functions,
4584                ctx.get_string_vars(),
4585                ctx.get_variable_types(),
4586                ctx.get_fast_div(),
4587                ctx.oracle(),
4588            );
4589            if movable_ret {
4590                set_movable_last_use(None);
4591            }
4592            writeln!(
4593                output,
4594                "{}return logicaffeine_data::LogosInt::from({});",
4595                indent_str, raw
4596            )
4597            .unwrap();
4598            return output;
4599        }
4600        let value_str = codegen_expr_boxed_with_types_oracle(
4601            v,
4602            interner,
4603            synced_vars,
4604            boxed_fields,
4605            registry,
4606            async_functions,
4607            ctx.get_string_vars(),
4608            ctx.get_variable_types(),
4609            ctx.get_fast_div(),
4610            ctx.oracle(),
4611        );
4612        // If returning a borrowed slice param (or copy of one), wrap in LogosSeq
4613        let slice_sym = match v {
4614            Expr::Identifier(sym) => Some(*sym),
4615            Expr::Copy { expr: inner } => {
4616                if let Expr::Identifier(sym) = inner {
4617                    Some(*sym)
4618                } else {
4619                    None
4620                }
4621            }
4622            _ => None,
4623        };
4624        let needs_to_vec = slice_sym
4625            .and_then(|sym| ctx.get_variable_types().get(&sym))
4626            .map(|t| t.starts_with("&["))
4627            .unwrap_or(false);
4628        // A scalarized `[T; N]` stack buffer (scratch / indexed / cursor-fill) that
4629        // is `return`ed by a fn whose DECLARED result is a heap `Vec<T>` — the
4630        // local scalarization and the heap return type disagree, so materialize the
4631        // owned copy (`[T; N]` exposes `.to_vec()` just like `&[T]`). A PROPER
4632        // array-return fn has `returns_vec() == false` and stays a direct `return`.
4633        let ret_ty_is_scalar_array = slice_sym
4634            .and_then(|sym| ctx.get_variable_types().get(&sym))
4635            .map(|t| t.starts_with('['))
4636            .unwrap_or(false);
4637        // If returning a &mut borrow param, the mutation was in-place — just return
4638        let is_mut_borrow_return = if let Expr::Identifier(sym) = v {
4639            ctx.get_variable_types()
4640                .get(sym)
4641                .map(|t| t.starts_with("&mut ["))
4642                .unwrap_or(false)
4643        } else {
4644            false
4645        };
4646        if is_mut_borrow_return {
4647            writeln!(output, "{}return;", indent_str).unwrap();
4648        } else if (needs_to_vec || ret_ty_is_scalar_array) && ctx.returns_vec() {
4649            // Phase 4: the function returns owned `Vec<T>` — return the
4650            // owned copy directly, no `LogosSeq::from_vec(...)` wrapper.
4651            writeln!(output, "{}return {}.to_vec();", indent_str, value_str).unwrap();
4652        } else if needs_to_vec {
4653            writeln!(
4654                output,
4655                "{}return LogosSeq::from_vec({}.to_vec());",
4656                indent_str, value_str
4657            )
4658            .unwrap();
4659        } else if super::expr::copies_out_of_a_lend(v, ctx.get_variable_types()) {
4660            writeln!(output, "{}return {}.clone();", indent_str, value_str).unwrap();
4661        } else {
4662            writeln!(output, "{}return {};", indent_str, value_str).unwrap();
4663        }
4664    } else {
4665        writeln!(output, "{}return;", indent_str).unwrap();
4666    }
4667    output
4668}
4669
4670/// What the `Serve` arm needs to know about the whole program: whether it declares a `## Session`,
4671/// and which of its functions take the program's bindings ([`crate::program_bindings`]) first.
4672#[derive(Default)]
4673struct ServeFacts {
4674    declares_session: bool,
4675    lends_program: HashSet<Symbol>,
4676}
4677
4678thread_local! {
4679    /// [`ServeFacts`] for the program being emitted — installed once at codegen entry, where the
4680    /// whole program is visible, and read by the `Serve` arm, which reaches a statement with no
4681    /// program in hand.
4682    static SERVE_FACTS: std::cell::RefCell<ServeFacts> = std::cell::RefCell::new(ServeFacts::default());
4683}
4684
4685pub(crate) fn set_serve_facts(stmts: &[Stmt], interner: &Interner) {
4686    let program = interner.lookup(crate::program_bindings::PROGRAM_BINDING);
4687    let lends_program = stmts
4688        .iter()
4689        .filter_map(|s| match s {
4690            Stmt::FunctionDef { name, params, .. }
4691                if program.is_some() && params.first().map(|(p, _)| *p) == program =>
4692            {
4693                Some(*name)
4694            }
4695            _ => None,
4696        })
4697        .collect();
4698    let declares_session =
4699        logicaffeine_language::parser::lgx_lower::declares_session(stmts, interner);
4700    SERVE_FACTS.with(|facts| {
4701        *facts.borrow_mut() = ServeFacts {
4702            declares_session,
4703            lends_program,
4704        }
4705    });
4706}
4707
4708/// The emitted conversion of the handler's `Response` bound to `resp` into the wire's
4709/// `HttpResponse`, as the tail expression of the block it is written into. The response's headers
4710/// merge through the shared denylist and response-splitting filter, then the authoritative (and
4711/// wire-safe) Content-Type is set last; a non-empty `bytes` field is a raw binary body (a `.wasm`,
4712/// an image …) and wins over the text `body`, each Int one byte — the interpreter's
4713/// `value_to_http_response` rule, byte for byte.
4714fn emit_wire_response(output: &mut String, indent: &str, resp: &str) {
4715    writeln!(
4716        output,
4717        "{indent}let mut __headers = std::collections::BTreeMap::new();"
4718    )
4719    .unwrap();
4720    writeln!(
4721        output,
4722        "{indent}for (__k, __v) in {resp}.headers.borrow().iter() {{"
4723    )
4724    .unwrap();
4725    writeln!(output, "{indent}    if logicaffeine_system::http::wire::response_header_allowed(__k, __v) {{ __headers.insert(__k.clone(), __v.clone()); }}").unwrap();
4726    writeln!(output, "{indent}}}").unwrap();
4727    writeln!(output, "{indent}__headers.insert(\"Content-Type\".to_string(), logicaffeine_system::http::wire::safe_content_type(&{resp}.contentType).to_string());").unwrap();
4728    writeln!(
4729        output,
4730        "{indent}let __bytes: Vec<u8> = {resp}.bytes.iter().map(|__b| __b as u8).collect();"
4731    )
4732    .unwrap();
4733    writeln!(output, "{indent}let __body = if __bytes.is_empty() {{ {resp}.body.into_bytes() }} else {{ __bytes }};").unwrap();
4734    writeln!(output, "{indent}logicaffeine_system::http::wire::HttpResponse {{ status: {resp}.status as u16, headers: __headers, body: __body }}").unwrap();
4735}
4736
4737/// The `Serve` arm of [`codegen_stmt`]: an arm of [`codegen_stmt`], in a frame of its own — see [`codegen_let_stmt`].
4738#[inline(never)]
4739#[allow(clippy::too_many_arguments)]
4740fn codegen_serve_stmt<'a>(
4741    mut output: String,
4742    port: &&'a Expr<'a>,
4743    handler: &&'a Expr<'a>,
4744    interner: &Interner,
4745    ctx: &mut RefinementContext<'a>,
4746    synced_vars: &mut HashSet<Symbol>,
4747    async_functions: &HashSet<Symbol>,
4748    indent_str: &str,
4749) -> String {
4750    let port_str = codegen_expr_with_async(
4751        port,
4752        interner,
4753        synced_vars,
4754        async_functions,
4755        ctx.get_variable_types(),
4756    );
4757    let handler_sym = match handler {
4758        Expr::Identifier(sym) => *sym,
4759        _ => {
4760            writeln!(
4761                output,
4762                "{}compile_error!(\"Serve: the handler must be a named function\");",
4763                indent_str
4764            )
4765            .unwrap();
4766            return output;
4767        }
4768    };
4769    let handler_name = interner.resolve(handler_sym).to_string();
4770    let (declares_session, lends_program) = SERVE_FACTS.with(|facts| {
4771        let facts = facts.borrow();
4772        (
4773            facts.declares_session,
4774            facts.lends_program.contains(&handler_sym),
4775        )
4776    });
4777    // ★ A HANDLER THAT TAKES THE PROGRAM'S BINDINGS is lent them on every call, and is served on
4778    // this thread (`serve_here`): the bindings hold collections that cannot cross to the engine's
4779    // threads. Calls stay one at a time, as `serve` serializes them. The record is the local
4780    // `## Main` holds, or the `mutable` parameter of a function that serves.
4781    let lend = if lends_program {
4782        let program = crate::program_bindings::PROGRAM_BINDING;
4783        let through_a_parameter = interner
4784            .lookup(program)
4785            .and_then(|sym| ctx.get_variable_types().get(&sym))
4786            .is_some_and(|ty| ty.starts_with('&'));
4787        if through_a_parameter {
4788            format!("&mut *{program}, ")
4789        } else {
4790            format!("&mut {program}, ")
4791        }
4792    } else {
4793        String::new()
4794    };
4795    // `LOGOS_HOST` names the interface (default loopback) and `LOGOS_PORT` (then
4796    // `PORT`) overrides the program's port expression — the same
4797    // `env_bind_address` seam the interpreter tier applies, so dev proxying and
4798    // PaaS deployment work identically on both tiers. The HOST matters here in
4799    // particular: this is the tier a site actually SHIPS as, and a binary that
4800    // binds loopback inside a container is unreachable from outside it.
4801    // An embedded site whose pages talk to the relay answers `/_relay` itself — a deployed page
4802    // can dial nothing else. Its pages decided that at build time (`logos_assets::USES_RELAY`);
4803    // a binary with no pages serves exactly as it always did.
4804    let upgrades = crate::codegen::embed_assets_enabled().then(|| {
4805        "if logos_assets::USES_RELAY { logicaffeine_system::relay::RelayHub::new().upgrades() } else { ::std::vec::Vec::new() }"
4806            .to_string()
4807    });
4808    let entry = match (lends_program, upgrades.is_some()) {
4809        (false, false) => "serve",
4810        (false, true) => "serve_with_upgrades",
4811        (true, false) => "serve_here",
4812        (true, true) => "serve_here_with_upgrades",
4813    };
4814    writeln!(output, "{indent_str}logicaffeine_system::http::server::{entry}(&logicaffeine_system::http::server::env_bind_address(logicaffeine_system::http::server::env_port_override(({port_str}) as u16)), |__raw: logicaffeine_system::http::wire::HttpRequest| {{").unwrap();
4815    // B4 — embedded full-stack site (a `largo build` web binary): consult the
4816    // bundled `logos_assets` table on the REQUEST PATH before the handler runs, so
4817    // a page/static asset shadows a backend route — exactly the dev router's
4818    // precedence (`serve_web::route_local`), making dev ≡ prod by construction.
4819    // A `GET` hits the table; anything else falls through to the handler, because a
4820    // POST to a path a file also occupies belongs to the handler. A QUERY STRING does
4821    // NOT disqualify a request: `logos_assets::lookup` matches by path (and splits a
4822    // query off itself), so `/style.css?v=2` — an ordinary cache-buster — serves here
4823    // exactly as it does in `largo serve`. Gating on an empty query made that 404 in
4824    // production while working all through development. The
4825    // scope is off by default, so a plain `Serve` program lowers byte-identically.
4826    if crate::codegen::embed_assets_enabled() {
4827        writeln!(output, "{indent_str}    if __raw.method == \"GET\" {{").unwrap();
4828        writeln!(output, "{indent_str}        if let Some((__ct, __cc, __et, __asset)) = logos_assets::lookup(&__raw.path) {{").unwrap();
4829        writeln!(
4830            output,
4831            "{indent_str}            let mut __ah = std::collections::BTreeMap::new();"
4832        )
4833        .unwrap();
4834        writeln!(
4835            output,
4836            "{indent_str}            __ah.insert(\"Content-Type\".to_string(), __ct.to_string());"
4837        )
4838        .unwrap();
4839        // The cache headers travel with the bytes: a content-addressed asset is cached for a year
4840        // and never revalidated (a different body would be a different URL), everything else is
4841        // revalidated cheaply against its ETag.
4842        writeln!(
4843            output,
4844            "{indent_str}            __ah.insert(\"Cache-Control\".to_string(), __cc.to_string());"
4845        )
4846        .unwrap();
4847        writeln!(
4848            output,
4849            "{indent_str}            __ah.insert(\"ETag\".to_string(), __et.to_string());"
4850        )
4851        .unwrap();
4852        // ★ A PAGE OF A SERVER WITH A `## Session` IS COMPOSED FOR ITS VISITOR, before any cache
4853        // validator is consulted: the handler is asked for the visitor's token at the router's
4854        // reserved path, with the visitor's own cookie, and the document goes out with that token
4855        // in its `<meta name="csrf-token">` — where the page's scripted requests read it — the
4856        // answer's `Set-Cookie`, and `no-store`, since the document now belongs to one visitor.
4857        // `largo serve` composes a page the same way (`serve_web::page_for_visitor`). A handler
4858        // that answers no token leaves the page as it was.
4859        if declares_session {
4860            let token_path = logicaffeine_language::parser::lgx_lower::CSRF_TOKEN_PATH;
4861            writeln!(
4862                output,
4863                "{indent_str}            if logos_assets::is_page(&__raw.path) {{"
4864            )
4865            .unwrap();
4866            writeln!(
4867                output,
4868                "{indent_str}                let __th = LogosMap::new();"
4869            )
4870            .unwrap();
4871            writeln!(output, "{indent_str}                if let Some((_, __c)) = __raw.headers.iter().find(|(__k, _)| __k.eq_ignore_ascii_case(\"cookie\")) {{ __th.insert(\"cookie\".to_string(), __c.clone()); }}").unwrap();
4872            writeln!(output, "{indent_str}                let __tr = {handler_name}({lend}Request {{ method: \"GET\".to_string(), path: {token_path:?}.to_string(), body: String::new(), headers: __th, query: LogosMap::new(), ..Default::default() }});").unwrap();
4873            writeln!(output, "{indent_str}                let __tok = {{").unwrap();
4874            emit_wire_response(
4875                &mut output,
4876                &format!("{indent_str}                    "),
4877                "__tr",
4878            );
4879            writeln!(output, "{indent_str}                }};").unwrap();
4880            writeln!(output, "{indent_str}                let __page = logicaffeine_system::http::wire::HttpResponse {{ status: 200, headers: __ah.clone(), body: __asset.to_vec() }};").unwrap();
4881            writeln!(output, "{indent_str}                if let Some(__composed) = logicaffeine_system::http::server::page_with_visitor_token(&__page, &__tok) {{ return __composed; }}").unwrap();
4882            writeln!(output, "{indent_str}            }}").unwrap();
4883        }
4884        // ★ NEGOTIATE, DECLARE, VARY — one contract in three headers. A compressed body
4885        // sent to a client that did not ask for one is unreadable; a compressed body sent
4886        // without `Vary: Accept-Encoding` is one a shared cache will hand to the next
4887        // client whether or not it asked. And the variant carries its OWN ETag, because
4888        // two bodies under one entity tag is exactly how that cache mix-up happens.
4889        writeln!(output, "{indent_str}            let __ae = __raw.headers.iter().find(|(__k, _)| __k.eq_ignore_ascii_case(\"accept-encoding\")).map(|(_, __v)| __v.as_str()).unwrap_or(\"\");").unwrap();
4890        writeln!(output, "{indent_str}            let __gz = if __ae.split(',').any(|__e| __e.trim().split(';').next().unwrap_or(\"\").eq_ignore_ascii_case(\"gzip\")) {{ logos_assets::encoded(&__raw.path) }} else {{ None }};").unwrap();
4891        writeln!(output, "{indent_str}            if __gz.is_some() {{ __ah.insert(\"Vary\".to_string(), \"Accept-Encoding\".to_string()); }}").unwrap();
4892        writeln!(output, "{indent_str}            let (__et, __body_src): (&str, &[u8]) = match __gz {{ Some((__e, __b)) => {{ __ah.insert(\"Content-Encoding\".to_string(), \"gzip\".to_string()); (__e, __b) }}, None => (__et, __asset) }};").unwrap();
4893        writeln!(output, "{indent_str}            __ah.insert(\"ETag\".to_string(), format!(\"\\\"{{}}\\\"\", __et.trim_matches('\\\"')));").unwrap();
4894        writeln!(output, "{indent_str}            let __inm = __raw.headers.iter().find(|(__k, _)| __k.eq_ignore_ascii_case(\"if-none-match\")).map(|(_, __v)| __v.as_str());").unwrap();
4895        writeln!(
4896            output,
4897            "{indent_str}            if logos_assets::fresh(__et, __inm) {{"
4898        )
4899        .unwrap();
4900        writeln!(output, "{indent_str}                return logicaffeine_system::http::wire::HttpResponse {{ status: 304, headers: __ah, body: Vec::new() }};").unwrap();
4901        writeln!(output, "{indent_str}            }}").unwrap();
4902        writeln!(output, "{indent_str}            return logicaffeine_system::http::wire::HttpResponse {{ status: 200, headers: __ah, body: __body_src.to_vec() }};").unwrap();
4903        writeln!(output, "{indent_str}        }}").unwrap();
4904        writeln!(output, "{indent_str}    }}").unwrap();
4905    }
4906    // Headers (wire-lowercased names) and query (percent-decoded) ride
4907    // into the Request as LogosMaps, inserted in the wire map's sorted
4908    // order — the interpreter's `http_request_to_value`, byte for byte.
4909    writeln!(output, "{indent_str}    let __hdrs = LogosMap::new();").unwrap();
4910    writeln!(
4911        output,
4912        "{indent_str}    for (__k, __v) in __raw.headers {{ __hdrs.insert(__k, __v); }}"
4913    )
4914    .unwrap();
4915    writeln!(output, "{indent_str}    let __qry = LogosMap::new();").unwrap();
4916    writeln!(
4917        output,
4918        "{indent_str}    for (__k, __v) in __raw.query {{ __qry.insert(__k, __v); }}"
4919    )
4920    .unwrap();
4921    writeln!(output, "{indent_str}    let __req = Request {{ method: __raw.method, path: __raw.path, body: String::from_utf8_lossy(&__raw.body).into_owned(), headers: __hdrs, query: __qry, ..Default::default() }};").unwrap();
4922    writeln!(
4923        output,
4924        "{indent_str}    let __resp = {handler_name}({lend}__req);"
4925    )
4926    .unwrap();
4927    emit_wire_response(&mut output, &format!("{indent_str}    "), "__resp");
4928    match upgrades {
4929        Some(table) => {
4930            writeln!(output, "{indent_str}}}, {table}).await.expect(\"serve\");").unwrap()
4931        }
4932        None => writeln!(output, "{indent_str}}}).await.expect(\"serve\");").unwrap(),
4933    }
4934    output
4935}
4936
4937/// The `SetIndex` arm of [`codegen_stmt`], in a frame of its own — see [`codegen_let_stmt`].
4938#[inline(never)]
4939#[allow(clippy::too_many_arguments)]
4940fn codegen_set_index_stmt<'a>(
4941    mut output: String,
4942    collection: &&'a Expr<'a>,
4943    index: &&'a Expr<'a>,
4944    value: &&'a Expr<'a>,
4945    interner: &Interner,
4946    ctx: &mut RefinementContext<'a>,
4947    synced_vars: &mut HashSet<Symbol>,
4948    async_functions: &HashSet<Symbol>,
4949    boxed_fields: &HashSet<(String, String, String)>,
4950    registry: &TypeRegistry,
4951    indent_str: &str,
4952    names: &RustNames,
4953) -> String {
4954    if let Expr::Identifier(coll_sym) = collection {
4955        if ctx
4956            .get_variable_types()
4957            .get(coll_sym)
4958            .is_some_and(|t| t == super::tower::VALUE)
4959        {
4960            let value_of = |e: &Expr| {
4961                super::tower::statement_value(
4962                    e,
4963                    interner,
4964                    synced_vars,
4965                    async_functions,
4966                    boxed_fields,
4967                    registry,
4968                    ctx.get_variable_types(),
4969                )
4970            };
4971            let (at, stored) = (value_of(index), value_of(value));
4972            writeln!(
4973                output,
4974                "{}logicaffeine_data::failure::answered({}.set_item(&({}), {}));",
4975                indent_str,
4976                names.ident(*coll_sym),
4977                at,
4978                stored
4979            )
4980            .unwrap();
4981            return output;
4982        }
4983    }
4984    // Nested value-semantic THROUGH-WRITE `grid[k][i] = v` (a fused place-write, see
4985    // splice_fuse): cow the outer grid, then `set_nested` cow's the ROW only if it is shared
4986    // — O(1) when uniquely owned, versus the desugar's unconditional full-row clone. Scoped
4987    // to a `LogosSeq<LogosSeq<…>>` base (the nested-array case); any other nested shape falls
4988    // through to the general handling below, and the compiled-vs-interpreted differential
4989    // guards value-semantics soundness for every shape.
4990    if let Expr::Index {
4991        collection: base,
4992        index: outer_idx,
4993    } = collection
4994    {
4995        if let Expr::Identifier(base_sym) = base {
4996            let is_nested_seq = ctx.get_variable_types().get(base_sym).map_or(false, |t| {
4997                t.split("|__hl:")
4998                    .next()
4999                    .unwrap_or(t)
5000                    .starts_with("LogosSeq<LogosSeq")
5001            });
5002            if is_nested_seq {
5003                let value_str = codegen_expr_boxed_with_types_oracle(
5004                    value,
5005                    interner,
5006                    synced_vars,
5007                    boxed_fields,
5008                    registry,
5009                    async_functions,
5010                    ctx.get_string_vars(),
5011                    ctx.get_variable_types(),
5012                    ctx.get_fast_div(),
5013                    ctx.oracle(),
5014                );
5015                let mut k_idx =
5016                    super::peephole::logos_index(outer_idx, interner, ctx.get_variable_types());
5017                let mut i_idx = super::peephole::logos_index(index, interner, ctx.get_variable_types());
5018                let mut value_str = value_str;
5019                // Operands one of which can change what another reads are taken in the language's order — the
5020                // item's index, the value, then the row's — each in a statement of its own, before the store reads
5021                // any of them.
5022                if ordered(&[*index, *value, *outer_idx]) {
5023                    let full = |e: &Expr| {
5024                        codegen_expr_with_async(e, interner, synced_vars, async_functions, ctx.get_variable_types())
5025                    };
5026                    let (i_full, k_full) = (full(index), full(outer_idx));
5027                    writeln!(output, "{indent_str}let __place_index = {i_full};").unwrap();
5028                    writeln!(output, "{indent_str}let __place_value = {value_str};").unwrap();
5029                    writeln!(output, "{indent_str}let __place_key = {k_full};").unwrap();
5030                    (i_idx, value_str, k_idx) =
5031                        ("__place_index".to_string(), "__place_value".to_string(), "__place_key".to_string());
5032                }
5033                emit_cow(base, ctx, &names, &indent_str, &mut output);
5034                writeln!(
5035                    output,
5036                    "{}{}.set_nested({}, {}, {});",
5037                    indent_str,
5038                    names.ident(*base_sym),
5039                    k_idx,
5040                    i_idx,
5041                    value_str
5042                )
5043                .unwrap();
5044                return output;
5045            }
5046        }
5047    }
5048    // AoS interleaving: `Set item i of member to v` → `backing[(i-1)][col] = v`.
5049    if let Expr::Identifier(sym) = collection {
5050        if let Some(tag) = parse_aos_tag(ctx.get_variable_types().get(sym)) {
5051            let value_str = codegen_expr_boxed_with_types_oracle(
5052                value,
5053                interner,
5054                synced_vars,
5055                boxed_fields,
5056                registry,
5057                async_functions,
5058                ctx.get_string_vars(),
5059                ctx.get_variable_types(),
5060                ctx.get_fast_div(),
5061                ctx.oracle(),
5062            );
5063            let at = super::peephole::logos_index(index, interner, ctx.get_variable_types());
5064            let item = super::expr::item_accessor(index, ctx.oracle(), true);
5065            writeln!(
5066                output,
5067                "{}{}.{}({})[{}] = {};",
5068                indent_str, tag.backing, item, at, tag.col, value_str
5069            )
5070            .unwrap();
5071            return output;
5072        }
5073    }
5074    let coll_str = codegen_expr_with_async(
5075        collection,
5076        interner,
5077        synced_vars,
5078        async_functions,
5079        ctx.get_variable_types(),
5080    );
5081    let value_str = codegen_expr_boxed_with_types_oracle(
5082        value,
5083        interner,
5084        synced_vars,
5085        boxed_fields,
5086        registry,
5087        async_functions,
5088        ctx.get_string_vars(),
5089        ctx.get_variable_types(),
5090        ctx.get_fast_div(),
5091        ctx.oracle(),
5092    );
5093    // An item stored into a list of rationals is the rational it equals.
5094    let value_str = match super::rational::held_item(collection, super::rational::Typing { interner, variable_types: ctx.get_variable_types(), registry }) {
5095        Some(item) => rational_value(
5096            value,
5097            &item,
5098            interner,
5099            ctx,
5100            synced_vars,
5101            async_functions,
5102            boxed_fields,
5103            registry,
5104        )
5105        .unwrap_or(value_str),
5106        None => value_str,
5107    };
5108    let value_str = stored_value(value, value_str, ctx.get_variable_types());
5109
5110    // A rational names the item it stores into as the integer it equals.
5111    let rational_index = {
5112        let ecx = super::expr::ExprCtx {
5113            async_functions,
5114            variable_types: ctx.get_variable_types(),
5115            ..super::expr::ExprCtx::bare(interner, synced_vars)
5116        };
5117        super::rational::item_index(
5118            collection,
5119            index,
5120            crate::semantics::collections::IntegerPlace::ListStore,
5121            &ecx,
5122        )
5123    };
5124    if let Some(at) = rational_index {
5125        writeln!(output, "{}let __rational_index: i64 = {};", indent_str, at).unwrap();
5126        writeln!(output, "{}let __rational_value = {};", indent_str, value_str).unwrap();
5127        emit_cow(collection, ctx, &names, &indent_str, &mut output);
5128        writeln!(
5129            output,
5130            "{}LogosIndexMut::logos_set(&mut {}, __rational_index, __rational_value);",
5131            indent_str, coll_str
5132        )
5133        .unwrap();
5134        return output;
5135    }
5136
5137    // The index and then the value are taken before the collection is touched; when taking
5138    // either calls, or lends the collection's own binding, each is taken in a statement of its own,
5139    // so the index is read before the value can change it and every lend has ended by the time the
5140    // store borrows.
5141    if let Some(root) = get_root_identifier(collection) {
5142        let types = ctx.get_variable_types();
5143        if ordered(&[*index, *value])
5144            || super::expr::lends_binding(index, root, types)
5145            || super::expr::lends_binding(value, root, types)
5146        {
5147            let index_str = codegen_expr_with_async(
5148                index,
5149                interner,
5150                synced_vars,
5151                async_functions,
5152                ctx.get_variable_types(),
5153            );
5154            writeln!(output, "{}let __lent_index = {};", indent_str, index_str).unwrap();
5155            writeln!(output, "{}let __lent_value = {};", indent_str, value_str).unwrap();
5156            emit_cow(collection, ctx, &names, &indent_str, &mut output);
5157            writeln!(
5158                output,
5159                "{}LogosIndexMut::logos_set(&mut {}, __lent_index, __lent_value);",
5160                indent_str, coll_str
5161            )
5162            .unwrap();
5163            return output;
5164        }
5165    }
5166
5167    // MVS copy-on-write before the in-place indexed store / map insert.
5168    // A no-op for the `Vec`/slice/array and `FxHashMap` arms below (they
5169    // are not shared `Rc`s); fires only for a real `LogosSeq`/`LogosMap`.
5170    emit_cow(collection, ctx, &names, &indent_str, &mut output);
5171
5172    // Direct indexing for known collection types (avoids trait dispatch)
5173    // Strip |__hl: hoisting suffix so type matching works correctly.
5174    let known_type = if let Expr::Identifier(sym) = collection {
5175        ctx.get_variable_types()
5176            .get(sym)
5177            .map(|s| s.split("|__hl:").next().unwrap_or(s.as_str()))
5178    } else {
5179        None
5180    };
5181
5182    match known_type {
5183        // A bit-packed `Seq of Bool` (`Opt::BitPack`): the store sets or clears the bit the index names, unchecked
5184        // where the oracle proves the index in range, where `true` is one `or` into its word.
5185        Some("LogosBits") => {
5186            let store_unchecked = crate::optimize::active_config()
5187                .is_on(crate::optimization::Opt::Unchecked)
5188                && ctx
5189                    .oracle()
5190                    .map_or(false, |o| o.index_provably_in_bounds(collection, index));
5191            if store_unchecked {
5192                crate::optimize::mark_fired(crate::optimization::Opt::Unchecked);
5193                let zb_index =
5194                    super::expr::zero_based_index_str(index, ctx.get_variable_types(), interner);
5195                let i0 = match &zb_index {
5196                    Some(s) => s.clone(),
5197                    None => simplify_1based_index(index, interner, false, ctx.get_variable_types()),
5198                };
5199                let offset = store_offset(index, zb_index.as_deref(), interner, ctx);
5200                writeln!(output, "{}debug_assert!(({}) >= 0 && ({}) < ({}.len() as i64), \"LOGOS oracle BCE: store out of range\");", indent_str, i0, i0, coll_str).unwrap();
5201                if matches!(value, Expr::Literal(Literal::Boolean(true))) {
5202                    writeln!(
5203                        output,
5204                        "{}unsafe {{ {}.set_true_unchecked({}); }}",
5205                        indent_str, coll_str, offset
5206                    )
5207                    .unwrap();
5208                } else {
5209                    writeln!(output, "{}let __set_val: bool = {};", indent_str, value_str).unwrap();
5210                    writeln!(
5211                        output,
5212                        "{}unsafe {{ {}.set_unchecked({}, __set_val); }}",
5213                        indent_str, coll_str, offset
5214                    )
5215                    .unwrap();
5216                }
5217            } else {
5218                let at = super::peephole::logos_index(index, interner, ctx.get_variable_types());
5219                writeln!(output, "{}let __set_val: bool = {};", indent_str, value_str).unwrap();
5220                writeln!(
5221                    output,
5222                    "{}{}.set_item({}, __set_val);",
5223                    indent_str, coll_str, at
5224                )
5225                .unwrap();
5226            }
5227        }
5228        Some(t) if t.starts_with("LogosSeq") => {
5229            // Use borrow_mut() for interior mutability — no &mut needed on the variable.
5230            let zb_index =
5231                super::expr::zero_based_index_str(index, ctx.get_variable_types(), interner);
5232            let at = super::peephole::logos_index(index, interner, ctx.get_variable_types());
5233            // BCE: when the oracle proves the store index in range, emit
5234            // an unchecked store through the borrow (no bounds branch)
5235            // with a `debug_assert!` net — the value-semantic analog of
5236            // the `Vec` path below. Soundness: the kernel-LIA proof + the
5237            // function entry precondition. `LOGOS_ORACLE_UNCHECKED=0` forces
5238            // checked. The `borrow_mut()` sees the owned buffer (a `cow()`
5239            // was emitted before this store for value bindings).
5240            let store_unchecked = crate::optimize::active_config()
5241                .is_on(crate::optimization::Opt::Unchecked)
5242                && ctx
5243                    .oracle()
5244                    .map_or(false, |o| o.index_provably_in_bounds(collection, index));
5245            // A store the range oracle proves in range is a plain indexed store, whose own check never fires.
5246            let place = if super::expr::range_proves_index(collection, index) {
5247                format!(
5248                    "{}.borrow_mut()[{}]",
5249                    coll_str,
5250                    store_offset(index, zb_index.as_deref(), interner, ctx)
5251                )
5252            } else {
5253                format!(
5254                    "*{}.borrow_mut().{}({})",
5255                    coll_str,
5256                    super::expr::item_accessor(index, ctx.oracle(), true),
5257                    at
5258                )
5259            };
5260            // If the RHS borrows ANY collection, evaluate it into a temp
5261            // first: under reference semantics that collection may alias
5262            // the target (e.g. `prev` after `Set prev to curr`), and a
5263            // live borrow() across the target's borrow_mut() panics.
5264            let needs_tmp = store_unchecked || expr_reads_any_collection(value);
5265            if store_unchecked {
5266                crate::optimize::mark_fired(crate::optimization::Opt::Unchecked);
5267                let i0 = match &zb_index {
5268                    Some(s) => s.clone(),
5269                    None => simplify_1based_index(index, interner, false, ctx.get_variable_types()),
5270                };
5271                let offset = store_offset(index, zb_index.as_deref(), interner, ctx);
5272                writeln!(output, "{}debug_assert!(({}) >= 0 && ({}) < ({}.len() as i64), \"LOGOS oracle BCE: store out of range\");", indent_str, i0, i0, coll_str).unwrap();
5273                writeln!(output, "{}let __set_val = {};", indent_str, value_str).unwrap();
5274                writeln!(
5275                    output,
5276                    "{}unsafe {{ *{}.borrow_mut().get_unchecked_mut({}) = __set_val; }}",
5277                    indent_str, coll_str, offset
5278                )
5279                .unwrap();
5280            } else if needs_tmp {
5281                writeln!(output, "{}let __set_val = {};", indent_str, value_str).unwrap();
5282                writeln!(output, "{}{} = __set_val;", indent_str, place).unwrap();
5283            } else {
5284                writeln!(output, "{}{} = {};", indent_str, place, value_str).unwrap();
5285            }
5286        }
5287        Some(t) if is_logos_map_type(t) => {
5288            let index_str = codegen_expr_with_async(
5289                index,
5290                interner,
5291                synced_vars,
5292                async_functions,
5293                ctx.get_variable_types(),
5294            );
5295            writeln!(
5296                output,
5297                "{}{}.insert({}, {});",
5298                indent_str, coll_str, index_str, value_str
5299            )
5300            .unwrap();
5301        }
5302        Some(t)
5303            if t.starts_with("Vec")
5304                || t.starts_with("&mut [")
5305                || t.starts_with("&[")
5306                || t.starts_with('[') =>
5307        {
5308            // Vec / slice / fixed array (O3) — a store through the item the index names.
5309            let zb_index =
5310                super::expr::zero_based_index_str(index, ctx.get_variable_types(), interner);
5311            // A narrowed (`Vec<i32>`) sequence truncates on store — lossless,
5312            // since narrowing proved every stored value fits i32.
5313            // Same anchor as the narrowed push above, and for the same reason: a typed binding,
5314            // because a cast would leave the stored expression's own type to inference.
5315            let narrowed = matches!(collection, Expr::Identifier(c) if ctx.is_narrowed(*c));
5316            let value_str = if narrowed {
5317                format!("{{ let __nv: i64 = {}; __nv as i32 }}", value_str)
5318            } else {
5319                value_str
5320            };
5321            // BCE: when the oracle proves the store index in range, emit an
5322            // unchecked store (no bounds branch) with a `debug_assert!` net.
5323            // Soundness: the kernel-LIA proof + the function's entry
5324            // precondition guard. `LOGOS_ORACLE_UNCHECKED=0` forces checked.
5325            let store_unchecked = crate::optimize::active_config()
5326                .is_on(crate::optimization::Opt::Unchecked)
5327                && ctx
5328                    .oracle()
5329                    .map_or(false, |o| o.index_provably_in_bounds(collection, index));
5330            if store_unchecked {
5331                crate::optimize::mark_fired(crate::optimization::Opt::Unchecked);
5332                let i0 = match &zb_index {
5333                    Some(s) => s.clone(),
5334                    None => simplify_1based_index(index, interner, false, ctx.get_variable_types()),
5335                };
5336                let offset = store_offset(index, zb_index.as_deref(), interner, ctx);
5337                writeln!(output, "{}debug_assert!(({}) >= 0 && ({}) < ({}.len() as i64), \"LOGOS oracle BCE: store out of range\");", indent_str, i0, i0, coll_str).unwrap();
5338                // Bind the value to a temp first: it may itself be a proven
5339                // `get_unchecked` read of the same slice (the partition swap),
5340                // so evaluating it before the `&mut` access avoids both a
5341                // nested `unsafe` block and an aliasing borrow.
5342                writeln!(output, "{}let __set_val = {};", indent_str, value_str).unwrap();
5343                writeln!(
5344                    output,
5345                    "{}unsafe {{ *{}.get_unchecked_mut({}) = __set_val; }}",
5346                    indent_str, coll_str, offset
5347                )
5348                .unwrap();
5349            } else if super::expr::range_proves_index(collection, index) {
5350                // A store the range oracle proves in range is a plain indexed store, whose own check never fires.
5351                let offset = store_offset(index, zb_index.as_deref(), interner, ctx);
5352                writeln!(
5353                    output,
5354                    "{}{}[{}] = {};",
5355                    indent_str, coll_str, offset, value_str
5356                )
5357                .unwrap();
5358            } else {
5359                let at = super::peephole::logos_index(index, interner, ctx.get_variable_types());
5360                writeln!(
5361                    output,
5362                    "{}*{}.{}({}) = {};",
5363                    indent_str,
5364                    coll_str,
5365                    super::expr::item_accessor(index, ctx.oracle(), true),
5366                    at,
5367                    value_str
5368                )
5369                .unwrap();
5370            }
5371        }
5372        Some(t)
5373            if t.starts_with("std::collections::HashMap")
5374                || t.starts_with("HashMap")
5375                || t.starts_with("rustc_hash::FxHashMap")
5376                || t.starts_with("FxHashMap") =>
5377        {
5378            let index_str = codegen_expr_with_async(
5379                index,
5380                interner,
5381                synced_vars,
5382                async_functions,
5383                ctx.get_variable_types(),
5384            );
5385            writeln!(
5386                output,
5387                "{}{}.insert({}, {});",
5388                indent_str, coll_str, index_str, value_str
5389            )
5390            .unwrap();
5391        }
5392        _ => {
5393            let index_str = codegen_expr_with_async(
5394                index,
5395                interner,
5396                synced_vars,
5397                async_functions,
5398                ctx.get_variable_types(),
5399            );
5400            // Fallback: polymorphic indexing via trait.
5401            // If the value expression reads ANY collection, bind it to a
5402            // temp first: that collection may alias the one being written
5403            // (reference semantics), and a live borrow across the mutable
5404            // access would conflict.
5405            let needs_tmp = expr_reads_any_collection(value);
5406            if needs_tmp {
5407                writeln!(output, "{}let __set_tmp = {};", indent_str, value_str).unwrap();
5408                writeln!(
5409                    output,
5410                    "{}LogosIndexMut::logos_set(&mut {}, {}, __set_tmp);",
5411                    indent_str, coll_str, index_str
5412                )
5413                .unwrap();
5414            } else {
5415                writeln!(
5416                    output,
5417                    "{}LogosIndexMut::logos_set(&mut {}, {}, {});",
5418                    indent_str, coll_str, index_str, value_str
5419                )
5420                .unwrap();
5421            }
5422        }
5423    }
5424    output
5425}
5426
5427/// Whether evaluating `writer` can change what `reader` reads: it writes a name `reader` reads (a binding it lends,
5428/// a global a call it makes reaches), or does what the emitter cannot see into.
5429fn interferes(writer: &Expr, reader: &Expr) -> bool {
5430    let writes = crate::optimize::WriteSet::of_expr(writer);
5431    writes.is_opaque() || crate::optimize::Mentions::of_expr(reader).symbols().any(|s| writes.may_write(s))
5432}
5433
5434/// Whether the operands of one statement must be taken one at a time, in order: one of them can change what another
5435/// reads.
5436fn ordered(operands: &[&Expr]) -> bool {
5437    operands.iter().enumerate().any(|(i, a)| operands.iter().enumerate().any(|(j, b)| i != j && interferes(a, b)))
5438}
5439
5440/// The `Set` arm of [`codegen_stmt`], in a frame of its own — the second-widest arm, and like
5441/// [`codegen_let_stmt`] never on the recursive path. See that function for why the widest arms are
5442/// the ones that must not share the walker's frame.
5443#[inline(never)]
5444#[allow(clippy::too_many_arguments)]
5445/// Collect the leaves of a left-leaning string concatenation (`X + a + b`) into `out`,
5446/// left to right. Only `Concat`/`Add` binary nodes are split; everything else is a leaf.
5447fn collect_concat_leaves<'a>(e: &'a Expr<'a>, out: &mut Vec<&'a Expr<'a>>) {
5448    match e {
5449        Expr::BinaryOp {
5450            op: BinaryOpKind::Concat | BinaryOpKind::Add,
5451            left,
5452            right,
5453        } => {
5454            collect_concat_leaves(left, out);
5455            out.push(right);
5456        }
5457        _ => out.push(e),
5458    }
5459}
5460
5461/// A concat operand PROVABLY safe to feed `push_str` — i.e. string-typed. `String + <number>`
5462/// is legal LOGOS (it stringifies the number), so a leaf whose type we cannot prove to be a
5463/// string must be DECLINED: assuming "string" here emitted `push_str(&i64)` (ill-typed Rust that
5464/// fails to compile). Declining just falls back to the correct `format!` path for that concat.
5465/// Recognised as string: a Text literal, a variable in the string set or of `String`/`&str`
5466/// type, and `item i of xs` where `xs`'s element type is a string. Every other shape (a number
5467/// literal, a call, a field, an index into a non-string seq) is rejected.
5468fn concat_leaf_is_string(e: &Expr, ctx: &RefinementContext) -> bool {
5469    match e {
5470        Expr::Literal(Literal::Text(_)) => true,
5471        Expr::Identifier(s) => {
5472            ctx.get_string_vars().contains(s)
5473                || matches!(
5474                    ctx.get_variable_types().get(s).map(String::as_str),
5475                    Some("String") | Some("&str")
5476                )
5477        }
5478        Expr::Index { collection, .. } => matches!(
5479            crate::codegen::expr::seq_element_rust_type(collection, ctx.get_variable_types()),
5480            Some("String") | Some("&str")
5481        ),
5482        _ => false,
5483    }
5484}
5485
5486/// `Set X to X combined with Y...` where X is a mutable owned `String` and no appended operand
5487/// mentions X → append each operand in place via `push_str` (amortized O(1) growth) instead of
5488/// `X = format!(...)` — which reallocates and copies the whole accumulator every call, making
5489/// `repeatText` and any concat-accumulator loop O(N^2). Shape-based (`Opt::StringAccumReuse`).
5490fn try_string_accum_push_str<'a>(
5491    target: &Symbol,
5492    value: &'a Expr<'a>,
5493    target_name: &str,
5494    interner: &Interner,
5495    ctx: &RefinementContext<'a>,
5496    synced_vars: &mut HashSet<Symbol>,
5497    async_functions: &HashSet<Symbol>,
5498    indent_str: &str,
5499) -> Option<String> {
5500    // Target must be a mutable owned String (push_str valid, in-place mutation sound).
5501    if ctx.get_variable_types().get(target).map(String::as_str) != Some("String") {
5502        return None;
5503    }
5504    // Value must be a concat whose LEFTMOST leaf is the target: `X + a + b`.
5505    let mut leaves: Vec<&Expr> = Vec::new();
5506    collect_concat_leaves(value, &mut leaves);
5507    if leaves.len() < 2 {
5508        return None;
5509    }
5510    match leaves[0] {
5511        Expr::Identifier(s) if *s == *target => {}
5512        _ => return None,
5513    }
5514    // Each appended leaf must be string-typed and must NOT mention the target (a self-append
5515    // like `X + X` aliases the `&mut` borrow → E0502; only the leftmost occurrence accumulates).
5516    let vt = ctx.get_variable_types();
5517    for leaf in &leaves[1..] {
5518        if !concat_leaf_is_string(leaf, ctx) {
5519            return None;
5520        }
5521        let mut syms: Vec<Symbol> = Vec::new();
5522        collect_expr_symbols(leaf, &mut syms);
5523        if syms.contains(target) {
5524            return None;
5525        }
5526    }
5527    let mut code = String::new();
5528    for leaf in &leaves[1..] {
5529        push_concat_leaf(
5530            &mut code,
5531            target_name,
5532            leaf,
5533            interner,
5534            synced_vars,
5535            async_functions,
5536            vt,
5537            indent_str,
5538        );
5539    }
5540    Some(code)
5541}
5542
5543/// Append one string-valued concat leaf to the `String` named `target_name`, in place: a text literal as a
5544/// `push_str` of its escaped bytes, a one-character text narrowed to a byte (`__single_char_u8`) as a character —
5545/// its value is a `u8`, which `push_str` does not take — and any other string-valued expression as a `push_str` of
5546/// a borrow. The one append emitter of the in-place concat passes ([`try_string_accum_push_str`],
5547/// [`try_string_concat_let`]).
5548fn push_concat_leaf<'a>(
5549    code: &mut String,
5550    target_name: &str,
5551    leaf: &Expr<'a>,
5552    interner: &Interner,
5553    synced_vars: &mut HashSet<Symbol>,
5554    async_functions: &HashSet<Symbol>,
5555    vt: &HashMap<Symbol, String>,
5556    indent_str: &str,
5557) {
5558    match leaf {
5559        Expr::Literal(Literal::Text(sym)) => {
5560            writeln!(
5561                code,
5562                "{}{}.push_str(\"{}\");",
5563                indent_str,
5564                target_name,
5565                rust_string_escape(interner.resolve(*sym))
5566            )
5567            .unwrap();
5568        }
5569        Expr::Identifier(sym) if vt.get(sym).map(String::as_str) == Some("__single_char_u8") => {
5570            let ch = codegen_expr_with_async(leaf, interner, synced_vars, async_functions, vt);
5571            writeln!(code, "{}{}.push({} as char);", indent_str, target_name, ch).unwrap();
5572        }
5573        _ => {
5574            let s = codegen_expr_with_async(leaf, interner, synced_vars, async_functions, vt);
5575            writeln!(code, "{}{}.push_str(&({}));", indent_str, target_name, s).unwrap();
5576        }
5577    }
5578}
5579
5580/// `Let X be A + B...` where A (leftmost leaf) is a fresh OWNED `String` — a call whose return type
5581/// is `String`, i.e. a movable temporary with no aliasing — reuses A's buffer: `let mut X = A;
5582/// X.push_str(&B)...` instead of `X = format!("{}{}", A, B)` (a fresh alloc + a copy of EVERY operand
5583/// including A). The `Let`-form twin of [`try_string_accum_push_str`]. A bare identifier / `&str` /
5584/// literal is NOT taken as A (moving a local risks a later use; a `&str` is not owned). Shape-based
5585/// (`Opt::StringConcatReuse`) — any user `Let s be build(..) + tail` benefits identically.
5586fn try_string_concat_let<'a>(
5587    var: &Symbol,
5588    value: &'a Expr<'a>,
5589    var_name: &str,
5590    interner: &Interner,
5591    ctx: &RefinementContext<'a>,
5592    synced_vars: &mut HashSet<Symbol>,
5593    async_functions: &HashSet<Symbol>,
5594    indent_str: &str,
5595) -> Option<String> {
5596    let mut leaves: Vec<&Expr> = Vec::new();
5597    collect_concat_leaves(value, &mut leaves);
5598    if leaves.len() < 2 {
5599        return None;
5600    }
5601    // A (leftmost) must be a fresh OWNED String: a call returning `String`.
5602    let a_owned_string = match leaves[0] {
5603        Expr::Call { function, .. } => {
5604            ctx.get_fn_return(function).map(String::as_str) == Some("String")
5605        }
5606        _ => false,
5607    };
5608    if !a_owned_string {
5609        return None;
5610    }
5611    // Every appended leaf must be push_str-able (string-typed) and must not mention X (X is new, so
5612    // this holds trivially, but guard against a self-referential concat all the same).
5613    for leaf in &leaves[1..] {
5614        if !concat_leaf_is_string(leaf, ctx) {
5615            return None;
5616        }
5617        let mut syms: Vec<Symbol> = Vec::new();
5618        collect_expr_symbols(leaf, &mut syms);
5619        if syms.contains(var) {
5620            return None;
5621        }
5622    }
5623    let vt = ctx.get_variable_types();
5624    let a_code = codegen_expr_with_async(leaves[0], interner, synced_vars, async_functions, vt);
5625    let mut code = format!("{}let mut {} = {};\n", indent_str, var_name, a_code);
5626    for leaf in &leaves[1..] {
5627        push_concat_leaf(
5628            &mut code,
5629            var_name,
5630            leaf,
5631            interner,
5632            synced_vars,
5633            async_functions,
5634            vt,
5635            indent_str,
5636        );
5637    }
5638    Some(code)
5639}
5640
5641fn codegen_set_stmt<'a>(
5642    mut output: String,
5643    target: &Symbol,
5644    value: &&'a Expr<'a>,
5645    interner: &Interner,
5646    ctx: &mut RefinementContext<'a>,
5647    synced_vars: &mut HashSet<Symbol>,
5648    async_functions: &HashSet<Symbol>,
5649    boxed_fields: &HashSet<(String, String, String)>,
5650    registry: &TypeRegistry,
5651    indent_str: &str,
5652    names: &RustNames,
5653    live_vars_after: Option<HashSet<Symbol>>,
5654) -> String {
5655    // A `mutable` parameter lent as `&mut` is set through the reference: the caller's value.
5656    let target_name = if super::expr::lent_in_place(*target, ctx.get_variable_types()) {
5657        format!("(*{})", names.ident(*target))
5658    } else {
5659        names.ident(*target)
5660    };
5661
5662    // A `mutable` list or map parameter lent by sharing is the caller's own buffer: setting it replaces what that
5663    // buffer holds. The new value is taken first, so it may read the parameter.
5664    if super::expr::lent_by_sharing(*target, ctx.get_variable_types()) {
5665        let held = ctx.get_variable_types().get(target).cloned().unwrap_or_default();
5666        let value_str = codegen_expr_with_async(value, interner, synced_vars, async_functions, ctx.get_variable_types());
5667        let contents = if held.starts_with("LogosSeq") { "to_vec()" } else { "borrow().clone()" };
5668        writeln!(
5669            output,
5670            "{}{{ let __replacement = {}; let __contents = __replacement.{}; *{}.borrow_mut() = __contents; }}",
5671            indent_str, value_str, contents, target_name
5672        )
5673        .unwrap();
5674        return output;
5675    }
5676
5677    // A binding that holds a value-or-nothing is set to `nothing`, to another whole, or to a value present.
5678    if let Some(held) = ctx.get_variable_types().get(target).cloned() {
5679        let ecx = operand_ctx(interner, ctx, synced_vars, async_functions, boxed_fields, registry);
5680        if let Some(code) = super::absent::stored(value, &held, &ecx) {
5681            writeln!(output, "{}{} = {};", indent_str, target_name, code).unwrap();
5682            return output;
5683        }
5684    }
5685
5686    if ctx
5687        .get_variable_types()
5688        .get(target)
5689        .is_some_and(|t| t == super::tower::VALUE)
5690    {
5691        let code = super::tower::statement_value(
5692            value,
5693            interner,
5694            synced_vars,
5695            async_functions,
5696            boxed_fields,
5697            registry,
5698            ctx.get_variable_types(),
5699        );
5700        writeln!(output, "{}{} = {};", indent_str, target_name, code).unwrap();
5701        return output;
5702    }
5703
5704    // A binding that holds rationals holds every integer it is set to as the rational it equals.
5705    if let Some(held) = ctx
5706        .get_variable_types()
5707        .get(target)
5708        .filter(|t| t.contains(super::rational::RATIONAL))
5709        .cloned()
5710    {
5711        if let Some(code) = rational_value(
5712            value,
5713            &held,
5714            interner,
5715            ctx,
5716            synced_vars,
5717            async_functions,
5718            boxed_fields,
5719            registry,
5720        ) {
5721            writeln!(output, "{}{} = {};", indent_str, target_name, code).unwrap();
5722            return output;
5723        }
5724    }
5725
5726    // Opt::WideAccumulator: `Set X to X + k` where X is an i128-widened counting accumulator — emit a
5727    // plain i128 add (no checked-add branch), so the count auto-vectorizes. Byte-identical: X ≤ trip ≤
5728    // i64::MAX, so the value is exact.
5729    if crate::optimize::active_config().is_on(crate::optimization::Opt::WideAccumulator)
5730        && super::expr::is_wide_acc(*target)
5731    {
5732        let val: &Expr = value;
5733        if let Expr::BinaryOp {
5734            op: BinaryOpKind::Add,
5735            left,
5736            right,
5737        } = val
5738        {
5739            if matches!(left, Expr::Identifier(l) if *l == *target) {
5740                if let Expr::Literal(Literal::Number(k)) = right {
5741                    crate::optimize::mark_fired(crate::optimization::Opt::WideAccumulator);
5742                    writeln!(
5743                        output,
5744                        "{}{} = {} + {}i128;",
5745                        indent_str, target_name, target_name, k
5746                    )
5747                    .unwrap();
5748                    return output;
5749                }
5750            }
5751        }
5752    }
5753
5754    // A self-assignment `Set X to X` is a semantic no-op on every tier (the
5755    // binding rebinds to itself; value semantics make it observably nothing).
5756    // Emitting `x = x;` is not only pointless but *invalid* Rust when X is an
5757    // immutable binding — e.g. a `for`-loop variable — so elide it entirely.
5758    if let Expr::Identifier(sym) = value {
5759        if *sym == *target {
5760            return output;
5761        }
5762    }
5763
5764    // String accumulator reuse: `Set X to X combined with Y...` — X a mutable owned String,
5765    // no appended operand mentions X — mutates X in place via `push_str` (amortized O(1) growth)
5766    // instead of `X = format!("{}{}", X, Y)` (a full realloc+copy each call → O(N^2) accumulator,
5767    // the repeatText cost). Yields to the bignum and cursor-indexed-buffer specializations below.
5768    if crate::optimize::active_config().is_on(crate::optimization::Opt::StringAccumReuse)
5769        && !ctx.is_bigint_var(*target)
5770        && ctx.indexed_string_build(*target).is_none()
5771    {
5772        if let Some(code) = try_string_accum_push_str(
5773            target,
5774            *value,
5775            &target_name,
5776            interner,
5777            ctx,
5778            synced_vars,
5779            async_functions,
5780            indent_str,
5781        ) {
5782            crate::optimize::mark_fired(crate::optimization::Opt::StringAccumReuse);
5783            output.push_str(&code);
5784            return output;
5785        }
5786    }
5787
5788    // Overflow-promoting Int target: assign an un-narrowed `LogosInt` (`.into()` is
5789    // identity when the RHS already is one, and promotes a plain `i64` otherwise), so a
5790    // running product/sum that exceeds i64 promotes to BigInt instead of panicking. A
5791    // bigint target is always a scalar integer, so none of the string/char/collection
5792    // special cases below apply.
5793    if ctx.is_bigint_var(*target) {
5794        // In-place scalar multiply. `Set acc to acc * <i64>` (or `<i64> * acc`) — a promoted
5795        // `Int` accumulator, dead the instant it is reassigned, times a compile-time-known
5796        // machine integer (a non-bignum variable or a numeric literal) — mutates `acc`'s heap
5797        // magnitude IN PLACE via `mul_assign_i64`, reusing the buffer instead of allocating a
5798        // fresh product every iteration (the factorial hot loop). Byte-identical value; the
5799        // accumulator must appear EXACTLY once (a true dead last-use) so nothing else reads the
5800        // pre-mutation value. A Big × Big multiply (`acc * acc`) has no scalar form and falls
5801        // through to the by-ref path below.
5802        if let Expr::BinaryOp {
5803            op: BinaryOpKind::Multiply,
5804            left,
5805            right,
5806        } = value
5807        {
5808            if crate::optimize::active_config().is_on(crate::optimization::Opt::BignumInPlace) {
5809                let left_is_acc = matches!(left, Expr::Identifier(s) if *s == *target);
5810                let right_is_acc = matches!(right, Expr::Identifier(s) if *s == *target);
5811                let scalar = match (left_is_acc, right_is_acc) {
5812                    (true, false) => Some(right),
5813                    (false, true) => Some(left),
5814                    _ => None,
5815                };
5816                if let Some(scalar) = scalar {
5817                    let scalar_str = match scalar {
5818                        Expr::Identifier(s) if !ctx.is_bigint_var(*s) => Some(names.ident(*s)),
5819                        Expr::Literal(Literal::Number(n)) => Some(format!("{}i64", n)),
5820                        _ => None,
5821                    };
5822                    if let Some(scalar_str) = scalar_str {
5823                        if count_target_reads(value, *target) == 1 {
5824                            crate::optimize::mark_fired(crate::optimization::Opt::BignumInPlace);
5825                            writeln!(
5826                                output,
5827                                "{}{}.mul_assign_i64({});",
5828                                indent_str, target_name, scalar_str
5829                            )
5830                            .unwrap();
5831                            if let Some((bound_var, predicate)) = ctx.get_constraint(*target) {
5832                                emit_refinement_check(
5833                                    &target_name,
5834                                    bound_var,
5835                                    predicate,
5836                                    interner,
5837                                    &indent_str,
5838                                    &mut output,
5839                                );
5840                            }
5841                            return output;
5842                        }
5843                    }
5844                }
5845            }
5846        }
5847        // The accumulator is dead the instant this statement reassigns it, so if
5848        // it appears exactly once in the RHS its read may MOVE instead of clone.
5849        let movable = count_target_reads(value, *target) == 1;
5850        if movable {
5851            set_movable_last_use(Some(*target));
5852        }
5853        let raw = codegen_expr_boxed_with_types_oracle_tolerant(
5854            value,
5855            interner,
5856            synced_vars,
5857            boxed_fields,
5858            registry,
5859            async_functions,
5860            ctx.get_string_vars(),
5861            ctx.get_variable_types(),
5862            ctx.get_fast_div(),
5863            ctx.oracle(),
5864        );
5865        if movable {
5866            set_movable_last_use(None);
5867        }
5868        writeln!(
5869            output,
5870            "{}{} = logicaffeine_data::LogosInt::from({});",
5871            indent_str, target_name, raw
5872        )
5873        .unwrap();
5874        if let Some((bound_var, predicate)) = ctx.get_constraint(*target) {
5875            emit_refinement_check(
5876                &target_name,
5877                bound_var,
5878                predicate,
5879                interner,
5880                &indent_str,
5881                &mut output,
5882            );
5883        }
5884        return output;
5885    }
5886
5887    // Cursor-indexed string build: `Set text to text + X` writes X at the
5888    // cursor in the pre-sized buffer (no push). The paired `Set c to c +
5889    // len(X)` that follows advances the cursor as usual. See
5890    // peephole::try_emit_indexed_string_build.
5891    if let Some(cursor) = ctx.indexed_string_build(*target).map(|c| c.to_string()) {
5892        if let Expr::BinaryOp {
5893            op: BinaryOpKind::Add,
5894            right,
5895            ..
5896        } = value
5897        {
5898            match right {
5899                Expr::Literal(Literal::Text(sym)) => {
5900                    let lit = interner.resolve(*sym);
5901                    let bytes: Vec<String> = lit.bytes().map(|b| format!("{}u8", b)).collect();
5902                    writeln!(
5903                        output,
5904                        "{ind}unsafe {{ std::ptr::copy_nonoverlapping([{b}].as_ptr(), {t}.as_mut_vec().as_mut_ptr().add(({c}) as usize), {k}); }}",
5905                        ind = indent_str, t = target_name, c = cursor, k = lit.len(), b = bytes.join(", ")
5906                    )
5907                    .unwrap();
5908                    return output;
5909                }
5910                Expr::Identifier(v)
5911                    if ctx.get_variable_types().get(v).map(String::as_str)
5912                        == Some("__single_char_u8") =>
5913                {
5914                    let vn = names.ident(*v);
5915                    writeln!(
5916                        output,
5917                        "{ind}unsafe {{ *{t}.as_mut_vec().as_mut_ptr().add(({c}) as usize) = {vn}; }}",
5918                        ind = indent_str, t = target_name, c = cursor
5919                    )
5920                    .unwrap();
5921                    return output;
5922                }
5923                _ => {}
5924            }
5925        }
5926    }
5927
5928    // O2 de-Rc: reassigning a de-Rc'd Seq to a FRESH allocation keeps
5929    // it a plain `Vec<T>` (`xs = Vec::new()`), not `Seq::default()`.
5930    if ctx.is_de_rc(*target) {
5931        if let Some((_, init)) = derc_vec_decl(
5932            value,
5933            interner,
5934            synced_vars,
5935            boxed_fields,
5936            registry,
5937            async_functions,
5938            ctx,
5939        ) {
5940            writeln!(output, "{}{} = {};", indent_str, target_name, init).unwrap();
5941            return output;
5942        }
5943    }
5944
5945    // OPT: Single-char u8 variable → emit byte literal assignment.
5946    let is_target_single_char_u8 = ctx
5947        .get_variable_types()
5948        .get(target)
5949        .map_or(false, |t| t == "__single_char_u8");
5950    if is_target_single_char_u8 {
5951        if let Expr::Literal(Literal::Text(sym)) = value {
5952            let text = interner.resolve(*sym);
5953            if text.len() == 1 {
5954                let ch = text.as_bytes()[0];
5955                writeln!(output, "{}{} = b'{}';", indent_str, target_name, ch as char).unwrap();
5956                return output;
5957            }
5958        }
5959    }
5960
5961    let string_vars = ctx.get_string_vars();
5962    let var_types = ctx.get_variable_types();
5963
5964    // Optimization: detect self-append pattern (result = result + x + y)
5965    // and emit write!(result, "{}{}", x, y) instead of result = format!(...).
5966    // This is O(n) amortized (in-place append) vs O(n²) (full copy each iteration).
5967    let used_write = if ctx.is_string_var(*target)
5968        && is_definitely_string_expr_with_vars(value, string_vars)
5969    {
5970        let mut operands = Vec::new();
5971        collect_string_concat_operands(value, string_vars, &mut operands);
5972
5973        // Need at least 2 operands, leftmost must be the target variable
5974        if operands.len() >= 2 && matches!(operands[0], Expr::Identifier(sym) if *sym == *target) {
5975            // Check no other operand references target (would cause borrow conflict)
5976            let tail = &operands[1..];
5977            let mut tail_ids = HashSet::new();
5978            for op in tail {
5979                collect_expr_identifiers(op, &mut tail_ids);
5980            }
5981
5982            if !tail_ids.contains(target) {
5983                if tail.len() == 1 {
5984                    // Single operand: use push/push_str for zero-format-overhead append
5985                    let operand = tail[0];
5986                    if let Expr::Literal(Literal::Text(sym)) = operand {
5987                        let text = interner.resolve(*sym);
5988                        if text.len() == 1 {
5989                            let ch = text.chars().next().unwrap();
5990                            writeln!(
5991                                output,
5992                                "{}{}.push('{}');",
5993                                indent_str,
5994                                target_name,
5995                                rust_char_escape(ch)
5996                            )
5997                            .unwrap();
5998                        } else {
5999                            writeln!(
6000                                output,
6001                                "{}{}.push_str(\"{}\");",
6002                                indent_str,
6003                                target_name,
6004                                rust_string_escape(text)
6005                            )
6006                            .unwrap();
6007                        }
6008                    } else if let Expr::Identifier(sym) = operand {
6009                        if var_types
6010                            .get(sym)
6011                            .map_or(false, |t| t == "__single_char_u8")
6012                        {
6013                            // OPT: u8 single-char var → push(ch as char)
6014                            let val_str = codegen_expr_boxed_with_types(
6015                                operand,
6016                                interner,
6017                                synced_vars,
6018                                boxed_fields,
6019                                registry,
6020                                async_functions,
6021                                string_vars,
6022                                var_types,
6023                                ctx.get_fast_div(),
6024                            );
6025                            writeln!(
6026                                output,
6027                                "{}{}.push({} as char);",
6028                                indent_str, target_name, val_str
6029                            )
6030                            .unwrap();
6031                        } else if string_vars.contains(sym) {
6032                            let val_str = codegen_expr_boxed_with_types(
6033                                operand,
6034                                interner,
6035                                synced_vars,
6036                                boxed_fields,
6037                                registry,
6038                                async_functions,
6039                                string_vars,
6040                                var_types,
6041                                ctx.get_fast_div(),
6042                            );
6043                            writeln!(
6044                                output,
6045                                "{}{}.push_str(&{});",
6046                                indent_str, target_name, val_str
6047                            )
6048                            .unwrap();
6049                        } else {
6050                            // Non-string single operand: use write!
6051                            let val_str = codegen_expr_boxed_with_types(
6052                                operand,
6053                                interner,
6054                                synced_vars,
6055                                boxed_fields,
6056                                registry,
6057                                async_functions,
6058                                string_vars,
6059                                var_types,
6060                                ctx.get_fast_div(),
6061                            );
6062                            writeln!(
6063                                output,
6064                                "{}write!({}, \"{{}}\", {}).unwrap();",
6065                                indent_str, target_name, val_str
6066                            )
6067                            .unwrap();
6068                        }
6069                    } else {
6070                        // Non-string single operand: use write!
6071                        let val_str = codegen_expr_boxed_with_types(
6072                            operand,
6073                            interner,
6074                            synced_vars,
6075                            boxed_fields,
6076                            registry,
6077                            async_functions,
6078                            string_vars,
6079                            var_types,
6080                            ctx.get_fast_div(),
6081                        );
6082                        writeln!(
6083                            output,
6084                            "{}write!({}, \"{{}}\", {}).unwrap();",
6085                            indent_str, target_name, val_str
6086                        )
6087                        .unwrap();
6088                    }
6089                } else if tail.iter().any(|op| {
6090                    crate::codegen::types::infer_numeric_type(op, interner, var_types) == "i64"
6091                }) {
6092                    // Multiple operands, at least one integer: append each with the
6093                    // fastest path for its type — `.push`/`.push_str` for char/string
6094                    // literals and string vars, `.push_i64` (itoa fast path, no
6095                    // `fmt::Display` vtable) for integers, `write!` only as the
6096                    // fallback. Sequential appends produce the identical string a
6097                    // single `write!("{}{}…")` would, without routing each integer
6098                    // through the formatter machinery.
6099                    for op in tail {
6100                        if let Expr::Literal(Literal::Text(sym)) = op {
6101                            let text = interner.resolve(*sym);
6102                            if text.chars().count() == 1 {
6103                                writeln!(
6104                                    output,
6105                                    "{}{}.push('{}');",
6106                                    indent_str,
6107                                    target_name,
6108                                    rust_char_escape(text.chars().next().unwrap())
6109                                )
6110                                .unwrap();
6111                            } else {
6112                                writeln!(
6113                                    output,
6114                                    "{}{}.push_str(\"{}\");",
6115                                    indent_str,
6116                                    target_name,
6117                                    rust_string_escape(text)
6118                                )
6119                                .unwrap();
6120                            }
6121                            continue;
6122                        }
6123                        let val_str = codegen_expr_boxed_with_types(
6124                            op,
6125                            interner,
6126                            synced_vars,
6127                            boxed_fields,
6128                            registry,
6129                            async_functions,
6130                            string_vars,
6131                            var_types,
6132                            ctx.get_fast_div(),
6133                        );
6134                        if let Expr::Identifier(sym) = op {
6135                            if string_vars.contains(sym) {
6136                                writeln!(
6137                                    output,
6138                                    "{}{}.push_str(&{});",
6139                                    indent_str, target_name, val_str
6140                                )
6141                                .unwrap();
6142                                continue;
6143                            }
6144                            if var_types
6145                                .get(sym)
6146                                .map_or(false, |t| t == "__single_char_u8")
6147                            {
6148                                writeln!(
6149                                    output,
6150                                    "{}{}.push({} as char);",
6151                                    indent_str, target_name, val_str
6152                                )
6153                                .unwrap();
6154                                continue;
6155                            }
6156                        }
6157                        if crate::codegen::types::infer_numeric_type(op, interner, var_types)
6158                            == "i64"
6159                        {
6160                            writeln!(
6161                                output,
6162                                "{}{}.push_i64({});",
6163                                indent_str, target_name, val_str
6164                            )
6165                            .unwrap();
6166                        } else {
6167                            writeln!(
6168                                output,
6169                                "{}write!({}, \"{{}}\", {}).unwrap();",
6170                                indent_str, target_name, val_str
6171                            )
6172                            .unwrap();
6173                        }
6174                    }
6175                } else {
6176                    // Multiple operands, all string/char: no integer to accelerate,
6177                    // so keep the single `write!` — the itoa fast path would gain
6178                    // nothing here (locked by e2e_opt_push_str_multi_operand_keeps_write).
6179                    // `write!`'s `{}` formats through a shared `&` reference, so feed it
6180                    // borrowed operands: string literals as `&str` (`" "`, not
6181                    // `String::from(" ")`), string vars by `&`-borrow — no throwaway
6182                    // heap `String` per append.
6183                    let mut fmt = String::new();
6184                    let mut args = Vec::new();
6185                    for op in tail {
6186                        fmt.push_str("{}");
6187                        if let Expr::Literal(Literal::Text(sym)) = op {
6188                            args.push(format!(
6189                                "\"{}\"",
6190                                rust_string_escape(interner.resolve(*sym))
6191                            ));
6192                            continue;
6193                        }
6194                        if let Expr::Identifier(sym) = op {
6195                            if string_vars.contains(sym) {
6196                                args.push(format!("&{}", names.ident(*sym)));
6197                                continue;
6198                            }
6199                        }
6200                        args.push(codegen_expr_boxed_with_types(
6201                            op,
6202                            interner,
6203                            synced_vars,
6204                            boxed_fields,
6205                            registry,
6206                            async_functions,
6207                            string_vars,
6208                            var_types,
6209                            ctx.get_fast_div(),
6210                        ));
6211                    }
6212                    writeln!(
6213                        output,
6214                        "{}write!({}, \"{}\", {}).unwrap();",
6215                        indent_str,
6216                        target_name,
6217                        fmt,
6218                        args.join(", ")
6219                    )
6220                    .unwrap();
6221                }
6222                true
6223            } else {
6224                false
6225            }
6226        } else {
6227            false
6228        }
6229    } else {
6230        false
6231    };
6232
6233    if !used_write {
6234        // &mut borrow call-site transformation:
6235        // `Set x to f(x, ...)` where f has fn_mut_borrow at the target position
6236        // → `f(&mut x, ...)` (no assignment, mutation is in-place)
6237        let mut used_mut_borrow = false;
6238        if let Expr::Call { function, args } = value {
6239            let callee_mut_borrow_indices: HashSet<usize> =
6240                super::fn_role_indices(var_types.get(function), super::FnRole::MutBorrow);
6241            if !callee_mut_borrow_indices.is_empty() {
6242                // Check if target is at a mut_borrow position
6243                let target_at_mut_borrow = args.iter().enumerate().any(|(i, a)| {
6244                    callee_mut_borrow_indices.contains(&i)
6245                        && matches!(a, Expr::Identifier(sym) if *sym == *target)
6246                });
6247                if target_at_mut_borrow {
6248                    let callee_borrow_indices: HashSet<usize> =
6249                        super::fn_role_indices(var_types.get(function), super::FnRole::Borrow);
6250                    let func_name = names.ident(*function);
6251                    let args_str: Vec<String> = args
6252                        .iter()
6253                        .enumerate()
6254                        .map(|(i, a)| {
6255                            let s = codegen_expr_boxed_with_types(
6256                                a,
6257                                interner,
6258                                synced_vars,
6259                                boxed_fields,
6260                                registry,
6261                                async_functions,
6262                                string_vars,
6263                                var_types,
6264                                ctx.get_fast_div(),
6265                            );
6266                            if callee_mut_borrow_indices.contains(&i) {
6267                                // Mut borrow param: pass &mut [T] reference
6268                                if let Expr::Identifier(sym) = a {
6269                                    if let Some(ty) = var_types.get(sym) {
6270                                        let ty = ty.split("|__hl:").next().unwrap_or(ty.as_str());
6271                                        if ty.starts_with("&mut [") {
6272                                            return s; // Already &mut slice
6273                                        }
6274                                        // Phase 3b: a de-Rc'd `Vec` lends `&mut x`
6275                                        // directly — no RefCell to borrow_mut.
6276                                        if ty.starts_with("Vec<") {
6277                                            return format!("&mut {}", s);
6278                                        }
6279                                        if ty.starts_with("LogosSeq") {
6280                                            return format!("&mut *{}.borrow_mut()", s);
6281                                        }
6282                                    }
6283                                    // Unknown type — default to LogosSeq
6284                                    return format!("&mut *{}.borrow_mut()", s);
6285                                }
6286                                format!("&mut {}", s)
6287                            } else if callee_borrow_indices.contains(&i) {
6288                                if let Expr::Identifier(sym) = a {
6289                                    if let Some(ty) = var_types.get(sym) {
6290                                        let ty = ty.split("|__hl:").next().unwrap_or(ty.as_str());
6291                                        if ty.starts_with("&[") || ty.starts_with("&mut [") {
6292                                            return s;
6293                                        }
6294                                        if ty.starts_with("Vec<") {
6295                                            return format!("&{}", s);
6296                                        }
6297                                        if ty.starts_with('[') {
6298                                            // Const-table stack array [T; N] coerces to &[T].
6299                                            return format!("&{}", s);
6300                                        }
6301                                        if ty.starts_with("LogosSeq") {
6302                                            return format!("&*{}.borrow()", s);
6303                                        }
6304                                    }
6305                                    // Unknown type — default to LogosSeq
6306                                    return format!("&*{}.borrow()", s);
6307                                }
6308                                format!("&*{}.borrow()", s)
6309                            } else {
6310                                s
6311                            }
6312                        })
6313                        .collect();
6314                    // Value semantics: make each lent handle's buffer
6315                    // UNIQUE before the in-place call — an alias keeps
6316                    // the pre-call value, the callee's writes land on
6317                    // ours alone. Amortized free: a refcount-1 cow is
6318                    // a branch, only a genuinely shared buffer copies.
6319                    if crate::semantics::collections::value_semantics_enabled() {
6320                        for (i, a) in args.iter().enumerate() {
6321                            if !callee_mut_borrow_indices.contains(&i) {
6322                                continue;
6323                            }
6324                            if let Expr::Identifier(sym) = a {
6325                                let lends_refcell = match var_types.get(sym) {
6326                                    Some(t) => t
6327                                        .split("|__hl:")
6328                                        .next()
6329                                        .unwrap_or(t.as_str())
6330                                        .starts_with("LogosSeq"),
6331                                    None => true, // unknown type lowers via borrow_mut above
6332                                };
6333                                if lends_refcell {
6334                                    writeln!(output, "{}{}.cow();", indent_str, names.ident(*sym))
6335                                        .unwrap();
6336                                }
6337                            }
6338                        }
6339                    }
6340                    let await_suffix = if async_functions.contains(function) {
6341                        ".await"
6342                    } else {
6343                        ""
6344                    };
6345                    writeln!(
6346                        output,
6347                        "{}{}({}){};",
6348                        indent_str,
6349                        func_name,
6350                        args_str.join(", "),
6351                        await_suffix
6352                    )
6353                    .unwrap();
6354                    used_mut_borrow = true;
6355                }
6356            }
6357        }
6358
6359        // OPT-1B: Last-use clone elimination for `Set x to f(x, ...)`.
6360        // When the target variable appears as a direct non-borrow argument
6361        // and doesn't appear in other arg sub-expressions, skip cloning it
6362        // since the old value is immediately overwritten by the result.
6363        let value_str = if used_mut_borrow {
6364            String::new() // Already emitted above
6365        } else if let Expr::Call { function, args } = value {
6366            if crate::semantics::builtins::builtin_from_name(interner.resolve(*function)).is_some()
6367            {
6368                // A math/value builtin (`sqrt`/`abs`/`pow`/…) needs its dedicated lowering
6369                // (`(x as f64).sqrt()`, `LogosComplexF::…`, …), NOT the bare `name(args)` the
6370                // last-use-move fast path below emits — `Set x to sqrt(x)` must round-trip like
6371                // `Let`/`Return` do. Route it through the full expression codegen.
6372                codegen_expr_boxed_with_types(
6373                    value,
6374                    interner,
6375                    synced_vars,
6376                    boxed_fields,
6377                    registry,
6378                    async_functions,
6379                    string_vars,
6380                    var_types,
6381                    ctx.get_fast_div(),
6382                )
6383            } else {
6384                // The arguments as every call writes them — borrows, lends, exact promotions, from
6385                // the one emitter (`call_arguments`) — with the one thing a `Set` of a call adds:
6386                // an identifier this call is the last reader of is MOVED rather than cloned. The
6387                // target is overwritten the moment the call returns, and a name liveness says is
6388                // dead after this statement is too, as long as no other argument reads it. A target
6389                // borrowed in place is borrowed from a copy, since it is assigned while borrowed.
6390                let ecx = super::expr::ExprCtx {
6391                    boxed_fields,
6392                    registry,
6393                    async_functions,
6394                    string_vars,
6395                    variable_types: var_types,
6396                    fast_div: ctx.get_fast_div(),
6397                    ..super::expr::ExprCtx::bare(interner, synced_vars)
6398                };
6399                let mut args_str = super::expr::call_arguments(*function, args, &ecx);
6400                for (i, a) in args.iter().enumerate() {
6401                    let Expr::Identifier(sym) = a else { continue };
6402                    let read = codegen_expr_boxed_with_types(
6403                        a,
6404                        interner,
6405                        synced_vars,
6406                        boxed_fields,
6407                        registry,
6408                        async_functions,
6409                        string_vars,
6410                        var_types,
6411                        ctx.get_fast_div(),
6412                    );
6413                    let elsewhere = args.iter().enumerate().any(|(j, b)| {
6414                        j != i && {
6415                            let mut ids = HashSet::new();
6416                            collect_expr_identifiers(b, &mut ids);
6417                            ids.contains(sym)
6418                        }
6419                    });
6420                    if *sym == *target && args_str[i] == format!("&*{read}.borrow()") {
6421                        args_str[i] = format!("&*{read}.clone().borrow()");
6422                        continue;
6423                    }
6424                    let last_read = *sym == *target
6425                        || live_vars_after
6426                            .as_ref()
6427                            .is_some_and(|live| !live.contains(sym));
6428                    if last_read && !elsewhere && args_str[i] == format!("{read}.clone()") {
6429                        args_str[i] = read;
6430                    }
6431                }
6432                let func_name =
6433                    super::expr::called_function_path(*function, names.ident(*function), var_types);
6434                let await_suffix = if async_functions.contains(function) {
6435                    ".await"
6436                } else {
6437                    ""
6438                };
6439                super::expr::sequenced_call(
6440                    &func_name,
6441                    *function,
6442                    args,
6443                    args_str,
6444                    await_suffix,
6445                    var_types,
6446                )
6447            }
6448        } else {
6449            let vs = codegen_expr_boxed_with_types(
6450                value,
6451                interner,
6452                synced_vars,
6453                boxed_fields,
6454                registry,
6455                async_functions,
6456                string_vars,
6457                var_types,
6458                ctx.get_fast_div(),
6459            );
6460            stored_value(value, vs, var_types)
6461        };
6462        if !used_mut_borrow {
6463            writeln!(output, "{}{} = {};", indent_str, target_name, value_str).unwrap();
6464        }
6465    }
6466
6467    // Phase 43C: Check if this variable has a refinement constraint
6468    if let Some((bound_var, predicate)) = ctx.get_constraint(*target) {
6469        emit_refinement_check(
6470            &target_name,
6471            bound_var,
6472            predicate,
6473            interner,
6474            &indent_str,
6475            &mut output,
6476        );
6477    }
6478    output
6479}
6480
6481/// The machine word a `Let` declares when its initializer is [`type_silent_int`](super::types::type_silent_int)
6482/// and the binding is a plain `Int`: without it, a binding no use pins is an `i32` to rustc.
6483/// The emission of `value` as a value of the Rust type `held`, which holds rationals, where it is not one already
6484/// ([`super::rational::value_as`]).
6485#[allow(clippy::too_many_arguments)]
6486fn rational_value(
6487    value: &Expr,
6488    held: &str,
6489    interner: &Interner,
6490    ctx: &RefinementContext,
6491    synced_vars: &HashSet<Symbol>,
6492    async_functions: &HashSet<Symbol>,
6493    boxed_fields: &HashSet<(String, String, String)>,
6494    registry: &TypeRegistry,
6495) -> Option<String> {
6496    let ecx = super::expr::ExprCtx {
6497        boxed_fields,
6498        registry,
6499        async_functions,
6500        string_vars: ctx.get_string_vars(),
6501        variable_types: ctx.get_variable_types(),
6502        fast_div: ctx.get_fast_div(),
6503        oracle: ctx.oracle(),
6504        ..super::expr::ExprCtx::bare(interner, synced_vars)
6505    };
6506    super::rational::value_as(value, &super::rational::named(held), &ecx)
6507}
6508
6509/// The context a statement's own expressions are emitted in.
6510fn operand_ctx<'c>(
6511    interner: &'c Interner,
6512    ctx: &'c RefinementContext,
6513    synced_vars: &'c HashSet<Symbol>,
6514    async_functions: &'c HashSet<Symbol>,
6515    boxed_fields: &'c HashSet<(String, String, String)>,
6516    registry: &'c TypeRegistry,
6517) -> super::expr::ExprCtx<'c> {
6518    super::expr::ExprCtx {
6519        boxed_fields,
6520        registry,
6521        async_functions,
6522        string_vars: ctx.get_string_vars(),
6523        variable_types: ctx.get_variable_types(),
6524        fast_div: ctx.get_fast_div(),
6525        oracle: ctx.oracle(),
6526        ..super::expr::ExprCtx::bare(interner, synced_vars)
6527    }
6528}
6529
6530fn type_silent_let_annotation(value: &Expr, registered: Option<&String>) -> Option<String> {
6531    (super::types::type_silent_int(value).is_some() && registered.is_some_and(|t| t == "i64"))
6532        .then(|| "i64".to_string())
6533}
6534
6535/// The `Let` arm of [`codegen_stmt`], in a frame of its own.
6536///
6537/// A compile recurses once per nesting level of the program, and in a debug build every arm's
6538/// locals share the enclosing function's frame — so the widest arms set the stack cost of EVERY
6539/// level, including levels that never run them. `Let` is the widest and is never on the recursive
6540/// path; giving it its own frame keeps it out of the nesting cost entirely.
6541#[inline(never)]
6542#[allow(clippy::too_many_arguments)]
6543fn codegen_let_stmt<'a>(
6544    mut output: String,
6545    stmt: &Stmt<'a>,
6546    var: &Symbol,
6547    ty: &Option<&'a TypeExpr<'a>>,
6548    value: &&'a Expr<'a>,
6549    mutable: &bool,
6550    interner: &Interner,
6551    mutable_vars: &HashSet<Symbol>,
6552    ctx: &mut RefinementContext<'a>,
6553    synced_vars: &mut HashSet<Symbol>,
6554    async_functions: &HashSet<Symbol>,
6555    boxed_fields: &HashSet<(String, String, String)>,
6556    registry: &TypeRegistry,
6557    indent_str: &str,
6558    names: &RustNames,
6559) -> String {
6560    let var_name = names.ident(*var);
6561
6562    // A binding a stored `nothing` reaches holds a value-or-nothing from its first assignment on.
6563    let held = {
6564        let ecx = operand_ctx(interner, ctx, synced_vars, async_functions, boxed_fields, registry);
6565        super::absent::binding(stmt, *ty, value, &ecx).map(|held| {
6566            let code = super::absent::stored(value, &held, &ecx)
6567                .unwrap_or_else(|| super::absent::whole(value, &ecx));
6568            (held, code)
6569        })
6570    };
6571    if let Some((held, code)) = held {
6572        let decl_mut = if *mutable || mutable_vars.contains(var) { "mut " } else { "" };
6573        writeln!(output, "{}let {}{}: {} = {};", indent_str, decl_mut, var_name, held, code).unwrap();
6574        ctx.register_variable_type(*var, held);
6575        return output;
6576    }
6577
6578    // A binding the exact extension reaches holds the compiled exact value from its first
6579    // assignment on, so every later write and read means what the interpreter's does.
6580    if super::tower::binding(*var) {
6581        let code = super::tower::statement_value(
6582            value,
6583            interner,
6584            synced_vars,
6585            async_functions,
6586            boxed_fields,
6587            registry,
6588            ctx.get_variable_types(),
6589        );
6590        let decl_mut = if *mutable || mutable_vars.contains(var) { "mut " } else { "" };
6591        writeln!(
6592            output,
6593            "{}let {}{}: {} = {};",
6594            indent_str,
6595            decl_mut,
6596            var_name,
6597            super::tower::VALUE,
6598            code
6599        )
6600        .unwrap();
6601        ctx.register_variable_type(*var, super::tower::VALUE.to_string());
6602        return output;
6603    }
6604
6605    // Opt::WideAccumulator: `Let X be 0` where X is an i128-widened counting accumulator — declare it
6606    // `i128` (the analysis guarantees the init is the literal 0), so the loop's adds stay plain i128
6607    // (no checked-add branch → the count vectorizes). Narrowed `as i64` at the `Show` sink.
6608    if crate::optimize::active_config().is_on(crate::optimization::Opt::WideAccumulator)
6609        && super::expr::is_wide_acc(*var)
6610    {
6611        writeln!(output, "{}let mut {}: i128 = 0i128;", indent_str, var_name).unwrap();
6612        return output;
6613    }
6614
6615    // AoS interleaving: a co-indexed group member. Column 0 emits the
6616    // single fused `[[T; W]; N]` backing (reusing the first member's
6617    // name); the other columns' declarations are dropped — their storage
6618    // lives in the backing. Runs before the scalarization branch below.
6619    if matches!(value, Expr::New { .. }) {
6620        if let Some(tag) = parse_aos_tag(ctx.get_variable_types().get(var)) {
6621            if tag.col == 0 {
6622                let default = match tag.elem.as_str() {
6623                    "f64" => "0f64",
6624                    "bool" => "false",
6625                    _ => "0i64",
6626                };
6627                writeln!(
6628                    output,
6629                    "{}let mut {}: [[{}; {}]; {}] = [[{}; {}]; {}];",
6630                    indent_str,
6631                    tag.backing,
6632                    tag.elem,
6633                    tag.width,
6634                    tag.len,
6635                    default,
6636                    tag.width,
6637                    tag.len
6638                )
6639                .unwrap();
6640            }
6641            return output;
6642        }
6643    }
6644
6645    // Opt::StringConcatReuse: `Let X be A + B...` where A is a fresh owned String (a call returning
6646    // `String`) → `let mut X = A; X.push_str(&B)...`, reusing A's buffer instead of `format!` (which
6647    // allocates a new String and copies every operand). The `Let`-form twin of StringAccumReuse.
6648    if crate::optimize::active_config().is_on(crate::optimization::Opt::StringConcatReuse) {
6649        if let Some(code) = try_string_concat_let(
6650            var,
6651            *value,
6652            &var_name,
6653            interner,
6654            ctx,
6655            synced_vars,
6656            async_functions,
6657            indent_str,
6658        ) {
6659            crate::optimize::mark_fired(crate::optimization::Opt::StringConcatReuse);
6660            ctx.register_variable_type(*var, "String".to_string());
6661            output.push_str(&code);
6662            return output;
6663        }
6664    }
6665
6666    // O3: a fixed-size Seq pre-registered as `[T; N]` (scalarization)
6667    // — emit a stack array and let the init pushes fill it via indexed
6668    // writes. Must run before the `new Seq` type registration below,
6669    // which would otherwise overwrite the array type with LogosSeq.
6670    if ctx.is_scalarized_array(*var) && matches!(value, Expr::New { .. }) {
6671        if let Some(arr_ty) = ctx.get_variable_types().get(var).cloned() {
6672            let inner = arr_ty.trim_start_matches('[').trim_end_matches(']');
6673            let mut parts = inner.split("; ");
6674            let elem = parts.next().unwrap_or("i64");
6675            let n = parts.next().unwrap_or("0");
6676            let default = match elem {
6677                "f64" => "0f64",
6678                "bool" => "false",
6679                "Word8" => "word8(0)",
6680                "Word16" => "word16(0)",
6681                "Word32" => "word32(0)",
6682                "Word64" => "word64(0)",
6683                _ => "0i64",
6684            };
6685            writeln!(
6686                output,
6687                "{}let mut {}: {} = [{}; {}];",
6688                indent_str, var_name, arr_ty, default, n
6689            )
6690            .unwrap();
6691            // A loop-built return buffer (the digest) fills through a RUNTIME cursor (the pushes
6692            // live in a loop): declare it here; the `Push` handler emits `out[cursor]=v; cursor+=1`.
6693            if let Some(cursor) = ctx.loop_fill_cursor(*var).map(|s| s.to_string()) {
6694                writeln!(output, "{}let mut {}: usize = 0;", indent_str, cursor).unwrap();
6695            }
6696            ctx.init_array_fill(*var);
6697            return output;
6698        }
6699    }
6700
6701    // Affine read-only array (CSR offset array): deleted entirely. The
6702    // build push is suppressed and every `item _ of`/`length of` read
6703    // substitutes the closed form, so the declaration emits nothing. The
6704    // `__affine_array:...` type was registered in `codegen_program`.
6705    if matches!(value, Expr::New { .. }) && ctx.affine_array(*var).is_some() {
6706        return output;
6707    }
6708
6709    // Append-only worklist: a de-Rc'd Seq frontier proven bounded by a
6710    // monotone visited-set guard. Emit a PRE-SIZED buffer + a register
6711    // tail counter; the pushes lower to `q[tail]=x; tail+=1` and
6712    // `length of q` to `tail`. This is C's frontier representation.
6713    if matches!(value, Expr::New { .. }) {
6714        if let Some((cap, default, tail)) = ctx.worklist(*var).map(|w| {
6715            (
6716                w.capacity.clone(),
6717                w.elem_default.clone(),
6718                w.tail_var.clone(),
6719            )
6720        }) {
6721            writeln!(
6722                output,
6723                "{}let mut {}: Vec<i64> = vec![{}; {}];",
6724                indent_str, var_name, default, cap
6725            )
6726            .unwrap();
6727            writeln!(output, "{}let mut {}: usize = 0;", indent_str, tail).unwrap();
6728            // Encode the LOGICAL length (the tail) as a hoisted length so
6729            // `length of q` reads `tail`, not the buffer size, while every
6730            // other site strips the suffix and sees a plain `Vec<i64>`.
6731            ctx.register_variable_type(*var, format!("Vec<i64>|__hl:({} as i64)", tail));
6732            return output;
6733        }
6734    }
6735
6736    // Opt::BitPack: a local `Seq of Bool` used only through item reads and stores, pushes and its
6737    // length is held one bit per item (`codegen::bits`).
6738    if ctx.is_bitpacked(*var) {
6739        let kw = if *mutable || mutable_vars.contains(var) {
6740            "let mut"
6741        } else {
6742            "let"
6743        };
6744        let init = match ctx.get_vec_presize(*var) {
6745            Some(cap) => format!(
6746                "logicaffeine_data::LogosBits::with_capacity(({}) as usize)",
6747                cap
6748            ),
6749            None => "logicaffeine_data::LogosBits::new()".to_string(),
6750        };
6751        writeln!(
6752            output,
6753            "{}{} {}: logicaffeine_data::LogosBits = {};",
6754            indent_str, kw, var_name, init
6755        )
6756        .unwrap();
6757        ctx.register_variable_type(*var, "LogosBits".to_string());
6758        return output;
6759    }
6760
6761    // O2 de-Rc: a Seq proven to never need reference semantics is a
6762    // plain `Vec<T>` (no Rc/RefCell). Emit the owned-Vec declaration;
6763    // access sites dispatch on the `Vec<T>` type exactly as they do for
6764    // borrow-hoisted slices and materialized vecs.
6765    if ctx.is_de_rc(*var) {
6766        if let Some((vec_ty, init)) = derc_vec_decl(
6767            value,
6768            interner,
6769            synced_vars,
6770            boxed_fields,
6771            registry,
6772            async_functions,
6773            ctx,
6774        ) {
6775            let is_mut = *mutable || mutable_vars.contains(var);
6776            let kw = if is_mut { "let mut" } else { "let" };
6777            // Pre-size a push-built Vec the program later index-reads up to
6778            // a bound: reserve once instead of reallocating as it grows
6779            // (C sizes the buffer exactly). Capacity is a hint — sound.
6780            let init = match (init.as_str(), ctx.get_vec_presize(*var)) {
6781                ("Vec::new()", Some(cap)) => {
6782                    format!("Vec::with_capacity(({}) as usize)", cap)
6783                }
6784                _ => init,
6785            };
6786            // i64→i32 narrowing: a Seq of Int proven to hold only
6787            // i32-range values is `Vec<i32>` (access sites convert).
6788            let vec_ty = if ctx.is_narrowed(*var) && vec_ty == "Vec<i64>" {
6789                "Vec<i32>".to_string()
6790            } else {
6791                vec_ty
6792            };
6793            writeln!(
6794                output,
6795                "{}{} {}: {} = {};",
6796                indent_str, kw, var_name, vec_ty, init
6797            )
6798            .unwrap();
6799            for g in ctx.narrow_guards(*var).to_vec() {
6800                writeln!(
6801                    output,
6802                    "{}assert!({}, \"LOGOS i32-narrowing guard: element value must fit i32\");",
6803                    indent_str, g
6804                )
6805                .unwrap();
6806            }
6807            ctx.register_variable_type(*var, vec_ty);
6808            return output;
6809        }
6810    }
6811
6812    // Register collection type for direct indexing optimization.
6813    // Check explicit type annotation first, then infer from Expr::New.
6814    if let Some(TypeExpr::Generic { base, params }) = ty {
6815        let base_name = interner.resolve(*base);
6816        match base_name {
6817            "Seq" | "List" | "Vec" => {
6818                let rust_type = if !params.is_empty() {
6819                    format!("LogosSeq<{}>", codegen_type_expr(&params[0], interner))
6820                } else {
6821                    "LogosSeq<()>".to_string()
6822                };
6823                ctx.register_variable_type(*var, rust_type);
6824            }
6825            "Map" | "HashMap" => {
6826                let rust_type = if params.len() >= 2 {
6827                    map_rust_type(
6828                        &codegen_type_expr(&params[0], interner),
6829                        &codegen_type_expr(&params[1], interner),
6830                        *var,
6831                        ctx,
6832                    )
6833                } else {
6834                    "LogosMap<String, String>".to_string()
6835                };
6836                ctx.register_variable_type(*var, rust_type);
6837            }
6838            _ => {}
6839        }
6840    } else if let Expr::New {
6841        type_name,
6842        type_args,
6843        ..
6844    } = value
6845    {
6846        let type_str = interner.resolve(*type_name);
6847        match type_str {
6848            "Seq" | "List" | "Vec" => {
6849                let rust_type = if !type_args.is_empty() {
6850                    format!("LogosSeq<{}>", codegen_type_expr(&type_args[0], interner))
6851                } else {
6852                    "LogosSeq<()>".to_string()
6853                };
6854                ctx.register_variable_type(*var, rust_type);
6855            }
6856            "Map" | "HashMap" => {
6857                let rust_type = if type_args.len() >= 2 {
6858                    map_rust_type(
6859                        &codegen_type_expr(&type_args[0], interner),
6860                        &codegen_type_expr(&type_args[1], interner),
6861                        *var,
6862                        ctx,
6863                    )
6864                } else {
6865                    "LogosMap<String, String>".to_string()
6866                };
6867                ctx.register_variable_type(*var, rust_type);
6868            }
6869            // A plain user-defined record (`Let p be a new Parcel ...`): register its own Rust
6870            // struct name, exactly as a typed function PARAMETER already is
6871            // (`codegen_type_expr`'s `Named` arm) — so `record_field_rust_type` can resolve
6872            // `p's field` for a LOCAL the same way it already does for a parameter. Without this,
6873            // `p's label + p's label` (no call, no literal on either side of `+` to carry the
6874            // "this is Text" signal past the concat-fold decision) fell through to a raw `+`.
6875            // Confirmed against the REGISTRY (not just "not Seq/Map") so a `New` of some other
6876            // generic container this match does not yet name (`Set`/`Option`/…, whose OWN Rust
6877            // type is never the bare type name) can never be mistaken for a struct here.
6878            other => {
6879                let is_struct = registry.iter_types().any(|(sym, def)| {
6880                    matches!(def, TypeDef::Struct { .. })
6881                        && super::types::rust_type_ident(interner.resolve(*sym)) == other
6882                });
6883                if is_struct {
6884                    ctx.register_variable_type(*var, super::types::rust_type_ident(type_str));
6885                }
6886            }
6887        }
6888    } else if let Expr::List(items) = value {
6889        // Infer element type from the first element. Every VALUE TYPE (`Seq of Money` /
6890        // `Seq of Quantity` / `Seq of Decimal` / `Seq of Modular` / `Seq of Complex[F]`) is
6891        // recognized richly via its canonical predicate so `item i of xs` and — crucially —
6892        // a value-type loop variable (`Repeat for m in ms`) resolve to the right Rust type;
6893        // otherwise the literal-type inference (which sees only `Expr::Literal`) would flatten
6894        // a `money(..)`/`quantity(..)` constructor call to `_`, and a `total + m` reduce would
6895        // lower to a raw Rust `+` on `LogosMoney` (E0369). Order: most specific first.
6896        let held = super::rational::type_of(value, super::rational::Typing { interner, variable_types: ctx.get_variable_types(), registry });
6897        if held.holds_rational() {
6898            ctx.register_variable_type(*var, held.to_rust_type());
6899        } else {
6900            let elem_type = items
6901                .first()
6902                .and_then(|e| {
6903                    crate::codegen::expr::value_rust_type(
6904                        e,
6905                        ctx.get_variable_types(),
6906                        registry,
6907                        interner,
6908                    )
6909                })
6910                .unwrap_or_else(|| "_".to_string());
6911            ctx.register_variable_type(*var, format!("LogosSeq<{}>", elem_type));
6912        }
6913    } else if matches!(value, Expr::Tuple(_) | Expr::NewVariant { .. }) {
6914        // A tuple literal records each element's type in its marker, so `item N of t` gives an
6915        // element back as itself; a constructed variant records its enum, as a record does above.
6916        if let Some(rust_ty) = crate::codegen::expr::value_rust_type(
6917            value,
6918            ctx.get_variable_types(),
6919            registry,
6920            interner,
6921        ) {
6922            ctx.register_variable_type(*var, rust_ty);
6923        }
6924    } else if let Expr::Identifier(src_sym) = value {
6925        // Propagate type from source variable: `Let result be arr` inherits arr's type.
6926        // For borrow params (&[T]), the copy becomes Vec<T> (owned).
6927        if let Some(src_type) = ctx.get_variable_types().get(src_sym).cloned() {
6928            if src_type.starts_with("&[") {
6929                // Propagate borrow type — rebinding the slice, not copying
6930                ctx.register_variable_type(*var, src_type);
6931            } else if src_type.starts_with("&mut [") {
6932                // Mutable borrow param consumed into alias → propagate &mut [T]
6933                // so the alias continues to be treated as the in-place mutable borrow.
6934                ctx.register_variable_type(*var, src_type);
6935            } else if !super::is_fn_role_slot(&src_type) {
6936                ctx.register_variable_type(*var, src_type);
6937            }
6938        }
6939    } else if let Expr::Copy { expr: inner } = value {
6940        // `Copy of items ... of arr` or `Copy of arr` produces same collection type
6941        let src_sym = match inner {
6942            Expr::Slice { collection, .. } => {
6943                if let Expr::Identifier(s) = collection {
6944                    Some(*s)
6945                } else {
6946                    None
6947                }
6948            }
6949            Expr::Identifier(s) => Some(*s),
6950            _ => None,
6951        };
6952        if let Some(s) = src_sym {
6953            if let Some(src_type) = ctx.get_variable_types().get(&s).cloned() {
6954                if src_type.starts_with("LogosSeq")
6955                    || src_type.starts_with("Vec")
6956                    || src_type.starts_with("&[")
6957                {
6958                    let elem = if src_type.starts_with("LogosSeq<") {
6959                        src_type
6960                            .strip_prefix("LogosSeq<")
6961                            .and_then(|t| t.strip_suffix('>'))
6962                            .unwrap_or("_")
6963                    } else if src_type.starts_with("Vec<") {
6964                        src_type
6965                            .strip_prefix("Vec<")
6966                            .and_then(|t| t.strip_suffix('>'))
6967                            .unwrap_or("_")
6968                    } else {
6969                        src_type
6970                            .strip_prefix("&[")
6971                            .and_then(|t| t.strip_suffix(']'))
6972                            .unwrap_or("_")
6973                    };
6974                    ctx.register_variable_type(*var, format!("LogosSeq<{}>", elem));
6975                } else if src_type.starts_with("LogosMap") {
6976                    ctx.register_variable_type(*var, src_type);
6977                }
6978            }
6979        }
6980    }
6981
6982    // An exact-value-producing RHS binds that value type, OVERRIDING any earlier inference:
6983    // `sqrt` normally types `f64`, but `sqrt` of a `ComplexF` is a `ComplexF` — so complex
6984    // Cholesky's `Let d be sqrt(..)` then reuse of `d` takes the ComplexF codegen path — and a
6985    // decimal, modular, quantity or money result (`Let subtotal be latte + muffin`) binds its own
6986    // type, so later arithmetic on the binding (`subtotal * 2`) stays exact.
6987    if let Some(exact) =
6988        crate::codegen::expr::exact_value_type_of(value, ctx.get_variable_types(), interner)
6989    {
6990        ctx.register_variable_type(*var, exact.to_string());
6991    }
6992
6993    // `Let fac be f's lu` — a struct field-access binding takes the field's DECLARED type, so a
6994    // `Seq of ComplexF` field's elements route through the ComplexF codegen path later
6995    // (`item i of fac` → `.mul`/`.add`, not the type-mismatched `as f64` float path).
6996    if let Expr::FieldAccess { object, field } = value {
6997        if let Expr::Identifier(obj_sym) = object {
6998            if let Some(struct_name) = ctx.get_variable_types().get(obj_sym).cloned() {
6999                let field_name = interner.resolve(*field);
7000                for (tname, tdef) in registry.iter_types() {
7001                    if interner.resolve(*tname) == struct_name {
7002                        if let crate::analysis::registry::TypeDef::Struct { fields, .. } = tdef {
7003                            if let Some(fd) = fields
7004                                .iter()
7005                                .find(|fd| interner.resolve(fd.name) == field_name)
7006                            {
7007                                let rust_ty =
7008                                    crate::codegen::types::codegen_field_type(&fd.ty, interner);
7009                                ctx.register_variable_type(*var, rust_ty);
7010                            }
7011                        }
7012                        break;
7013                    }
7014                }
7015            }
7016        }
7017    }
7018
7019    // Infer result type from function call return types
7020    if !ctx.get_variable_types().contains_key(var) {
7021        if let Expr::Call { function, .. } = value {
7022            // The `decimal(..)` builtin yields an exact `LogosDecimal` — record it so
7023            // later `+ − ×` over this binding take the exact decimal codegen path.
7024            if interner.resolve(*function) == "decimal" {
7025                ctx.register_variable_type(*var, "LogosDecimal".to_string());
7026            } else if interner.resolve(*function) == "complex" {
7027                // Two exact reals (a float part was caught above as `ComplexF`).
7028                ctx.register_variable_type(*var, "LogosComplex".to_string());
7029            } else if interner.resolve(*function) == "modular" {
7030                ctx.register_variable_type(*var, "LogosModular".to_string());
7031            } else if matches!(interner.resolve(*function), "quantity" | "convert") {
7032                // Both quantity builtins yield a `LogosQuantity`; record it so later
7033                // `+ − × ÷` / comparison over this binding take the quantity codegen path.
7034                ctx.register_variable_type(*var, "LogosQuantity".to_string());
7035            } else if interner.resolve(*function) == "money" {
7036                // `money(..)` yields a `LogosMoney`; record it so later `+ − × ÷` /
7037                // comparison over this binding take the money codegen path.
7038                ctx.register_variable_type(*var, "LogosMoney".to_string());
7039            } else if matches!(
7040                interner.resolve(*function),
7041                "uuid"
7042                    | "uuid_nil"
7043                    | "uuid_max"
7044                    | "uuid_v3"
7045                    | "uuid_v5"
7046                    | "uuid_dns"
7047                    | "uuid_url"
7048                    | "uuid_oid"
7049                    | "uuid_x500"
7050            ) {
7051                // Every UUID constructor yields a `LogosUuid`; record it so a later
7052                // comparison over this binding takes the (Ord) UUID codegen path.
7053                ctx.register_variable_type(*var, "LogosUuid".to_string());
7054            } else if interner.resolve(*function) == "text_from_bytes" {
7055                // The byte→Text builtin yields a `String`; record it so a subsequent
7056                // `Let userVal be creds` (this binding read by value) clones instead of
7057                // moving — a bare move would strand a later read as a use-after-move.
7058                ctx.register_variable_type(*var, "String".to_string());
7059            } else if let Some(rt) = ctx.get_fn_return(function).cloned() {
7060                ctx.register_variable_type(*var, rt);
7061            }
7062        }
7063    }
7064
7065    // Register scalar types for mixed Float*Int arithmetic coercion
7066    if !ctx.get_variable_types().contains_key(var) {
7067        let inferred = infer_rust_type_from_expr(value, interner);
7068        if inferred != "_" {
7069            ctx.register_variable_type(*var, inferred);
7070        } else {
7071            // Try deeper numeric type inference for expressions like `4.0 * pi * pi`
7072            let numeric = infer_numeric_type(value, interner, ctx.get_variable_types());
7073            if numeric != "unknown" {
7074                ctx.register_variable_type(*var, numeric.to_string());
7075            } else if let crate::analysis::types::LogosType::Map(k, v) =
7076                super::types::infer_logos_type(value, interner, ctx.get_variable_types())
7077            {
7078                // A `{k: v, …}` map-literal binding: record its `Map<K, V>` type so a
7079                // numeric-unified key lookup (`m contains 1.0` on an Int-keyed map) can
7080                // coerce. Only Map is registered here — the narrowest change that closes
7081                // the compiled key-coercion gap.
7082                ctx.register_variable_type(
7083                    *var,
7084                    crate::analysis::types::LogosType::Map(k, v).to_rust_type(),
7085                );
7086            }
7087        }
7088    }
7089
7090    // A destructure binder `Let fv be item N of tmp` over a MARKED tuple whose element unboxes
7091    // to a concrete type: register that element type. The desugared binder's value is an
7092    // `item N of tmp` Index, so `infer_rust_type_from_expr` cannot see the element type (it
7093    // lives in the tuple's marker), leaving `fv` untyped — and an untyped `Set sev to fv` then
7094    // MOVES `fv`, stranding a sibling branch's `Set sqlstate to fv` as a use-after-move. Reading
7095    // the marker here types the binder so the value-copy clone fires.
7096    if !ctx.get_variable_types().contains_key(var) {
7097        if let Expr::Index {
7098            collection,
7099            index: Expr::Literal(Literal::Number(n)),
7100        } = value
7101        {
7102            if *n >= 1 {
7103                let tuple_type = match collection {
7104                    Expr::Identifier(tuple_sym) => ctx.get_variable_types().get(tuple_sym).cloned(),
7105                    other => crate::codegen::expr::record_field_rust_type(
7106                        other,
7107                        interner,
7108                        ctx.get_variable_types(),
7109                        registry,
7110                    ),
7111                };
7112                if let Some(ty) = tuple_type
7113                    .as_deref()
7114                    .and_then(|t| super::types::logos_tuple_elem_type(t, *n).map(str::to_string))
7115                {
7116                    ctx.register_variable_type(*var, ty);
7117                }
7118            }
7119        }
7120    }
7121
7122    // A nested list literal (`[[…], …]`) whose whole-program type only resolved to the
7123    // imprecise `LogosSeq<_>`: re-register the precise `LogosSeq<LogosSeq<…>>` so the
7124    // nested-write through-write fast path can specialise on the inner Seq. Narrowly gated
7125    // on the imprecise inner, so a de-Rc'd `Vec` or a specialised representation is untouched.
7126    if matches!(value, Expr::List(_))
7127        && ctx
7128            .get_variable_types()
7129            .get(var)
7130            .map_or(false, |t| t == "LogosSeq<_>")
7131    {
7132        if let crate::analysis::types::LogosType::Seq(inner) =
7133            super::types::infer_logos_type(value, interner, ctx.get_variable_types())
7134        {
7135            if matches!(*inner, crate::analysis::types::LogosType::Seq(_)) {
7136                ctx.register_variable_type(
7137                    *var,
7138                    crate::analysis::types::LogosType::Seq(inner).to_rust_type(),
7139                );
7140            }
7141        }
7142    }
7143
7144    // OPT: Single-char text variable → u8 byte.
7145    // If this variable is pre-registered as __single_char_u8, emit u8 instead of String.
7146    let is_single_char_u8 = ctx
7147        .get_variable_types()
7148        .get(var)
7149        .map_or(false, |t| t == "__single_char_u8");
7150
7151    if is_single_char_u8 {
7152        if let Expr::Literal(Literal::Text(sym)) = value {
7153            let text = interner.resolve(*sym);
7154            if text.len() == 1 {
7155                let ch = text.as_bytes()[0];
7156                let is_mutable = *mutable || mutable_vars.contains(var);
7157                if is_mutable {
7158                    writeln!(
7159                        output,
7160                        "{}let mut {}: u8 = b'{}';",
7161                        indent_str, var_name, ch as char
7162                    )
7163                    .unwrap();
7164                } else {
7165                    writeln!(
7166                        output,
7167                        "{}let {}: u8 = b'{}';",
7168                        indent_str, var_name, ch as char
7169                    )
7170                    .unwrap();
7171                }
7172                // Don't register as string var — it's a u8 now
7173                return output;
7174            }
7175        }
7176    }
7177
7178    // Materialize Expr::Slice on LogosSeq as Vec<T> to avoid dangling
7179    // &[T] borrows from temporary Ref guards. Stored as Vec (not LogosSeq)
7180    // so that downstream `copy of` can wrap with LogosSeq::from_vec()
7181    // for zero-copy ownership transfer instead of deep_clone.
7182    if let Expr::Slice {
7183        collection,
7184        start,
7185        end,
7186    } = value
7187    {
7188        if let Expr::Identifier(coll_sym) = collection {
7189            if let Some(coll_type) = ctx.get_variable_types().get(coll_sym).cloned() {
7190                if coll_type.starts_with("LogosSeq<") {
7191                    let elem_type = coll_type
7192                        .strip_prefix("LogosSeq<")
7193                        .and_then(|t| t.strip_suffix('>'))
7194                        .unwrap_or("_");
7195                    let coll_name = names.ident(*coll_sym);
7196                    let start_str = codegen_expr_boxed_with_types(
7197                        start,
7198                        interner,
7199                        synced_vars,
7200                        boxed_fields,
7201                        registry,
7202                        async_functions,
7203                        ctx.get_string_vars(),
7204                        ctx.get_variable_types(),
7205                        ctx.get_fast_div(),
7206                    );
7207                    let end_str = codegen_expr_boxed_with_types(
7208                        end,
7209                        interner,
7210                        synced_vars,
7211                        boxed_fields,
7212                        registry,
7213                        async_functions,
7214                        ctx.get_string_vars(),
7215                        ctx.get_variable_types(),
7216                        ctx.get_fast_div(),
7217                    );
7218                    let is_mutable = *mutable || mutable_vars.contains(var);
7219                    let mutk = if is_mutable { "mut " } else { "" };
7220                    writeln!(
7221                        output,
7222                        "{}let {}{}: Vec<{}> = {}.borrow().logos_slice({}, {}).to_vec();",
7223                        indent_str, mutk, var_name, elem_type, coll_name, start_str, end_str
7224                    )
7225                    .unwrap();
7226                    // Register as Vec<T> — indexing works directly, and `copy of`
7227                    // wraps with LogosSeq::from_vec(x.clone()) for one-copy semantics.
7228                    ctx.register_variable_type(*var, format!("Vec<{}>", elem_type));
7229                    if is_definitely_string_expr_with_vars(value, ctx.get_string_vars()) {
7230                        ctx.register_string_var(*var);
7231                    }
7232                    return output;
7233                } else if coll_type.starts_with("&[") {
7234                    let elem_type = coll_type
7235                        .strip_prefix("&[")
7236                        .and_then(|t| t.strip_suffix(']'))
7237                        .unwrap_or("_");
7238                    let coll_name = names.ident(*coll_sym);
7239                    let start_str = codegen_expr_boxed_with_types(
7240                        start,
7241                        interner,
7242                        synced_vars,
7243                        boxed_fields,
7244                        registry,
7245                        async_functions,
7246                        ctx.get_string_vars(),
7247                        ctx.get_variable_types(),
7248                        ctx.get_fast_div(),
7249                    );
7250                    let end_str = codegen_expr_boxed_with_types(
7251                        end,
7252                        interner,
7253                        synced_vars,
7254                        boxed_fields,
7255                        registry,
7256                        async_functions,
7257                        ctx.get_string_vars(),
7258                        ctx.get_variable_types(),
7259                        ctx.get_fast_div(),
7260                    );
7261                    let is_mutable = *mutable || mutable_vars.contains(var);
7262                    let mutk = if is_mutable { "mut " } else { "" };
7263                    // Direct slice of borrow param — no .borrow() needed
7264                    writeln!(
7265                        output,
7266                        "{}let {}{}: Vec<{}> = {}.logos_slice({}, {}).to_vec();",
7267                        indent_str, mutk, var_name, elem_type, coll_name, start_str, end_str
7268                    )
7269                    .unwrap();
7270                    ctx.register_variable_type(*var, format!("Vec<{}>", elem_type));
7271                    if is_definitely_string_expr_with_vars(value, ctx.get_string_vars()) {
7272                        ctx.register_string_var(*var);
7273                    }
7274                    return output;
7275                }
7276            }
7277        }
7278    }
7279
7280    // Overflow-promoting Int binding: a promotion candidate whose initializer is an
7281    // integer expression is stored as `LogosInt` (not a bare `i64`), so a value that
7282    // exceeds i64 promotes instead of panicking. Register the `|__bigint` sentinel BEFORE
7283    // codegen so any self-reference in the RHS already reads as a LogosInt.
7284    let is_bigint_binding = ty.is_none()
7285        && ctx.is_promotable_candidate(*var)
7286        && crate::codegen::types::infer_numeric_type(value, interner, ctx.get_variable_types())
7287            == "i64";
7288    if is_bigint_binding {
7289        ctx.register_variable_type(*var, "i64|__bigint".to_string());
7290    }
7291
7292    // Phase 54+: the initializer through `codegen_expr_boxed_with_types_oracle`, with string + type tracking.
7293    let mut value_str = if is_bigint_binding {
7294        // Tolerant (un-narrowed) RHS, coerced to LogosInt (`.into()` is identity when the
7295        // RHS is already a LogosInt, and promotes a plain `i64` otherwise).
7296        let raw = codegen_expr_boxed_with_types_oracle_tolerant(
7297            value,
7298            interner,
7299            synced_vars,
7300            boxed_fields,
7301            registry,
7302            async_functions,
7303            ctx.get_string_vars(),
7304            ctx.get_variable_types(),
7305            ctx.get_fast_div(),
7306            ctx.oracle(),
7307        );
7308        format!("logicaffeine_data::LogosInt::from({})", raw)
7309    } else {
7310        codegen_expr_boxed_with_types_oracle(
7311            value,
7312            interner,
7313            synced_vars,
7314            boxed_fields,
7315            registry,
7316            async_functions,
7317            ctx.get_string_vars(),
7318            ctx.get_variable_types(),
7319            ctx.get_fast_div(),
7320            ctx.oracle(),
7321        )
7322    };
7323
7324    // Phase D: lower a non-aliased `Map of Int to Int` to the specialized
7325    // open-addressing `LogosI64Map`, or the keys-only `LogosI64Set` when
7326    // the value is never read (contains + insert only). Override the
7327    // constructor AND re-register the type so the two never disagree,
7328    // regardless of which `Let` initializer shape registered it above.
7329    if ctx.is_i64_map(*var) {
7330        // Densest tier first: a proven bounded key domain → a
7331        // direct-addressed array sized to the capacity hint, offset by the
7332        // proven window `lo`. Otherwise the open-addressing map/set.
7333        let dense = ctx.dense_info(*var);
7334        let i64_ty = if let Some(info) = dense {
7335            dense_type_name(info.kind)
7336        } else if ctx.is_i32_set(*var) {
7337            "LogosI32Set"
7338        } else if ctx.is_i32_map(*var) {
7339            "LogosI32Map"
7340        } else if ctx.is_i64_set(*var) {
7341            "LogosI64Set"
7342        } else {
7343            "LogosI64Map"
7344        };
7345        if let Some(ctor) = i64_map_ctor(
7346            value,
7347            i64_ty,
7348            dense.map(|i| i.lo),
7349            interner,
7350            synced_vars,
7351            boxed_fields,
7352            registry,
7353            async_functions,
7354            ctx,
7355        ) {
7356            value_str = ctor;
7357            ctx.register_variable_type(*var, i64_ty.to_string());
7358        }
7359    }
7360
7361    // Grand Challenge: Variable is mutable if explicitly marked OR if it's a Set target.
7362    // A `LogosI64Map` is mutated in place via `&mut self` (the analysis
7363    // requires ≥1 insert), so it must bind as `let mut`.
7364    let is_mutable = *mutable || mutable_vars.contains(var) || ctx.is_i64_map(*var);
7365
7366    // Reference semantics: clone LogosSeq/LogosMap on assignment to share the Rc.
7367    // Borrow param (&[T]) assigned to mutable local → convert to owned.
7368    // A non-Copy SCALAR source (a `String` — `Let userVal be creds`) is copied by VALUE on
7369    // every tier (the interpreter/VM bind a fresh value), so it must clone too: the source
7370    // variable is frequently read again after the binding (a following `indexOf(creds)` or a
7371    // sibling-branch `cutBefore(creds, …)`), and a bare move would leave those a use-after-move
7372    // (E0382). Mirrors the field-read clone just below and the defensive arg clone in the call
7373    // codegen; a redundant clone of a truly-dead value is elided by LLVM.
7374    if let Expr::Identifier(src_sym) = value {
7375        if let Some(src_type) = ctx.get_variable_types().get(src_sym) {
7376            if super::expr::lent_by_sharing(*src_sym, ctx.get_variable_types()) {
7377                value_str = format!("{}.deep_clone()", value_str);
7378            } else if src_type.starts_with("LogosSeq") || src_type.starts_with("LogosMap") {
7379                value_str = format!("{}.clone()", value_str);
7380            } else if is_mutable && src_type.starts_with("&[") {
7381                value_str = format!("{}.to_vec()", value_str);
7382            } else if !is_copy_type(src_type)
7383                && !src_type.starts_with("&[")
7384                && !src_type.starts_with("&mut [")
7385            {
7386                value_str = format!("{}.clone()", value_str);
7387            }
7388        }
7389    }
7390
7391    // Value semantics for a field READ bound into an owned local — the analog of
7392    // the identifier clone above. `Let rows be result's rows` MOVES the field out
7393    // of the object; if the object is used again afterward (`… pgIntAt(result, …)`)
7394    // that partial move fails to compile ("borrow of partially moved value"). A
7395    // `Let` owns its binding, so clone the field — keeping the object whole, as the
7396    // interpreter/VM already do. Only the owning `Let` needs this; a borrowed read
7397    // (`Show`/`length of`/indexing) never moves. A Copy SCALAR field (Int/Real/Bool)
7398    // is copied by a bare read already, so leave it a free move (no redundant clone).
7399    if let Expr::FieldAccess { object, field } = value {
7400        let field_name = interner.resolve(*field);
7401        let is_copy_scalar = if let Expr::Identifier(obj_sym) = object {
7402            ctx.get_variable_types()
7403                .get(obj_sym)
7404                .and_then(|ty_name| interner.lookup(ty_name))
7405                .and_then(|ty_sym| registry.get(ty_sym))
7406                .and_then(|def| match def {
7407                    logicaffeine_language::analysis::registry::TypeDef::Struct {
7408                        fields, ..
7409                    } => fields
7410                        .iter()
7411                        .find(|f| interner.resolve(f.name) == field_name),
7412                    _ => None,
7413                })
7414                .map(|fd| {
7415                    matches!(
7416                        super::types::codegen_field_type(&fd.ty, interner).as_str(),
7417                        "i64" | "f64" | "bool"
7418                    )
7419                })
7420                .unwrap_or(false)
7421        } else {
7422            false
7423        };
7424        if !is_copy_scalar {
7425            value_str = format!("{}.clone()", value_str);
7426        }
7427    }
7428
7429    // Phase 103: Get explicit type annotation or infer for multi-param generic enums
7430    let type_annotation = if is_bigint_binding {
7431        Some("logicaffeine_data::LogosInt".to_string())
7432    } else {
7433        ty.map(|t| codegen_type_expr(t, interner))
7434            .or_else(|| ctx.rational_join(*var).cloned())
7435            .or_else(|| super::rational::rational_type_of(value, super::rational::Typing { interner, variable_types: ctx.get_variable_types(), registry }))
7436            .or_else(|| infer_variant_type_annotation(value, registry, interner))
7437            .or_else(|| type_silent_let_annotation(value, ctx.get_variable_types().get(var)))
7438    };
7439
7440    // A binding that holds rationals — declared one, a list of them, or exactly joined from integers and rationals —
7441    // holds every integer it is given as the rational it equals. A value no type is known for is an integer.
7442    if let Some(held) = type_annotation.clone().filter(|t| t.contains(super::rational::RATIONAL)) {
7443        let to = super::rational::named(&held);
7444        if let Some(code) = rational_value(
7445            value,
7446            &held,
7447            interner,
7448            ctx,
7449            synced_vars,
7450            async_functions,
7451            boxed_fields,
7452            registry,
7453        ) {
7454            value_str = code;
7455        } else if to == crate::analysis::types::LogosType::Rational
7456            && super::rational::type_of(value, super::rational::Typing { interner, variable_types: ctx.get_variable_types(), registry })
7457                == crate::analysis::types::LogosType::Unknown
7458            && !is_rational_expr(value, ctx.get_variable_types())
7459        {
7460            value_str = format!("LogosRational::from_i64(({}) as i64)", value_str);
7461        }
7462        ctx.register_variable_type(*var, held);
7463    }
7464
7465    match (is_mutable, type_annotation) {
7466        (true, Some(t)) => writeln!(
7467            output,
7468            "{}let mut {}: {} = {};",
7469            indent_str, var_name, t, value_str
7470        )
7471        .unwrap(),
7472        (true, None) => writeln!(
7473            output,
7474            "{}let mut {} = {};",
7475            indent_str, var_name, value_str
7476        )
7477        .unwrap(),
7478        (false, Some(t)) => writeln!(
7479            output,
7480            "{}let {}: {} = {};",
7481            indent_str, var_name, t, value_str
7482        )
7483        .unwrap(),
7484        (false, None) => {
7485            writeln!(output, "{}let {} = {};", indent_str, var_name, value_str).unwrap()
7486        }
7487    }
7488
7489    // O9 libdivide: if this binding is a loop-invariant positive divisor,
7490    // precompute its magic multiply ONCE here so every later `% n` / `/ n`
7491    // lowers to `helper.rem(..)` / `helper.div(..)`. Harmless if `n <= 0`
7492    // (the helper is only ever read inside loops that don't run there).
7493    if let Some(helper) = ctx.get_fast_div().get(var) {
7494        writeln!(
7495            output,
7496            "{}let {} = logicaffeine_data::LogosDivU64::new(({}) as u64);",
7497            indent_str, helper, var_name
7498        )
7499        .unwrap();
7500    }
7501
7502    // Track string variables for proper concatenation in subsequent expressions
7503    if is_definitely_string_expr_with_vars(value, ctx.get_string_vars()) {
7504        ctx.register_string_var(*var);
7505    }
7506
7507    // Phase 43C: Handle refinement type
7508    if let Some(TypeExpr::Refinement {
7509        base: _,
7510        var: bound_var,
7511        predicate,
7512    }) = ty
7513    {
7514        emit_refinement_check(
7515            &var_name,
7516            *bound_var,
7517            predicate,
7518            interner,
7519            &indent_str,
7520            &mut output,
7521        );
7522        ctx.register(*var, *bound_var, predicate);
7523    }
7524    output
7525}
7526
7527pub fn codegen_stmt<'a>(
7528    stmt: &Stmt<'a>,
7529    interner: &Interner,
7530    indent: usize,
7531    mutable_vars: &HashSet<Symbol>,
7532    ctx: &mut RefinementContext<'a>,
7533    lww_fields: &HashSet<(String, String)>,
7534    mv_fields: &HashSet<(String, String)>, // Phase 49b: MVRegister fields (no timestamp)
7535    synced_vars: &mut HashSet<Symbol>,     // Phase 52: Track synced variables
7536    var_caps: &HashMap<Symbol, VariableCapabilities>, // Phase 56: Mount+Sync detection
7537    async_functions: &HashSet<Symbol>,     // Phase 54: Functions that are async
7538    pipe_vars: &HashSet<Symbol>,           // Phase 54: Pipe declarations (have _tx/_rx suffixes)
7539    boxed_fields: &HashSet<(String, String, String)>, // Phase 102: Recursive enum fields
7540    registry: &TypeRegistry,               // Phase 103: For type annotations on polymorphic enums
7541    type_env: &crate::analysis::types::TypeEnv,
7542) -> String {
7543    let indent_str = "    ".repeat(indent);
7544    let mut output = String::new();
7545    let names = RustNames::new(interner);
7546
7547    // OPT-1C: the variables live after this statement (`None` for a statement the liveness analysis never saw →
7548    // conservative clone), published for the expressions it emits.
7549    let live_vars_after: Option<HashSet<Symbol>> = super::flow::live_after(stmt);
7550    let _flow = super::flow::enter(stmt);
7551    let _control = super::control::enter(stmt);
7552
7553    // Mode B: a scheduler operation lowers onto the deterministic replay executor.
7554    if super::deterministic_replay_enabled() {
7555        let mut scope = super::replay::Scope {
7556            interner,
7557            indent,
7558            mutable_vars,
7559            ctx: &mut *ctx,
7560            lww_fields,
7561            mv_fields,
7562            synced_vars: &mut *synced_vars,
7563            var_caps,
7564            async_functions,
7565            pipe_vars,
7566            boxed_fields,
7567            registry,
7568            type_env,
7569        };
7570        if let Some(code) = super::replay::replay_stmt(stmt, &mut scope) {
7571            output.push_str(&code);
7572            return output;
7573        }
7574    }
7575
7576    // Drop a scratch buffer's `new Seq` declaration at any nesting: its fill loop is rewritten in place
7577    // to `let w: [T; N] = from_fn(…)` (the `Stmt::Repeat` handler), which becomes the binding, so this
7578    // `Seq::default()` declaration would be a dead duplicate.
7579    if let Stmt::Let { var, .. } = stmt {
7580        if ctx.scratch_buffer(*var).is_some() {
7581            return output;
7582        }
7583    }
7584
7585    // O5: prepend oracle-proven bounds-elision hints for this statement's
7586    // indexed accesses (the relational `i <= length(arr)` proofs O5a's for-range
7587    // counter hints cannot reach — e.g. a growing FIFO read by a cursor).
7588    output.push_str(&emit_oracle_index_hints(stmt, ctx, interner, registry, &indent_str));
7589
7590    // A change to a value-or-nothing, or to a collection that holds them.
7591    let held = {
7592        let ecx = operand_ctx(interner, ctx, synced_vars, async_functions, boxed_fields, registry);
7593        super::absent::statement(stmt, &ecx, &indent_str)
7594    };
7595    if let Some((code, bound)) = held {
7596        output.push_str(&code);
7597        if let Some((var, ty)) = bound {
7598            ctx.register_variable_type(var, ty);
7599        }
7600        return output;
7601    }
7602
7603    match stmt {
7604        // ★ A LOWERED `## Route` IS A DECLARATION HERE, exactly as it is on the VM. It became an
7605        // ordinary function plus the synthesized `route`/`routeStatus` walk before this codegen
7606        // ever ran, so emitting anything for the declaration itself would be emitting the route
7607        // twice — and emitting a `compile_error!` meant NO route program had ever built to
7608        // AOT-Rust, which is the tier a server actually ships as. The refusal is asked the SAME
7609        // question the VM asks (`route_lowerable`) so the two tiers cannot disagree about which
7610        // routes run, and a route that genuinely did not lower still refuses BY NAME rather than
7611        // vanishing into a server that answers nothing.
7612        Stmt::RouteDef { method, path, .. } => {
7613            if let Some(why) = crate::codegen::expr::route_refusal(*method, *path) {
7614                output.push_str(&format!(
7615                    "{indent_str}compile_error!(\"this `## Route` cannot run on this tier yet: {}.\");\n",
7616                    why.replace('"', "'")
7617                ));
7618            }
7619        }
7620        // Declarations the router carries — the lowering already emitted their functions.
7621        Stmt::MiddlewareDef { .. } | Stmt::RedirectDef { .. } => {}
7622        // ★ A `## Component` IS A DECLARATION HERE, exactly as a `## Route` is. Its functions were
7623        // synthesized by `lower_lgx_components` before this codegen ever ran, so the declaration
7624        // itself emits nothing — and the browser-only half of those functions is skipped by
7625        // `is_browser_only_lowering`, leaving `__html_<Name>` to render markup on a tier with no
7626        // document.
7627        //
7628        // It used to emit a blanket `compile_error!`, which meant a server declaring ONE component
7629        // did not build, and therefore that PER-REQUEST SERVER RENDERING DID NOT EXIST IN
7630        // PRODUCTION: markup could only be produced at build time by pre-rendering, so a dashboard
7631        // or a search result had no server-rendered form at all. A `## Directive` is the same
7632        // shape — behaviour attached to an element, which no server template can reference
7633        // (`view_html_lowerable` refuses a directive attribute by name).
7634        Stmt::ComponentDef(_) | Stmt::DirectiveDef { .. } => {}
7635        // These still need a browser and say so. `Mount` renders into a document; `Fetch` and
7636        // `Serve fetches` are the page's side of the wire; `Replay` drives a recorded session.
7637        // A server that silently dropped one would answer with a page that never appears.
7638        Stmt::Ui(_)
7639        | Stmt::Fetch { .. }
7640        | Stmt::GivenFetch { .. }
7641        | Stmt::ServeFetches
7642        | Stmt::Replay { .. } => {
7643            output.push_str(&format!("{indent_str}compile_error!(\"this needs a browser: mounting, fetching and replaying run in a page, not in a server binary\");\n"));
7644        }
7645        Stmt::TestDef { .. } => {
7646            // `## Test` blocks never enter a compiled program: the runner
7647            // executes them on the interpreter tier (constitution Wave 3;
7648            // compiled tiers join in Wave 13).
7649        }
7650        Stmt::Expect { .. }
7651        | Stmt::ExpectFail { .. }
7652        | Stmt::ExpectOutput { .. }
7653        | Stmt::AdvanceTime { .. }
7654        | Stmt::GivenFile { .. }
7655        | Stmt::ForAll { .. } => {
7656            // Parser-gated to `## Test` bodies, which are never code-generated.
7657            unreachable!("test-only statement reached codegen outside a ## Test block")
7658        }
7659        Stmt::Observe {
7660            category,
7661            message,
7662            payloads,
7663            sample: _,
7664        } => {
7665            // Wave 13 — the OBSERVED profile emits the observation into the
7666            // compiled binary's channel; the ELIDED (release) profile strips
7667            // `Observe` before codegen (`elide_observation`), so this arm is only
7668            // reached when observation is wanted.
7669            use logicaffeine_language::ast::stmt::ObsCategory;
7670            let kind = match category {
7671                ObsCategory::Note => "note",
7672                ObsCategory::Warn => "warn",
7673                ObsCategory::Record => "record",
7674            };
7675            let msg = interner.resolve(*message);
7676            let parts: Vec<String> = payloads
7677                .iter()
7678                .map(|(name, expr)| {
7679                    let name_s = interner.resolve(*name);
7680                    let expr_rust = codegen_expr_with_async_and_strings(
7681                        expr,
7682                        interner,
7683                        synced_vars,
7684                        async_functions,
7685                        ctx.get_string_vars(),
7686                        ctx.get_variable_types(),
7687                        ctx.get_fast_div(),
7688                        registry,
7689                    );
7690                    format!("({name_s:?}, format!(\"{{}}\", {expr_rust}))")
7691                })
7692                .collect();
7693            writeln!(
7694                output,
7695                "{indent_str}logicaffeine_system::obs::record({kind:?}, {msg:?}, &[{}]);",
7696                parts.join(", ")
7697            )
7698            .unwrap();
7699        }
7700        Stmt::During { label, body } => {
7701            // Wave 13 — a balanced trace span in the OBSERVED profile (the ELIDED
7702            // profile unwraps `During` to its body before codegen).
7703            let name = interner.resolve(*label);
7704            writeln!(
7705                output,
7706                "{indent_str}logicaffeine_system::obs::span_enter({name:?});"
7707            )
7708            .unwrap();
7709            for inner in body.iter() {
7710                output.push_str(&codegen_stmt(
7711                    inner,
7712                    interner,
7713                    indent,
7714                    mutable_vars,
7715                    ctx,
7716                    lww_fields,
7717                    mv_fields,
7718                    synced_vars,
7719                    var_caps,
7720                    async_functions,
7721                    pipe_vars,
7722                    boxed_fields,
7723                    registry,
7724                    type_env,
7725                ));
7726            }
7727            writeln!(
7728                output,
7729                "{indent_str}logicaffeine_system::obs::span_exit({name:?});"
7730            )
7731            .unwrap();
7732        }
7733        Stmt::Swap { a, b } => {
7734            // Reversible register exchange → a plain Rust swap of the two same-typed locals; a name swapped with
7735            // itself changes nothing.
7736            let na = names.ident(*a);
7737            let nb = names.ident(*b);
7738            if na != nb {
7739                writeln!(output, "{indent_str}std::mem::swap(&mut {na}, &mut {nb});").unwrap();
7740            }
7741        }
7742        Stmt::Splice { body } => {
7743            // Scope-transparent desugar output: emit the statements FLAT —
7744            // no braces, same indent — so a multi-push lowers byte-identically
7745            // to the consecutive pushes it desugars from.
7746            for inner in body.iter() {
7747                output.push_str(&codegen_stmt(
7748                    inner,
7749                    interner,
7750                    indent,
7751                    mutable_vars,
7752                    ctx,
7753                    lww_fields,
7754                    mv_fields,
7755                    synced_vars,
7756                    var_caps,
7757                    async_functions,
7758                    pipe_vars,
7759                    boxed_fields,
7760                    registry,
7761                    type_env,
7762                ));
7763            }
7764        }
7765        Stmt::Reversibly { body } => {
7766            // A reversible/uncompute block is output-TRANSPARENT: the AOT tier has no history-tape
7767            // notion, so it emits the body FLAT (same as `Splice`), producing byte-identical output
7768            // to the same statements outside the block.
7769            for inner in body.iter() {
7770                output.push_str(&codegen_stmt(
7771                    inner,
7772                    interner,
7773                    indent,
7774                    mutable_vars,
7775                    ctx,
7776                    lww_fields,
7777                    mv_fields,
7778                    synced_vars,
7779                    var_caps,
7780                    async_functions,
7781                    pipe_vars,
7782                    boxed_fields,
7783                    registry,
7784                    type_env,
7785                ));
7786            }
7787        }
7788        Stmt::Let {
7789            var,
7790            ty,
7791            value,
7792            mutable,
7793        } => {
7794            return codegen_let_stmt(
7795                output,
7796                stmt,
7797                var,
7798                ty,
7799                value,
7800                mutable,
7801                interner,
7802                mutable_vars,
7803                ctx,
7804                synced_vars,
7805                async_functions,
7806                boxed_fields,
7807                registry,
7808                &indent_str,
7809                &names,
7810            );
7811        }
7812
7813        Stmt::Set { target, value } => {
7814            return codegen_set_stmt(
7815                output,
7816                target,
7817                value,
7818                interner,
7819                ctx,
7820                synced_vars,
7821                async_functions,
7822                boxed_fields,
7823                registry,
7824                &indent_str,
7825                &names,
7826                live_vars_after,
7827            );
7828        }
7829
7830        Stmt::Call { function, args } => {
7831            let fish = super::instantiation::for_stmt(stmt);
7832            return codegen_call_stmt(
7833                output,
7834                function,
7835                &fish,
7836                args,
7837                interner,
7838                ctx,
7839                synced_vars,
7840                async_functions,
7841                &indent_str,
7842                &names,
7843            );
7844        }
7845
7846        Stmt::If {
7847            cond,
7848            then_block,
7849            else_block,
7850        } => {
7851            return codegen_if_stmt(
7852                output,
7853                cond,
7854                then_block,
7855                else_block,
7856                interner,
7857                indent,
7858                mutable_vars,
7859                ctx,
7860                lww_fields,
7861                mv_fields,
7862                synced_vars,
7863                var_caps,
7864                async_functions,
7865                pipe_vars,
7866                boxed_fields,
7867                registry,
7868                type_env,
7869                &indent_str,
7870            );
7871        }
7872
7873        Stmt::While {
7874            cond,
7875            body,
7876            decreasing: _,
7877        } => {
7878            return codegen_while_stmt(
7879                output,
7880                stmt,
7881                cond,
7882                body,
7883                interner,
7884                indent,
7885                mutable_vars,
7886                ctx,
7887                lww_fields,
7888                mv_fields,
7889                synced_vars,
7890                var_caps,
7891                async_functions,
7892                pipe_vars,
7893                boxed_fields,
7894                registry,
7895                type_env,
7896                &indent_str,
7897            );
7898        }
7899
7900        Stmt::Repeat {
7901            pattern,
7902            iterable,
7903            body,
7904        } => {
7905            return codegen_repeat_stmt(
7906                output,
7907                stmt,
7908                pattern,
7909                iterable,
7910                body,
7911                interner,
7912                indent,
7913                mutable_vars,
7914                ctx,
7915                lww_fields,
7916                mv_fields,
7917                synced_vars,
7918                var_caps,
7919                async_functions,
7920                pipe_vars,
7921                boxed_fields,
7922                registry,
7923                type_env,
7924                &indent_str,
7925                &names,
7926            );
7927        }
7928
7929        Stmt::Return { value } => {
7930            // A `Return` inside a zone leaves the zone, its value computed and set aside.
7931            if let Some(exit) = super::control::return_label() {
7932                if let Some(value) = value {
7933                    let value = codegen_expr_with_async(
7934                        value,
7935                        interner,
7936                        synced_vars,
7937                        async_functions,
7938                        ctx.get_variable_types(),
7939                    );
7940                    writeln!(output, "{indent_str}let _ = {value};").unwrap();
7941                }
7942                writeln!(output, "{indent_str}break '{exit};").unwrap();
7943                return output;
7944            }
7945            return codegen_return_stmt(
7946                output,
7947                value,
7948                interner,
7949                ctx,
7950                synced_vars,
7951                async_functions,
7952                boxed_fields,
7953                registry,
7954                &indent_str,
7955            );
7956        }
7957
7958        Stmt::Break => match super::control::break_label() {
7959            Some(exit) => writeln!(output, "{indent_str}break '{exit};").unwrap(),
7960            None => writeln!(output, "{}break;", indent_str).unwrap(),
7961        },
7962
7963        // A proposition the program asserts or trusts is a proof obligation, discharged (or taken on
7964        // trust) before the program runs; no tier evaluates it at run time.
7965        Stmt::Assert { .. } => {}
7966
7967        // Phase 35: Trust with documented justification
7968        Stmt::Trust { justification, .. } => {
7969            let reason = interner.resolve(*justification);
7970            // Strip quotes if present (string literals include their quotes)
7971            let reason_clean = reason.trim_matches('"');
7972            writeln!(output, "{}// TRUST: {}", indent_str, reason_clean).unwrap();
7973        }
7974
7975        // `Require` and `Assert that` are both checked, in every build, as every tier checks them. A
7976        // reason is evaluated only when the contract breaks, and is the whole report — the panic hook
7977        // prints the payload verbatim.
7978        Stmt::RuntimeAssert {
7979            condition,
7980            hard: _,
7981            dim: _,
7982            reason,
7983        } => {
7984            let cond_str = codegen_expr_with_async_oracle(
7985                condition,
7986                interner,
7987                synced_vars,
7988                async_functions,
7989                ctx.get_variable_types(),
7990                ctx.oracle(),
7991            );
7992            match reason {
7993                None => {
7994                    // The same words every tier reports — never Rust's `assertion failed: <expr>`.
7995                    writeln!(
7996                        output,
7997                        "{}if !({}) {{ panic!(\"Assertion failed\"); }}",
7998                        indent_str, cond_str
7999                    )
8000                    .unwrap();
8001                }
8002                Some(r) => {
8003                    let reason_str = codegen_expr_with_async_oracle(
8004                        r,
8005                        interner,
8006                        synced_vars,
8007                        async_functions,
8008                        ctx.get_variable_types(),
8009                        ctx.oracle(),
8010                    );
8011                    writeln!(output, "{}if !({}) {{ panic!(\"{{}}\", logicaffeine_data::contract_reason(&({}))); }}", indent_str, cond_str, reason_str).unwrap();
8012                }
8013            }
8014        }
8015
8016        Stmt::Fail { reason } => {
8017            let reason_str = codegen_expr_with_async_oracle(
8018                reason,
8019                interner,
8020                synced_vars,
8021                async_functions,
8022                ctx.get_variable_types(),
8023                ctx.oracle(),
8024            );
8025            // The report is the raised value exactly as `Show` prints it, whatever its type.
8026            writeln!(
8027                output,
8028                "{}panic!(\"{{}}\", logicaffeine_system::io::show_string(&({})));",
8029                indent_str, reason_str
8030            )
8031            .unwrap();
8032        }
8033
8034        // Phase 50: Security Check - mandatory runtime guard (NEVER optimized out)
8035        Stmt::Check {
8036            subject,
8037            predicate,
8038            is_capability,
8039            object,
8040            source_text,
8041            ..
8042        } => {
8043            let subj_name = interner.resolve(*subject);
8044            let pred_name = interner.resolve(*predicate).to_lowercase();
8045
8046            let call = if *is_capability {
8047                let obj_sym = object.expect("capability must have object");
8048                let obj_word = interner.resolve(obj_sym);
8049
8050                // Phase 50: Type-based resolution
8051                // "Check that user can publish the document" -> find variable of type Document
8052                // First try to find a variable whose type matches the object word
8053                let obj_name = ctx
8054                    .find_variable_by_type(obj_word, interner)
8055                    .unwrap_or_else(|| obj_word.to_string());
8056
8057                format!("{}.can_{}(&{})", subj_name, pred_name, obj_name)
8058            } else {
8059                format!("{}.is_{}()", subj_name, pred_name)
8060            };
8061
8062            writeln!(output, "{}if !({}) {{", indent_str, call).unwrap();
8063            writeln!(
8064                output,
8065                "{}    logicaffeine_system::panic_with({:?});",
8066                indent_str,
8067                crate::semantics::policy::check_failed(source_text)
8068            )
8069            .unwrap();
8070            writeln!(output, "{}}}", indent_str).unwrap();
8071        }
8072
8073        // Phase 51: P2P Networking - Listen on network address
8074        Stmt::Listen { address, secure } => {
8075            // The PNP one-time pad is wired only into the interpreter's channel seam; the native-AOT
8076            // transpile backend does not carry that seam yet, so fail loud (never silently drop crypto).
8077            if secure.is_some() {
8078                writeln!(output, "{}compile_error!(\"the PNP one-time pad (`with pad`) is only supported by the interpreter tier, not the native-AOT/transpile backend\");", indent_str).unwrap();
8079                return output;
8080            }
8081            let addr_str = codegen_expr_with_async(
8082                address,
8083                interner,
8084                synced_vars,
8085                async_functions,
8086                ctx.get_variable_types(),
8087            );
8088            // Pass &str instead of String
8089            writeln!(
8090                output,
8091                "{}logicaffeine_system::network::listen(&{}).await.expect(\"Failed to listen\");",
8092                indent_str, addr_str
8093            )
8094            .unwrap();
8095        }
8096
8097        // HTTP server: bind the port, then per request marshal the parsed
8098        // `HttpRequest` into a LOGOS `Request`, call the handler, and marshal the
8099        // returned `Response` back to an `HttpResponse`. Byte-identical to the
8100        // interpreter tier: both go through `http::server::serve` →
8101        // `serialize_response`, and neither emits `Date`/volatile headers.
8102        Stmt::Serve { port, handler } => {
8103            return codegen_serve_stmt(
8104                output,
8105                port,
8106                handler,
8107                interner,
8108                ctx,
8109                synced_vars,
8110                async_functions,
8111                &indent_str,
8112            );
8113        }
8114
8115        // Phase 51: P2P Networking - Connect to remote peer
8116        Stmt::ConnectTo { address, secure } => {
8117            if secure.is_some() {
8118                writeln!(output, "{}compile_error!(\"the PNP one-time pad (`with pad`) is only supported by the interpreter tier, not the native-AOT/transpile backend\");", indent_str).unwrap();
8119                return output;
8120            }
8121            let addr_str = codegen_expr_with_async(
8122                address,
8123                interner,
8124                synced_vars,
8125                async_functions,
8126                ctx.get_variable_types(),
8127            );
8128            // Pass &str instead of String
8129            writeln!(
8130                output,
8131                "{}logicaffeine_system::network::connect(&{}).await.expect(\"Failed to connect\");",
8132                indent_str, addr_str
8133            )
8134            .unwrap();
8135        }
8136
8137        // Phase 51: P2P Networking - Create PeerAgent remote handle
8138        Stmt::LetPeerAgent { var, address } => {
8139            let var_name = interner.resolve(*var);
8140            let addr_str = codegen_expr_with_async(
8141                address,
8142                interner,
8143                synced_vars,
8144                async_functions,
8145                ctx.get_variable_types(),
8146            );
8147            // Pass &str instead of String
8148            writeln!(output, "{}let {} = logicaffeine_system::network::PeerAgent::new(&{}).expect(\"Invalid address\");",
8149                     indent_str, var_name, addr_str).unwrap();
8150            ctx.register_variable_type(*var, PEER_AGENT_TYPE.to_string());
8151        }
8152
8153        // Phase 51: Sleep - supports Duration literals or milliseconds
8154        Stmt::Sleep { milliseconds } => {
8155            let expr_str = codegen_expr_with_async(
8156                milliseconds,
8157                interner,
8158                synced_vars,
8159                async_functions,
8160                ctx.get_variable_types(),
8161            );
8162            let inferred_type = infer_rust_type_from_expr(milliseconds, interner);
8163
8164            if inferred_type == "std::time::Duration" {
8165                // Duration type: use directly (already a std::time::Duration)
8166                writeln!(
8167                    output,
8168                    "{}tokio::time::sleep({}).await;",
8169                    indent_str, expr_str
8170                )
8171                .unwrap();
8172            } else {
8173                // Assume milliseconds (integer) - legacy behavior
8174                writeln!(
8175                    output,
8176                    "{}tokio::time::sleep(std::time::Duration::from_millis({} as u64)).await;",
8177                    indent_str, expr_str
8178                )
8179                .unwrap();
8180            }
8181        }
8182
8183        // Phase 52/56: Sync CRDT variable on topic
8184        Stmt::Sync { var, topic } => {
8185            let var_name = interner.resolve(*var);
8186            let topic_str = codegen_expr_with_async(
8187                topic,
8188                interner,
8189                synced_vars,
8190                async_functions,
8191                ctx.get_variable_types(),
8192            );
8193
8194            // Phase 56: Check if this variable is also mounted
8195            if let Some(caps) = var_caps.get(var) {
8196                if caps.mounted {
8197                    // Both Mount and Sync: use Distributed<T>
8198                    // Mount statement will handle the Distributed::mount call
8199                    // Here we just track it as synced
8200                    synced_vars.insert(*var);
8201                    return output; // Skip - Mount will emit Distributed<T>
8202                }
8203            }
8204
8205            // Sync-only: use Synced<T>
8206            writeln!(
8207                output,
8208                "{}let {} = logicaffeine_system::crdt::Synced::new({}, &{}).await;",
8209                indent_str, var_name, var_name, topic_str
8210            )
8211            .unwrap();
8212            synced_vars.insert(*var);
8213        }
8214
8215        // Phase 53/56: Mount persistent CRDT from journal
8216        Stmt::Mount { var, path } => {
8217            let var_name = interner.resolve(*var);
8218            let path_str = codegen_expr_with_async(
8219                path,
8220                interner,
8221                synced_vars,
8222                async_functions,
8223                ctx.get_variable_types(),
8224            );
8225
8226            // Phase 56: Check if this variable is also synced
8227            if let Some(caps) = var_caps.get(var) {
8228                if caps.synced {
8229                    // Both Mount and Sync: use Distributed<T>
8230                    let topic_str = caps
8231                        .sync_topic
8232                        .as_ref()
8233                        .map(|s| s.as_str())
8234                        .unwrap_or("\"default\"");
8235                    writeln!(
8236                        output,
8237                        "{}let {} = logicaffeine_system::distributed::Distributed::mount(vfs.clone(), &{}, Some({}.to_string())).await.expect(\"Failed to mount\");",
8238                        indent_str, var_name, path_str, topic_str
8239                    ).unwrap();
8240                    synced_vars.insert(*var);
8241                    return output;
8242                }
8243            }
8244
8245            // Mount-only: use Persistent<T>
8246            writeln!(
8247                output,
8248                "{}let {} = logicaffeine_system::storage::Persistent::mount(vfs.clone(), &{}).await.expect(\"Failed to mount\");",
8249                indent_str, var_name, path_str
8250            ).unwrap();
8251            synced_vars.insert(*var);
8252        }
8253
8254        // =====================================================================
8255        // Phase 54: Go-like Concurrency Codegen
8256        // =====================================================================
8257        Stmt::LaunchTask { function, args } => {
8258            let fn_name = names.ident(*function);
8259            // Phase 54: When passing a pipe variable, pass the sender (_tx)
8260            let args_str: Vec<String> = args
8261                .iter()
8262                .map(|a| {
8263                    if let Expr::Identifier(sym) = a {
8264                        if pipe_vars.contains(sym) {
8265                            return format!("{}_tx.clone()", interner.resolve(*sym));
8266                        }
8267                    }
8268                    let arg = codegen_expr_with_async(
8269                        a,
8270                        interner,
8271                        synced_vars,
8272                        async_functions,
8273                        ctx.get_variable_types(),
8274                    );
8275                    super::tower::crossing_to_a_task(a, arg, ctx.get_variable_types(), interner)
8276                })
8277                .collect();
8278            let args_str: Vec<(String, bool)> = args_str
8279                .into_iter()
8280                .zip(args.iter())
8281                .map(|(s, a)| (s, matches!(a, Expr::Literal(_))))
8282                .collect();
8283            // Phase 54: Add .await only if the function is async
8284            let await_suffix = if async_functions.contains(function) {
8285                ".await"
8286            } else {
8287                ""
8288            };
8289            writeln!(
8290                output,
8291                "{}tokio::spawn({});",
8292                indent_str,
8293                launched_future(&fn_name, &args_str, &format!("{await_suffix};"))
8294            )
8295            .unwrap();
8296        }
8297
8298        Stmt::LaunchTaskWithHandle {
8299            handle,
8300            function,
8301            args,
8302        } => {
8303            let handle_name = interner.resolve(*handle);
8304            let fn_name = names.ident(*function);
8305            // Phase 54: When passing a pipe variable, pass the sender (_tx)
8306            let args_str: Vec<String> = args
8307                .iter()
8308                .map(|a| {
8309                    if let Expr::Identifier(sym) = a {
8310                        if pipe_vars.contains(sym) {
8311                            return format!("{}_tx.clone()", interner.resolve(*sym));
8312                        }
8313                    }
8314                    let arg = codegen_expr_with_async(
8315                        a,
8316                        interner,
8317                        synced_vars,
8318                        async_functions,
8319                        ctx.get_variable_types(),
8320                    );
8321                    super::tower::crossing_to_a_task(a, arg, ctx.get_variable_types(), interner)
8322                })
8323                .collect();
8324            let args_str: Vec<(String, bool)> = args_str
8325                .into_iter()
8326                .zip(args.iter())
8327                .map(|(s, a)| (s, matches!(a, Expr::Literal(_))))
8328                .collect();
8329            // Phase 54: Add .await only if the function is async
8330            let await_suffix = if async_functions.contains(function) {
8331                ".await"
8332            } else {
8333                ""
8334            };
8335            writeln!(
8336                output,
8337                "{}let {} = tokio::spawn({});",
8338                indent_str,
8339                handle_name,
8340                launched_future(&fn_name, &args_str, await_suffix)
8341            )
8342            .unwrap();
8343        }
8344
8345        Stmt::CreatePipe {
8346            var,
8347            element_type,
8348            capacity,
8349        } => {
8350            let var_name = interner.resolve(*var);
8351            let type_name = interner.resolve(*element_type);
8352            let cap = capacity.unwrap_or(32);
8353            // Map LOGOS types to Rust types
8354            let rust_type = match type_name {
8355                "Int" => "i64",
8356                "Nat" => "u64",
8357                "Text" => "String",
8358                "Bool" => "bool",
8359                _ => type_name,
8360            };
8361            writeln!(
8362                output,
8363                "{}let ({}_tx, mut {}_rx) = tokio::sync::mpsc::channel::<{}>({});",
8364                indent_str, var_name, var_name, rust_type, cap
8365            )
8366            .unwrap();
8367        }
8368
8369        Stmt::SendPipe { value, pipe } => {
8370            let val_str = codegen_expr_boxed_with_types_oracle(
8371                value,
8372                interner,
8373                synced_vars,
8374                boxed_fields,
8375                registry,
8376                async_functions,
8377                ctx.get_string_vars(),
8378                ctx.get_variable_types(),
8379                ctx.get_fast_div(),
8380                ctx.oracle(),
8381            );
8382            let pipe_str = codegen_expr_with_async(
8383                pipe,
8384                interner,
8385                synced_vars,
8386                async_functions,
8387                ctx.get_variable_types(),
8388            );
8389            // Phase 54: Check if pipe is a local declaration (has _tx suffix) or parameter (no suffix)
8390            let is_local_pipe = if let Expr::Identifier(sym) = pipe {
8391                pipe_vars.contains(sym)
8392            } else {
8393                false
8394            };
8395            if is_local_pipe {
8396                writeln!(
8397                    output,
8398                    "{}{}_tx.send({}).await.expect(\"pipe send failed\");",
8399                    indent_str, pipe_str, val_str
8400                )
8401                .unwrap();
8402            } else {
8403                writeln!(
8404                    output,
8405                    "{}{}.send({}).await.expect(\"pipe send failed\");",
8406                    indent_str, pipe_str, val_str
8407                )
8408                .unwrap();
8409            }
8410        }
8411
8412        Stmt::ReceivePipe { var, pipe } => {
8413            let var_name = interner.resolve(*var);
8414            let pipe_str = codegen_expr_with_async(
8415                pipe,
8416                interner,
8417                synced_vars,
8418                async_functions,
8419                ctx.get_variable_types(),
8420            );
8421            // Phase 54: Check if pipe is a local declaration (has _rx suffix) or parameter (no suffix)
8422            let is_local_pipe = if let Expr::Identifier(sym) = pipe {
8423                pipe_vars.contains(sym)
8424            } else {
8425                false
8426            };
8427            if is_local_pipe {
8428                writeln!(
8429                    output,
8430                    "{}let {} = {}_rx.recv().await.expect(\"pipe closed\");",
8431                    indent_str, var_name, pipe_str
8432                )
8433                .unwrap();
8434            } else {
8435                writeln!(
8436                    output,
8437                    "{}let {} = {}.recv().await.expect(\"pipe closed\");",
8438                    indent_str, var_name, pipe_str
8439                )
8440                .unwrap();
8441            }
8442        }
8443
8444        Stmt::TrySendPipe {
8445            value,
8446            pipe,
8447            result,
8448        } => {
8449            let val_str = codegen_expr_boxed_with_types_oracle(
8450                value,
8451                interner,
8452                synced_vars,
8453                boxed_fields,
8454                registry,
8455                async_functions,
8456                ctx.get_string_vars(),
8457                ctx.get_variable_types(),
8458                ctx.get_fast_div(),
8459                ctx.oracle(),
8460            );
8461            let pipe_str = codegen_expr_with_async(
8462                pipe,
8463                interner,
8464                synced_vars,
8465                async_functions,
8466                ctx.get_variable_types(),
8467            );
8468            // Phase 54: Check if pipe is a local declaration
8469            let is_local_pipe = if let Expr::Identifier(sym) = pipe {
8470                pipe_vars.contains(sym)
8471            } else {
8472                false
8473            };
8474            let suffix = if is_local_pipe { "_tx" } else { "" };
8475            if let Some(res) = result {
8476                let res_name = interner.resolve(*res);
8477                writeln!(
8478                    output,
8479                    "{}let {} = {}{}.try_send({}).is_ok();",
8480                    indent_str, res_name, pipe_str, suffix, val_str
8481                )
8482                .unwrap();
8483            } else {
8484                writeln!(
8485                    output,
8486                    "{}let _ = {}{}.try_send({});",
8487                    indent_str, pipe_str, suffix, val_str
8488                )
8489                .unwrap();
8490            }
8491        }
8492
8493        Stmt::TryReceivePipe { var, pipe } => {
8494            let var_name = interner.resolve(*var);
8495            let pipe_str = codegen_expr_with_async(
8496                pipe,
8497                interner,
8498                synced_vars,
8499                async_functions,
8500                ctx.get_variable_types(),
8501            );
8502            // Phase 54: Check if pipe is a local declaration
8503            let is_local_pipe = if let Expr::Identifier(sym) = pipe {
8504                pipe_vars.contains(sym)
8505            } else {
8506                false
8507            };
8508            let suffix = if is_local_pipe { "_rx" } else { "" };
8509            writeln!(
8510                output,
8511                "{}let {} = {}{}.try_recv().ok();",
8512                indent_str, var_name, pipe_str, suffix
8513            )
8514            .unwrap();
8515        }
8516
8517        Stmt::StopTask { handle } => {
8518            let handle_str = codegen_expr_with_async(
8519                handle,
8520                interner,
8521                synced_vars,
8522                async_functions,
8523                ctx.get_variable_types(),
8524            );
8525            writeln!(output, "{}{}.abort();", indent_str, handle_str).unwrap();
8526        }
8527
8528        Stmt::CloseChannel { channel } => {
8529            let chan_str = codegen_expr_with_async(
8530                channel,
8531                interner,
8532                synced_vars,
8533                async_functions,
8534                ctx.get_variable_types(),
8535            );
8536            // A local pipe splits into `_tx`/`_rx`; closing is the sender's `close()`. A parameter channel
8537            // is the sender itself.
8538            let is_local_pipe = if let Expr::Identifier(sym) = channel {
8539                pipe_vars.contains(sym)
8540            } else {
8541                false
8542            };
8543            let suffix = if is_local_pipe { "_tx" } else { "" };
8544            writeln!(output, "{}{}{}.close();", indent_str, chan_str, suffix).unwrap();
8545        }
8546
8547        Stmt::AwaitTask { handle, result } => {
8548            let handle_str = codegen_expr_with_async(
8549                handle,
8550                interner,
8551                synced_vars,
8552                async_functions,
8553                ctx.get_variable_types(),
8554            );
8555            // A tokio `JoinHandle` awaits to a `Result<T, JoinError>`; the join panics on a task panic
8556            // (the deterministic scheduler joins cleanly). `… into r` binds the value; a bare await discards.
8557            match result {
8558                Some(r) => {
8559                    let r_name = interner.resolve(*r);
8560                    writeln!(
8561                        output,
8562                        "{}let {} = {}.await.expect(\"task join failed\");",
8563                        indent_str, r_name, handle_str
8564                    )
8565                    .unwrap();
8566                }
8567                None => {
8568                    writeln!(output, "{}let _ = {}.await;", indent_str, handle_str).unwrap();
8569                }
8570            }
8571        }
8572
8573        Stmt::Select { branches } => {
8574            write_tokio_select(
8575                &mut output,
8576                branches,
8577                interner,
8578                indent,
8579                mutable_vars,
8580                ctx,
8581                lww_fields,
8582                mv_fields,
8583                synced_vars,
8584                var_caps,
8585                async_functions,
8586                pipe_vars,
8587                boxed_fields,
8588                registry,
8589                type_env,
8590            );
8591        }
8592
8593        Stmt::Give { object, recipient } => {
8594            // Move semantics: pass ownership without borrowing
8595            let obj_str = codegen_expr_with_async(
8596                object,
8597                interner,
8598                synced_vars,
8599                async_functions,
8600                ctx.get_variable_types(),
8601            );
8602            let recv_str = recipient_path(
8603                recipient,
8604                interner,
8605                synced_vars,
8606                async_functions,
8607                ctx.get_variable_types(),
8608            );
8609            writeln!(output, "{}{}({});", indent_str, recv_str, obj_str).unwrap();
8610        }
8611
8612        Stmt::Show { object, recipient } => {
8613            return codegen_show_stmt(
8614                output,
8615                object,
8616                recipient,
8617                interner,
8618                ctx,
8619                synced_vars,
8620                async_functions,
8621                registry,
8622                &indent_str,
8623                &names,
8624            );
8625        }
8626
8627        Stmt::SetField {
8628            object,
8629            field,
8630            value,
8631        } => {
8632            let obj_str = codegen_expr_with_async(
8633                object,
8634                interner,
8635                synced_vars,
8636                async_functions,
8637                ctx.get_variable_types(),
8638            );
8639            let field_name = interner.resolve(*field);
8640            let value_str = codegen_expr_boxed_with_types_oracle(
8641                value,
8642                interner,
8643                synced_vars,
8644                boxed_fields,
8645                registry,
8646                async_functions,
8647                ctx.get_string_vars(),
8648                ctx.get_variable_types(),
8649                ctx.get_fast_div(),
8650                ctx.oracle(),
8651            );
8652            let value_str = stored_value(value, value_str, ctx.get_variable_types());
8653
8654            // Phase 49: Check if this field is an LWWRegister or MVRegister
8655            // LWW needs .set(value, timestamp), MV needs .set(value)
8656            let is_lww = lww_fields.iter().any(|(_, f)| f == field_name);
8657            let is_mv = mv_fields.iter().any(|(_, f)| f == field_name);
8658            let field_name = escape_rust_ident(field_name);
8659            if is_lww {
8660                // LWWRegister needs a timestamp - use current system time in microseconds
8661                writeln!(output, "{}{}.{}.set({}, std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_micros() as u64);", indent_str, obj_str, field_name, value_str).unwrap();
8662            } else if is_mv {
8663                // MVRegister just needs the value
8664                writeln!(
8665                    output,
8666                    "{}{}.{}.set({});",
8667                    indent_str, obj_str, field_name, value_str
8668                )
8669                .unwrap();
8670            } else {
8671                writeln!(
8672                    output,
8673                    "{}{}.{} = {};",
8674                    indent_str, obj_str, field_name, value_str
8675                )
8676                .unwrap();
8677            }
8678        }
8679
8680        Stmt::StructDef { .. } => {
8681            // Struct definitions are handled in codegen_program, not here
8682        }
8683
8684        Stmt::FunctionDef { .. } => {
8685            // Function definitions are handled in codegen_program, not here
8686        }
8687
8688        Stmt::Inspect { target, arms, .. } => {
8689            return codegen_inspect_stmt(
8690                output,
8691                target,
8692                arms,
8693                interner,
8694                indent,
8695                mutable_vars,
8696                ctx,
8697                lww_fields,
8698                mv_fields,
8699                synced_vars,
8700                var_caps,
8701                async_functions,
8702                pipe_vars,
8703                boxed_fields,
8704                registry,
8705                type_env,
8706                &indent_str,
8707            );
8708        }
8709
8710        Stmt::Push { value, collection } => {
8711            return codegen_push_stmt(
8712                output,
8713                value,
8714                collection,
8715                interner,
8716                ctx,
8717                synced_vars,
8718                async_functions,
8719                boxed_fields,
8720                registry,
8721                &indent_str,
8722                &names,
8723            );
8724        }
8725
8726        Stmt::Pop { collection, into } => {
8727            if let Expr::Identifier(coll_sym) = collection {
8728                if ctx
8729                    .get_variable_types()
8730                    .get(coll_sym)
8731                    .is_some_and(|t| t == super::tower::VALUE)
8732                {
8733                    let popped = format!(
8734                        "logicaffeine_data::failure::answered({}.pop_value())",
8735                        names.ident(*coll_sym)
8736                    );
8737                    match into {
8738                        Some(var) => {
8739                            writeln!(
8740                                output,
8741                                "{}let {}: {} = {};",
8742                                indent_str,
8743                                names.ident(*var),
8744                                super::tower::VALUE,
8745                                popped
8746                            )
8747                            .unwrap();
8748                            ctx.register_variable_type(*var, super::tower::VALUE.to_string());
8749                        }
8750                        None => writeln!(output, "{}{};", indent_str, popped).unwrap(),
8751                    }
8752                    return output;
8753                }
8754            }
8755            let coll_str = codegen_expr_with_async(
8756                collection,
8757                interner,
8758                synced_vars,
8759                async_functions,
8760                ctx.get_variable_types(),
8761            );
8762            // MVS copy-on-write before the in-place pop (mutates the buffer).
8763            emit_cow(collection, ctx, &names, &indent_str, &mut output);
8764            match into {
8765                Some(var) => {
8766                    let var_name = names.ident(*var);
8767                    // An item popped from a list of rationals is the rational it is.
8768                    let rational = super::rational::held_item(collection, super::rational::Typing { interner, variable_types: ctx.get_variable_types(), registry });
8769                    let typed = rational.as_ref().map(|t| format!(": {t}")).unwrap_or_default();
8770                    // Unwrap the Option returned by pop() - panics if empty
8771                    writeln!(
8772                        output,
8773                        "{}let {}{} = {}.pop().expect(\"Pop from empty collection\");",
8774                        indent_str, var_name, typed, coll_str
8775                    )
8776                    .unwrap();
8777                    if let Some(item) = rational {
8778                        ctx.register_variable_type(*var, item);
8779                    }
8780                }
8781                None => {
8782                    writeln!(output, "{}{}.pop();", indent_str, coll_str).unwrap();
8783                }
8784            }
8785        }
8786
8787        Stmt::Add { value, collection } => {
8788            let val_str = codegen_expr_boxed_with_types_oracle(
8789                value,
8790                interner,
8791                synced_vars,
8792                boxed_fields,
8793                registry,
8794                async_functions,
8795                ctx.get_string_vars(),
8796                ctx.get_variable_types(),
8797                ctx.get_fast_div(),
8798                ctx.oracle(),
8799            );
8800            let val_str = stored_value(value, val_str, ctx.get_variable_types());
8801            let val_str = value_taken_before_the_write(
8802                value,
8803                collection,
8804                val_str,
8805                ctx,
8806                &indent_str,
8807                &mut output,
8808            );
8809            let coll_str = codegen_expr_with_async(
8810                collection,
8811                interner,
8812                synced_vars,
8813                async_functions,
8814                ctx.get_variable_types(),
8815            );
8816            // MVS copy-on-write before the in-place insert (a `LogosMap`; a plain
8817            // `FxHashSet`/`Set` is already value-semantic and yields no `cow`).
8818            emit_cow(collection, ctx, &names, &indent_str, &mut output);
8819            writeln!(output, "{}{}.insert({});", indent_str, coll_str, val_str).unwrap();
8820        }
8821
8822        Stmt::Remove { value, collection } => {
8823            let val_str = codegen_expr_boxed_with_types_oracle(
8824                value,
8825                interner,
8826                synced_vars,
8827                boxed_fields,
8828                registry,
8829                async_functions,
8830                ctx.get_string_vars(),
8831                ctx.get_variable_types(),
8832                ctx.get_fast_div(),
8833                ctx.oracle(),
8834            );
8835            let val_str = value_taken_before_the_write(
8836                value,
8837                collection,
8838                val_str,
8839                ctx,
8840                &indent_str,
8841                &mut output,
8842            );
8843            let coll_str = codegen_expr_with_async(
8844                collection,
8845                interner,
8846                synced_vars,
8847                async_functions,
8848                ctx.get_variable_types(),
8849            );
8850            // MVS copy-on-write before the in-place remove.
8851            emit_cow(collection, ctx, &names, &indent_str, &mut output);
8852            // Order-preserving removal: a `Set` is an IndexSet, whose plain
8853            // `remove` is a swap_remove — `shift_remove` keeps insertion
8854            // order (`LogosMap::remove` already shifts internally).
8855            let is_set = matches!(collection, Expr::Identifier(sym)
8856                if ctx.get_variable_types().get(sym).is_some_and(|t| t.starts_with("Set<") || t.starts_with("FxHashSet<")));
8857            let method = if is_set { "shift_remove" } else { "remove" };
8858            writeln!(
8859                output,
8860                "{}{}.{}(&{});",
8861                indent_str, coll_str, method, val_str
8862            )
8863            .unwrap();
8864        }
8865
8866        Stmt::SetIndex {
8867            collection,
8868            index,
8869            value,
8870        } => {
8871            return codegen_set_index_stmt(
8872                output,
8873                collection,
8874                index,
8875                value,
8876                interner,
8877                ctx,
8878                synced_vars,
8879                async_functions,
8880                boxed_fields,
8881                registry,
8882                &indent_str,
8883                &names,
8884            );
8885        }
8886
8887        // Phase 8.5: Zone (memory arena) block
8888        Stmt::Zone {
8889            name,
8890            capacity,
8891            source_file,
8892            body,
8893        } => {
8894            return codegen_zone_stmt(
8895                output,
8896                name,
8897                capacity,
8898                source_file,
8899                body,
8900                interner,
8901                indent,
8902                mutable_vars,
8903                ctx,
8904                lww_fields,
8905                mv_fields,
8906                synced_vars,
8907                var_caps,
8908                async_functions,
8909                pipe_vars,
8910                boxed_fields,
8911                registry,
8912                type_env,
8913                &indent_str,
8914            );
8915        }
8916
8917        // Phase 9: Concurrent execution block (async, I/O-bound)
8918        // Generates tokio::join! for concurrent task execution
8919        // Phase 51: Variables used across multiple tasks are cloned to avoid move issues
8920        Stmt::Concurrent { tasks } => {
8921            return codegen_concurrent_stmt(
8922                output,
8923                tasks,
8924                interner,
8925                indent,
8926                mutable_vars,
8927                ctx,
8928                lww_fields,
8929                mv_fields,
8930                synced_vars,
8931                var_caps,
8932                async_functions,
8933                pipe_vars,
8934                boxed_fields,
8935                registry,
8936                type_env,
8937                &indent_str,
8938            );
8939        }
8940
8941        // Parallel execution block (CPU-bound): one balanced tree of `rayon::join`s over every task
8942        Stmt::Parallel { tasks } => {
8943            return codegen_parallel_stmt(
8944                output,
8945                tasks,
8946                interner,
8947                indent,
8948                mutable_vars,
8949                ctx,
8950                lww_fields,
8951                mv_fields,
8952                synced_vars,
8953                var_caps,
8954                async_functions,
8955                pipe_vars,
8956                boxed_fields,
8957                registry,
8958                type_env,
8959                &indent_str,
8960            );
8961        }
8962
8963        // Phase 10: Read from console or file
8964        // Phase 53: File reads now use async VFS
8965        Stmt::ReadFrom { var, source } => {
8966            let var_name = interner.resolve(*var);
8967            match source {
8968                ReadSource::Console => {
8969                    writeln!(
8970                        output,
8971                        "{}let {} = logicaffeine_system::io::read_line();",
8972                        indent_str, var_name
8973                    )
8974                    .unwrap();
8975                }
8976                ReadSource::File(path_expr) => {
8977                    let path_str = codegen_expr_with_async(
8978                        path_expr,
8979                        interner,
8980                        synced_vars,
8981                        async_functions,
8982                        ctx.get_variable_types(),
8983                    );
8984                    // Phase 53: Use VFS with async
8985                    writeln!(
8986                        output,
8987                        "{}let {} = vfs.read_to_string(&{}).await.expect(\"Failed to read file\");",
8988                        indent_str, var_name, path_str
8989                    )
8990                    .unwrap();
8991                }
8992            }
8993        }
8994
8995        // Phase 10: Write to file
8996        // Phase 53: File writes now use async VFS
8997        Stmt::WriteFile { content, path } => {
8998            let content_str = codegen_expr_with_async(
8999                content,
9000                interner,
9001                synced_vars,
9002                async_functions,
9003                ctx.get_variable_types(),
9004            );
9005            let path_str = codegen_expr_with_async(
9006                path,
9007                interner,
9008                synced_vars,
9009                async_functions,
9010                ctx.get_variable_types(),
9011            );
9012            // Phase 53: Use VFS with async
9013            writeln!(
9014                output,
9015                "{}vfs.write(&{}, {}.as_bytes()).await.expect(\"Failed to write file\");",
9016                indent_str, path_str, content_str
9017            )
9018            .unwrap();
9019        }
9020
9021        // Phase 46: Spawn an agent
9022        Stmt::Spawn { agent_type, name } => {
9023            let type_name = interner.resolve(*agent_type);
9024            let agent_name = interner.resolve(*name);
9025            // Generate agent spawn with tokio channel
9026            writeln!(
9027                output,
9028                "{}let {} = tokio::spawn(async move {{ /* {} agent loop */ }});",
9029                indent_str, agent_name, type_name
9030            )
9031            .unwrap();
9032        }
9033
9034        // Phase 46: Send message to agent
9035        Stmt::SendMessage {
9036            message,
9037            destination,
9038            ..
9039        } => {
9040            let msg_str = codegen_expr_with_async(
9041                message,
9042                interner,
9043                synced_vars,
9044                async_functions,
9045                ctx.get_variable_types(),
9046            );
9047            let dest_str = codegen_expr_with_async(
9048                destination,
9049                interner,
9050                synced_vars,
9051                async_functions,
9052                ctx.get_variable_types(),
9053            );
9054            // A remote peer is reached through the mesh (`network::send`); an agent is a channel.
9055            let to_peer = matches!(destination, Expr::Identifier(sym)
9056                if ctx.get_variable_types().get(sym).is_some_and(|t| t == PEER_AGENT_TYPE));
9057            if to_peer {
9058                writeln!(
9059                    output,
9060                    "{}logicaffeine_system::network::send(&{}, &{}).await.expect(\"Failed to send message\");",
9061                    indent_str, dest_str, msg_str
9062                ).unwrap();
9063            } else {
9064                writeln!(
9065                    output,
9066                    "{}{}.send({}).await.expect(\"Failed to send message\");",
9067                    indent_str, dest_str, msg_str
9068                )
9069                .unwrap();
9070            }
9071        }
9072
9073        // Streaming is a tree-walker feature (the relay receive runs in the interpreter); the AOT
9074        // path does not lower it yet — emit a marker rather than silently dropping it.
9075        Stmt::StreamMessage { .. } => {
9076            writeln!(
9077                output,
9078                "{}// Stream: interpreter-only (not yet lowered to AOT)",
9079                indent_str
9080            )
9081            .unwrap();
9082        }
9083
9084        // Phase 46: Await response from agent. (`view` is a tree-walker zero-copy receive hint;
9085        // the compiled path decodes eagerly to the same values.)
9086        Stmt::AwaitMessage {
9087            source,
9088            into,
9089            view: _,
9090            stream: _,
9091        } => {
9092            let src_str = codegen_expr_with_async(
9093                source,
9094                interner,
9095                synced_vars,
9096                async_functions,
9097                ctx.get_variable_types(),
9098            );
9099            let var_name = interner.resolve(*into);
9100            writeln!(
9101                output,
9102                "{}let {} = {}.recv().await.expect(\"Failed to receive message\");",
9103                indent_str, var_name, src_str
9104            )
9105            .unwrap();
9106        }
9107
9108        // Phase 49: Merge CRDT state
9109        Stmt::MergeCrdt { source, target } => {
9110            let src_str = codegen_expr_with_async(
9111                source,
9112                interner,
9113                synced_vars,
9114                async_functions,
9115                ctx.get_variable_types(),
9116            );
9117            let tgt_str = codegen_expr_with_async(
9118                target,
9119                interner,
9120                synced_vars,
9121                async_functions,
9122                ctx.get_variable_types(),
9123            );
9124            write_crdt_fold(
9125                &mut output,
9126                &indent_str,
9127                "merge",
9128                &tgt_str,
9129                &src_str,
9130                source,
9131                target,
9132            );
9133        }
9134
9135        // The IDEMPOTENT sibling of `MergeCrdt` — the lattice join. It differs from `Merge` on bare-`Int`
9136        // fields (per-field MAX, not ADD), so it calls the struct's inherent `join` (which folds EVERY field
9137        // ≡ the VM's `crdt_join_field`), NOT `merge` (whose Int fields ADD).
9138        Stmt::JoinCrdt { source, target } => {
9139            let src_str = codegen_expr_with_async(
9140                source,
9141                interner,
9142                synced_vars,
9143                async_functions,
9144                ctx.get_variable_types(),
9145            );
9146            let tgt_str = codegen_expr_with_async(
9147                target,
9148                interner,
9149                synced_vars,
9150                async_functions,
9151                ctx.get_variable_types(),
9152            );
9153            write_crdt_fold(
9154                &mut output,
9155                &indent_str,
9156                "join",
9157                &tgt_str,
9158                &src_str,
9159                source,
9160                target,
9161            );
9162        }
9163
9164        // Phase 49: Increment GCounter
9165        // Phase 52: If object is synced, wrap in .mutate() for auto-publish
9166        Stmt::IncreaseCrdt {
9167            object,
9168            field,
9169            amount,
9170        } => {
9171            let field_name = escape_rust_ident(interner.resolve(*field));
9172            let amount_str = codegen_expr_with_async(
9173                amount,
9174                interner,
9175                synced_vars,
9176                async_functions,
9177                ctx.get_variable_types(),
9178            );
9179
9180            // Check if the root object is synced
9181            let root_sym = get_root_identifier(object);
9182            if let Some(sym) = root_sym {
9183                if synced_vars.contains(&sym) {
9184                    // Synced: use .mutate() for auto-publish
9185                    let obj_name = interner.resolve(sym);
9186                    writeln!(
9187                        output,
9188                        "{}{}.mutate(|inner| inner.{}.increment({} as u64)).await;",
9189                        indent_str, obj_name, field_name, amount_str
9190                    )
9191                    .unwrap();
9192                    return output;
9193                }
9194            }
9195
9196            // Not synced: direct access
9197            let obj_str = codegen_expr_with_async(
9198                object,
9199                interner,
9200                synced_vars,
9201                async_functions,
9202                ctx.get_variable_types(),
9203            );
9204            writeln!(
9205                output,
9206                "{}{}.{}.increment({} as u64);",
9207                indent_str, obj_str, field_name, amount_str
9208            )
9209            .unwrap();
9210        }
9211
9212        // Phase 49b: Decrement PNCounter
9213        Stmt::DecreaseCrdt {
9214            object,
9215            field,
9216            amount,
9217        } => {
9218            let field_name = escape_rust_ident(interner.resolve(*field));
9219            let amount_str = codegen_expr_with_async(
9220                amount,
9221                interner,
9222                synced_vars,
9223                async_functions,
9224                ctx.get_variable_types(),
9225            );
9226
9227            // Check if the root object is synced
9228            let root_sym = get_root_identifier(object);
9229            if let Some(sym) = root_sym {
9230                if synced_vars.contains(&sym) {
9231                    // Synced: use .mutate() for auto-publish
9232                    let obj_name = interner.resolve(sym);
9233                    writeln!(
9234                        output,
9235                        "{}{}.mutate(|inner| inner.{}.decrement({} as u64)).await;",
9236                        indent_str, obj_name, field_name, amount_str
9237                    )
9238                    .unwrap();
9239                    return output;
9240                }
9241            }
9242
9243            // Not synced: direct access
9244            let obj_str = codegen_expr_with_async(
9245                object,
9246                interner,
9247                synced_vars,
9248                async_functions,
9249                ctx.get_variable_types(),
9250            );
9251            writeln!(
9252                output,
9253                "{}{}.{}.decrement({} as u64);",
9254                indent_str, obj_str, field_name, amount_str
9255            )
9256            .unwrap();
9257        }
9258
9259        // Phase 49b: Append to SharedSequence (RGA)
9260        Stmt::AppendToSequence { sequence, value } => {
9261            let seq_str = codegen_expr_with_async(
9262                sequence,
9263                interner,
9264                synced_vars,
9265                async_functions,
9266                ctx.get_variable_types(),
9267            );
9268            let val_str = codegen_expr_boxed_with_types_oracle(
9269                value,
9270                interner,
9271                synced_vars,
9272                boxed_fields,
9273                registry,
9274                async_functions,
9275                ctx.get_string_vars(),
9276                ctx.get_variable_types(),
9277                ctx.get_fast_div(),
9278                ctx.oracle(),
9279            );
9280            writeln!(output, "{}{}.append({});", indent_str, seq_str, val_str).unwrap();
9281        }
9282
9283        // Phase 49b: Resolve MVRegister conflicts
9284        Stmt::ResolveConflict {
9285            object,
9286            field,
9287            value,
9288        } => {
9289            let field_name = escape_rust_ident(interner.resolve(*field));
9290            let val_str = codegen_expr_boxed_with_types_oracle(
9291                value,
9292                interner,
9293                synced_vars,
9294                boxed_fields,
9295                registry,
9296                async_functions,
9297                ctx.get_string_vars(),
9298                ctx.get_variable_types(),
9299                ctx.get_fast_div(),
9300                ctx.oracle(),
9301            );
9302            let obj_str = codegen_expr_with_async(
9303                object,
9304                interner,
9305                synced_vars,
9306                async_functions,
9307                ctx.get_variable_types(),
9308            );
9309            writeln!(
9310                output,
9311                "{}{}.{}.resolve({});",
9312                indent_str, obj_str, field_name, val_str
9313            )
9314            .unwrap();
9315        }
9316
9317        // Escape hatch: emit raw foreign code wrapped in braces for scope isolation
9318        Stmt::Escape { code, .. } => {
9319            let raw_code = interner.resolve(*code);
9320            // The block's own Rust writes to stdout directly, so everything shown before it goes out first.
9321            writeln!(
9322                output,
9323                "{}logicaffeine_system::io::flush_stdout();",
9324                indent_str
9325            )
9326            .unwrap();
9327            write!(output, "{}{{\n", indent_str).unwrap();
9328            for line in raw_code.lines() {
9329                write!(output, "{}    {}\n", indent_str, line).unwrap();
9330            }
9331            write!(output, "{}}}\n", indent_str).unwrap();
9332        }
9333
9334        // Dependencies are metadata; no Rust code emitted.
9335        Stmt::Require { .. } => {}
9336
9337        // Theorems and definitions are proof-layer declarations verified at
9338        // compile-time; they generate no runtime code (handled separately by the
9339        // theorem pipeline at the meta-level).
9340        Stmt::Theorem(_) | Stmt::Definition(_) | Stmt::Axiom(_) | Stmt::Theory(_) => {}
9341
9342        // ★ A FAILURE-SITE MARKER (Wave 3). AOT-Rust does not yet track "current site" the way
9343        // the tree-walker does — accepted and ignored here, explicitly, rather than by a wildcard,
9344        // so the day this backend DOES need to emit something for it, a new variant elsewhere
9345        // cannot silently land in this same arm unnoticed. Emits nothing: a marker this tier
9346        // does not read costs it zero runtime code, which is the whole point of a marker over a
9347        // span field every `Stmt` variant would otherwise carry.
9348        Stmt::Site(_) => {}
9349    }
9350
9351    output
9352}
9353
9354/// OPT-5: Sentinel → break transformation.
9355///
9356/// Detects `If cond then: ...; Set counter to limit.` inside a `While counter < limit:` loop
9357/// and replaces the sentinel set with `break;`. This gives LLVM a clean early-exit edge
9358/// instead of an opaque counter assignment that forces one more condition check.
9359///
9360/// Returns the generated code if the pattern matches, or None.
9361fn try_emit_sentinel_break<'a>(
9362    stmt: &Stmt<'a>,
9363    counter_sym: Symbol,
9364    limit_expr: &Expr<'a>,
9365    interner: &Interner,
9366    indent: usize,
9367    mutable_vars: &HashSet<Symbol>,
9368    ctx: &mut RefinementContext<'a>,
9369    lww_fields: &HashSet<(String, String)>,
9370    mv_fields: &HashSet<(String, String)>,
9371    synced_vars: &mut HashSet<Symbol>,
9372    var_caps: &HashMap<Symbol, VariableCapabilities>,
9373    async_functions: &HashSet<Symbol>,
9374    pipe_vars: &HashSet<Symbol>,
9375    boxed_fields: &HashSet<(String, String, String)>,
9376    registry: &TypeRegistry,
9377    type_env: &crate::analysis::types::TypeEnv,
9378) -> Option<String> {
9379    // Match: If cond then: ...; Set counter to limit. (no else block)
9380    let (if_cond, then_block, else_block) = match stmt {
9381        Stmt::If {
9382            cond,
9383            then_block,
9384            else_block,
9385        } => (cond, then_block, else_block),
9386        _ => return None,
9387    };
9388
9389    if else_block.is_some() {
9390        return None;
9391    }
9392
9393    if then_block.is_empty() {
9394        return None;
9395    }
9396
9397    // Last statement in then_block must be `Set counter to limit`
9398    let last = &then_block[then_block.len() - 1];
9399    match last {
9400        Stmt::Set { target, value, .. } => {
9401            if *target != counter_sym || !exprs_equal(value, limit_expr) {
9402                return None;
9403            }
9404        }
9405        _ => return None,
9406    }
9407
9408    // Pattern matched! Emit if block with break instead of sentinel set.
9409    let indent_str = "    ".repeat(indent);
9410    let var_types = ctx.get_variable_types();
9411    let cond_str =
9412        codegen_expr_with_async(if_cond, interner, synced_vars, async_functions, var_types);
9413    let mut output = String::new();
9414    writeln!(output, "{}if {} {{", indent_str, cond_str).unwrap();
9415
9416    // Emit all then_block statements except the last (the sentinel set)
9417    for s in &then_block[..then_block.len() - 1] {
9418        output.push_str(&codegen_stmt(
9419            s,
9420            interner,
9421            indent + 1,
9422            mutable_vars,
9423            ctx,
9424            lww_fields,
9425            mv_fields,
9426            synced_vars,
9427            var_caps,
9428            async_functions,
9429            pipe_vars,
9430            boxed_fields,
9431            registry,
9432            type_env,
9433        ));
9434    }
9435
9436    // Emit break instead of the sentinel set
9437    writeln!(output, "{}    break;", indent_str).unwrap();
9438    writeln!(output, "{}}}", indent_str).unwrap();
9439
9440    Some(output)
9441}
9442
9443/// `Merge <source> into <target>` / `Converge …`: fold the source's state into the target. The
9444/// source is read as it stood BEFORE the fold — when both name the same variable (`Merge a into a`)
9445/// it is snapshotted first, exactly as the interpreter reads it (and a borrow of `a` while `a` is
9446/// mutated is not Rust).
9447fn write_crdt_fold(
9448    output: &mut String,
9449    indent: &str,
9450    method: &str,
9451    tgt: &str,
9452    src: &str,
9453    source: &Expr,
9454    target: &Expr,
9455) {
9456    let shares_root = matches!(
9457        (get_root_identifier(source), get_root_identifier(target)),
9458        (Some(a), Some(b)) if a == b
9459    );
9460    if shares_root {
9461        writeln!(
9462            output,
9463            "{indent}{{ let __fold_src = ({src}).clone(); {tgt}.{method}(&__fold_src); }}"
9464        )
9465        .unwrap();
9466    } else {
9467        writeln!(output, "{indent}{tgt}.{method}(&{src});").unwrap();
9468    }
9469}
9470
9471/// Phase 52: Extract the root identifier from an expression.
9472/// For `x.field.subfield`, returns `x`.
9473pub(crate) fn get_root_identifier(expr: &Expr) -> Option<Symbol> {
9474    match expr {
9475        Expr::Identifier(sym) => Some(*sym),
9476        Expr::FieldAccess { object, .. } => get_root_identifier(object),
9477        _ => None,
9478    }
9479}
9480
9481/// Extract all symbols from `Expr::Length { collection: Expr::Identifier(sym) }` nodes
9482/// in an expression tree. Used for loop bounds hoisting.
9483pub(crate) fn extract_length_expr_syms(expr: &Expr) -> Vec<Symbol> {
9484    let mut out = Vec::new();
9485    collect_length_syms_from_expr(expr, &mut out);
9486    out
9487}
9488
9489fn collect_length_syms_from_expr(expr: &Expr, out: &mut Vec<Symbol>) {
9490    match expr {
9491        Expr::Length { collection } => {
9492            if let Expr::Identifier(sym) = collection {
9493                out.push(*sym);
9494            }
9495        }
9496        Expr::BinaryOp { left, right, .. } => {
9497            collect_length_syms_from_expr(left, out);
9498            collect_length_syms_from_expr(right, out);
9499        }
9500        Expr::Not { operand } => collect_length_syms_from_expr(operand, out),
9501        Expr::Index { collection, index } => {
9502            collect_length_syms_from_expr(collection, out);
9503            collect_length_syms_from_expr(index, out);
9504        }
9505        Expr::Call { args, .. } => {
9506            for arg in args.iter() {
9507                collect_length_syms_from_expr(arg, out);
9508            }
9509        }
9510        _ => {}
9511    }
9512}
9513
9514/// Collect all `Expr::Length { Identifier(sym) }` symbols from a statement list (recursively).
9515pub(crate) fn collect_length_syms_from_stmts(stmts: &[Stmt], out: &mut Vec<Symbol>) {
9516    for stmt in stmts {
9517        collect_length_syms_from_stmt(stmt, out);
9518    }
9519}
9520
9521fn collect_length_syms_from_stmt(stmt: &Stmt, out: &mut Vec<Symbol>) {
9522    match stmt {
9523        Stmt::Let { value, .. } => collect_length_syms_from_expr(value, out),
9524        Stmt::Set { value, .. } => collect_length_syms_from_expr(value, out),
9525        Stmt::Show { object, .. } => collect_length_syms_from_expr(object, out),
9526        Stmt::Push { value, collection } => {
9527            collect_length_syms_from_expr(value, out);
9528            collect_length_syms_from_expr(collection, out);
9529        }
9530        Stmt::SetIndex {
9531            collection,
9532            index,
9533            value,
9534        } => {
9535            collect_length_syms_from_expr(collection, out);
9536            collect_length_syms_from_expr(index, out);
9537            collect_length_syms_from_expr(value, out);
9538        }
9539        Stmt::If {
9540            cond,
9541            then_block,
9542            else_block,
9543        } => {
9544            collect_length_syms_from_expr(cond, out);
9545            collect_length_syms_from_stmts(then_block, out);
9546            if let Some(else_stmts) = else_block {
9547                collect_length_syms_from_stmts(else_stmts, out);
9548            }
9549        }
9550        Stmt::While { cond, body, .. } => {
9551            collect_length_syms_from_expr(cond, out);
9552            collect_length_syms_from_stmts(body, out);
9553        }
9554        Stmt::Repeat { body, .. } => {
9555            collect_length_syms_from_stmts(body, out);
9556        }
9557        Stmt::Return { value } => {
9558            if let Some(v) = value {
9559                collect_length_syms_from_expr(v, out);
9560            }
9561        }
9562        Stmt::Call { args, .. } => {
9563            for arg in args.iter() {
9564                collect_length_syms_from_expr(arg, out);
9565            }
9566        }
9567        _ => {}
9568    }
9569}
9570
9571/// Check if a type string represents a Copy type (no .clone() needed).
9572/// Delegates to `LogosType::is_copy()` — single source of truth.
9573pub(crate) fn is_copy_type(ty: &str) -> bool {
9574    crate::analysis::types::LogosType::from_rust_type_str(ty).is_copy()
9575}
9576
9577/// Wrap an `If`/`While` condition in `logos_truthy` unless it's statically
9578/// Bool — `If xs:` on a Seq tests emptiness, `If 0.0:` is false, exactly the
9579/// interpreter's truthiness. Bool conditions emit untouched (hot paths pay
9580/// nothing); an imprecisely-inferred Bool still works (`Truthy` covers bool).
9581pub(super) fn truthy_cond_wrap(
9582    cond: &Expr,
9583    cond_str: String,
9584    interner: &Interner,
9585    variable_types: &HashMap<Symbol, String>,
9586) -> String {
9587    if super::tower::is_tower_expr(cond, variable_types, interner) {
9588        return format!("logos_truthy(&({}))", cond_str);
9589    }
9590    if matches!(
9591        super::types::infer_logos_type(cond, interner, variable_types),
9592        crate::analysis::types::LogosType::Bool
9593    ) {
9594        cond_str
9595    } else {
9596        format!("logos_truthy(&({}))", cond_str)
9597    }
9598}
9599
9600/// Check if a Vec<T> type has a Copy element type.
9601/// Delegates to `LogosType::element_type().is_copy()` — single source of truth.
9602pub(crate) fn has_copy_element_type(vec_type: &str) -> bool {
9603    crate::analysis::types::LogosType::from_rust_type_str(vec_type)
9604        .element_type()
9605        .map_or(false, |e| e.is_copy())
9606}
9607
9608/// Check if a HashMap<K, V> type has a Copy value type.
9609/// Delegates to `LogosType::value_type().is_copy()` — single source of truth.
9610pub(crate) fn has_copy_value_type(map_type: &str) -> bool {
9611    crate::analysis::types::LogosType::from_rust_type_str(map_type)
9612        .value_type()
9613        .map_or(false, |v| v.is_copy())
9614}
9615
9616/// Detect commutative reduction patterns in Repeat loops and emit par_iter() code.
9617///
9618/// Pattern: `Repeat for x in coll: Set acc = acc + expr(x)`
9619/// Emits:
9620/// ```text
9621/// if coll.len() >= 10000 {
9622///     acc += coll.par_iter().copied().map(|x| expr).sum::<i64>();
9623/// } else {
9624///     for x in coll.iter().copied() { acc = acc + expr; }
9625/// }
9626/// ```
9627fn try_emit_parallel_reduction<'a>(
9628    var_sym: Symbol,
9629    pattern_str: &str,
9630    iter_str: &str,
9631    iterable: &'a Expr<'a>,
9632    body: &'a [Stmt<'a>],
9633    interner: &Interner,
9634    indent: usize,
9635    ctx: &RefinementContext<'a>,
9636    synced_vars: &HashSet<Symbol>,
9637    async_functions: &HashSet<Symbol>,
9638) -> Option<String> {
9639    // Body must be exactly 1 statement: Set acc = acc OP expr
9640    if body.len() != 1 {
9641        return None;
9642    }
9643
9644    let (acc_sym, op, increment_expr) = match &body[0] {
9645        Stmt::Set { target, value } => {
9646            if let Expr::BinaryOp { op, left, right } = value {
9647                match op {
9648                    BinaryOpKind::Add => {
9649                        // acc = acc + expr  OR  acc = expr + acc
9650                        if let Expr::Identifier(lhs) = left {
9651                            if *lhs == *target {
9652                                Some((*target, BinaryOpKind::Add, *right))
9653                            } else {
9654                                None
9655                            }
9656                        } else if let Expr::Identifier(rhs) = right {
9657                            if *rhs == *target {
9658                                Some((*target, BinaryOpKind::Add, *left))
9659                            } else {
9660                                None
9661                            }
9662                        } else {
9663                            None
9664                        }
9665                    }
9666                    _ => None,
9667                }
9668            } else {
9669                None
9670            }
9671        }
9672        _ => None,
9673    }?;
9674
9675    // The increment expression must only involve the loop variable and literals
9676    if !expr_is_pure_of(increment_expr, var_sym) {
9677        return None;
9678    }
9679
9680    // The collection must be a typed Vec (for .par_iter().copied())
9681    let is_vec_i64 = if let Expr::Identifier(coll_sym) = iterable {
9682        ctx.get_variable_types()
9683            .get(coll_sym)
9684            .map(|t| {
9685                let t = t.split("|__hl:").next().unwrap_or(t.as_str());
9686                (t.starts_with("LogosSeq<") || t.starts_with("Vec<") || t.starts_with("&["))
9687                    && has_copy_element_type(t)
9688            })
9689            .unwrap_or(false)
9690    } else {
9691        false
9692    };
9693
9694    if !is_vec_i64 {
9695        return None;
9696    }
9697
9698    let indent_str = "    ".repeat(indent);
9699    let acc_name = interner.resolve(acc_sym);
9700
9701    // Parallel reduction reorders the additions, so it is sound ONLY for an
9702    // associative accumulator. Integer addition is associative (even under i64
9703    // wrapping), so the parallel sum equals the sequential one bit-for-bit.
9704    // IEEE-754 float addition is NOT associative — a parallel `f64` sum diverges
9705    // from the sequential sum every other tier computes (tree-walker, VM, AOT-C),
9706    // breaking the cross-tier byte-identity that is the whole product. So a float
9707    // accumulator declines the optimization and stays a sequential loop. The
9708    // `.sum::<T>()` type must still match the accumulator (not a hardcoded i64).
9709    let acc_ty = ctx
9710        .get_variable_types()
9711        .get(&acc_sym)
9712        .map(|s| s.split("|__hl:").next().unwrap_or(s.as_str()))
9713        .unwrap_or("i64");
9714    let sum_ty = match acc_ty {
9715        "i64" | "u64" | "i32" | "u32" | "usize" | "isize" => acc_ty,
9716        _ => return None,
9717    };
9718
9719    // Generate the increment expression as Rust code
9720    let incr_code = codegen_expr_with_async(
9721        increment_expr,
9722        interner,
9723        synced_vars,
9724        async_functions,
9725        ctx.get_variable_types(),
9726    );
9727
9728    // Determine if we need a .map() or can use .sum() directly
9729    let needs_map = !matches!(increment_expr, Expr::Identifier(s) if *s == var_sym);
9730
9731    let mut out = String::new();
9732
9733    // Emit parallel reduction with runtime threshold
9734    // LogosSeq needs .borrow() to access the inner Vec for .par_iter()/.iter()
9735    // &[T] and Vec<T> can be used directly without .borrow()
9736    let (borrow_expr, len_expr) = if let Expr::Identifier(coll_sym) = iterable {
9737        let ty = ctx
9738            .get_variable_types()
9739            .get(coll_sym)
9740            .map(|s| s.split("|__hl:").next().unwrap_or(s.as_str()));
9741        if matches!(ty, Some(t) if t.starts_with("LogosSeq")) {
9742            (
9743                format!("{}.borrow()", iter_str),
9744                format!("{}.len()", iter_str),
9745            )
9746        } else {
9747            (iter_str.to_string(), format!("{}.len()", iter_str))
9748        }
9749    } else {
9750        (
9751            format!("{}.borrow()", iter_str),
9752            format!("{}.len()", iter_str),
9753        )
9754    };
9755    writeln!(out, "{}if {} >= 10000 {{", indent_str, len_expr).unwrap();
9756    writeln!(out, "{}    use rayon::prelude::*;", indent_str).unwrap();
9757    writeln!(out, "{}    let __par_ref = {};", indent_str, borrow_expr).unwrap();
9758    if needs_map {
9759        writeln!(
9760            out,
9761            "{}    {} += __par_ref.par_iter().copied().map(|{}| {}).sum::<{}>();",
9762            indent_str, acc_name, pattern_str, incr_code, sum_ty
9763        )
9764        .unwrap();
9765    } else {
9766        writeln!(
9767            out,
9768            "{}    {} += __par_ref.par_iter().copied().sum::<{}>();",
9769            indent_str, acc_name, sum_ty
9770        )
9771        .unwrap();
9772    }
9773    writeln!(out, "{}}} else {{", indent_str).unwrap();
9774    writeln!(
9775        out,
9776        "{}    for {} in {}.to_vec() {{",
9777        indent_str, pattern_str, iter_str
9778    )
9779    .unwrap();
9780
9781    match op {
9782        BinaryOpKind::Add => {
9783            writeln!(out, "{}        {} += {};", indent_str, acc_name, incr_code).unwrap();
9784        }
9785        _ => {
9786            writeln!(
9787                out,
9788                "{}        {} = {} {:?} {};",
9789                indent_str, acc_name, acc_name, op, incr_code
9790            )
9791            .unwrap();
9792        }
9793    }
9794    writeln!(out, "{}    }}", indent_str).unwrap();
9795    writeln!(out, "{}}}", indent_str).unwrap();
9796
9797    Some(out)
9798}
9799
9800/// Check if an expression only involves the given symbol and literals (no side effects).
9801fn expr_is_pure_of(expr: &Expr, allowed_sym: Symbol) -> bool {
9802    match expr {
9803        Expr::Identifier(s) => *s == allowed_sym,
9804        Expr::Literal(_) => true,
9805        Expr::BinaryOp { left, right, .. } => {
9806            expr_is_pure_of(left, allowed_sym) && expr_is_pure_of(right, allowed_sym)
9807        }
9808        Expr::Not { operand } => expr_is_pure_of(operand, allowed_sym),
9809        _ => false,
9810    }
9811}
9812
9813#[cfg(test)]
9814#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/codegen/stmt/tests.rs"]
9815mod tests;