Skip to main content

logicaffeine_compile/codegen/
program.rs

1use std::collections::{HashMap, HashSet};
2use std::fmt::Write;
3
4use crate::analysis::policy::PolicyRegistry;
5use crate::analysis::registry::{TypeDef, TypeRegistry};
6use crate::analysis::types::RustNames;
7use crate::ast::stmt::{Expr, Stmt, TypeExpr};
8use crate::intern::{Interner, Symbol};
9use crate::optimization::{Opt, OptimizationConfig};
10use crate::sourcemap::{OwnershipRole, SourceMap, SourceMapBuilder};
11use crate::token::Span as LogosSpan;
12
13use super::context::{analyze_variable_capabilities, RefinementContext};
14use crate::analysis::callgraph::CallGraph;
15
16/// Does the program call a bit-intrinsic helper `name` (`count_ones` /
17/// `leading_zeros` / `trailing_zeros`, inserted by `optimize::popcount_leaf`)?
18/// Gates emission of that helper so programs that don't use it have
19/// byte-identical codegen (keeps the codegen snapshot tests stable).
20fn program_calls_named(stmts: &[Stmt], interner: &Interner, name: &str) -> bool {
21    fn in_expr(e: &Expr, it: &Interner, name: &str) -> bool {
22        match e {
23            Expr::Call { function, args } => {
24                it.resolve(*function) == name || args.iter().any(|a| in_expr(a, it, name))
25            }
26            Expr::BinaryOp { left, right, .. } => {
27                in_expr(left, it, name) || in_expr(right, it, name)
28            }
29            Expr::Not { operand } => in_expr(operand, it, name),
30            Expr::Index { collection, index } => {
31                in_expr(collection, it, name) || in_expr(index, it, name)
32            }
33            Expr::Length { collection } => in_expr(collection, it, name),
34            _ => false,
35        }
36    }
37    fn in_block(b: &[Stmt], it: &Interner, name: &str) -> bool {
38        b.iter().any(|s| match s {
39            Stmt::Let { value, .. } | Stmt::Set { value, .. } => in_expr(value, it, name),
40            Stmt::Return { value } => value.map_or(false, |e| in_expr(e, it, name)),
41            Stmt::If {
42                cond,
43                then_block,
44                else_block,
45            } => {
46                in_expr(cond, it, name)
47                    || in_block(then_block, it, name)
48                    || else_block.map_or(false, |b| in_block(b, it, name))
49            }
50            Stmt::While { cond, body, .. } => in_expr(cond, it, name) || in_block(body, it, name),
51            Stmt::FunctionDef { body, .. } => in_block(body, it, name),
52            _ => false,
53        })
54    }
55    in_block(stmts, interner, name)
56}
57use crate::analysis::liveness::LivenessResult;
58use crate::analysis::readonly::{MutableBorrowParams, ReadonlyParams};
59
60use super::detection::{
61    collect_async_functions, collect_boxed_fields, collect_crdt_register_fields,
62    collect_de_rc_seqs, collect_escaping_collection_vars, collect_give_arg_indices,
63    collect_interleaved_groups, collect_mutable_vars, collect_mutable_vars_stmt,
64    collect_pipe_sender_params, collect_pipe_vars, collect_pure_functions,
65    collect_scalarizable_seqs, collect_single_char_text_vars, collect_vec_return_fns,
66    detect_double_recursion_closed_form, is_copy_type_expr, is_result_type, is_vec_type_expr,
67    requires_async, requires_vfs, serves, should_inline, should_memoize, vec_to_mut_slice_type,
68    vec_to_slice_type,
69};
70use super::escape_rust_ident;
71use super::ffi::{
72    codegen_logos_runtime_preamble, collect_c_export_reference_types,
73    collect_c_export_value_type_structs, has_c_exports, has_c_exports_with_text, has_wasm_exports,
74};
75use super::marshal::{codegen_c_export_with_marshaling, is_char_type, is_text_type};
76use super::policy::codegen_policy_impls;
77use super::stmt::codegen_stmt;
78use super::tce::{
79    body_has_top_level_tail_pair, codegen_mutual_tce_pair, codegen_stmt_acc, codegen_stmt_tce,
80    codegen_tce_loopback, detect_mutual_tce_pairs, is_tail_recursive,
81};
82use super::types::{
83    codegen_enum_def, codegen_struct_def, codegen_type_expr, infer_return_type_from_body,
84    logos_return_type_to_rust, rust_type_ident,
85};
86use crate::tail_call::detect_accumulator_pattern;
87
88/// Emit `pub type <Bare><generics> = <Alias__Name><generics>;` for a bare type
89/// whose canonical namespaced struct/enum is emitted elsewhere. Preserves the
90/// type's generics (so a generic imported type stays generic) and escapes a
91/// keyword name (`type`/`match`/…), so construction through the bare spelling
92/// resolves to the one canonical Rust type.
93fn emit_bare_type_alias(
94    output: &mut String,
95    simple: &str,
96    twin: &str,
97    generics: &[logicaffeine_base::Symbol],
98    interner: &Interner,
99) {
100    use std::fmt::Write as _;
101    let gstr = if generics.is_empty() {
102        String::new()
103    } else {
104        let params: Vec<&str> = generics.iter().map(|g| interner.resolve(*g)).collect();
105        format!("<{}>", params.join(", "))
106    };
107    let _ = writeln!(
108        output,
109        "    pub type {}{gstr} = {}{gstr};",
110        escape_rust_ident(simple),
111        rust_type_ident(twin)
112    );
113}
114
115use super::{
116    classify_type_for_c_abi, codegen_c_accessors, collect_c_export_ref_structs, CAbiClass,
117};
118
119/// Check if a function body contains escape blocks (raw Rust code).
120/// Functions with escape blocks should not have their param types changed
121/// by borrow optimization, since the escape code may depend on specific types.
122pub(crate) fn body_contains_escape(body: &[Stmt]) -> bool {
123    body.iter().any(|stmt| stmt_contains_escape(stmt))
124}
125
126fn stmt_contains_escape(stmt: &Stmt) -> bool {
127    match stmt {
128        Stmt::Escape { .. } => true,
129        Stmt::Let { value, .. } => expr_contains_escape(value),
130        Stmt::Set { value, .. } => expr_contains_escape(value),
131        Stmt::If {
132            then_block,
133            else_block,
134            ..
135        } => {
136            body_contains_escape(then_block)
137                || else_block
138                    .as_ref()
139                    .map_or(false, |eb| body_contains_escape(eb))
140        }
141        Stmt::While { body, .. } | Stmt::Repeat { body, .. } => body_contains_escape(body),
142        Stmt::Inspect { arms, .. } => arms.iter().any(|arm| body_contains_escape(arm.body)),
143        _ => false,
144    }
145}
146
147fn expr_contains_escape(expr: &Expr) -> bool {
148    matches!(expr, Expr::Escape { .. })
149}
150
151/// - Uses `Distributed<T>` when both Mount and Sync detected
152/// - Boxes recursive enum fields
153/// Generates a complete Rust program from LOGOS statements.
154///
155/// This is the main entry point for code generation. It produces a full Rust
156/// program including:
157/// - Prelude imports (`use logicaffeine_data::*;`)
158/// - Type definitions (structs, enums, inductive types)
159/// - Policy structs with capability methods
160/// - Main function with async runtime if needed
161/// - VFS initialization for file operations
162///
163/// # Arguments
164///
165/// * `stmts` - The parsed LOGOS statements to compile
166/// * `registry` - Type definitions discovered during parsing
167/// * `policies` - Policy definitions for access control
168/// * `interner` - Symbol interner for resolving names
169///
170/// # Returns
171///
172/// A complete Rust source code string ready for compilation.
173/// An affine read-only array's declaration (`Let A be a new Seq …` where `A` was
174/// recognized as an affine read-only array). Codegen deletes such arrays — the
175/// build push is suppressed and every read substitutes the closed form — so the
176/// decl is filtered out of the statement stream before peephole dispatch, where
177/// a `vec_with_capacity`/`vec_fill` pattern would otherwise re-materialize it.
178fn is_affine_array_decl(stmt: &Stmt, ctx: &RefinementContext) -> bool {
179    matches!(stmt, Stmt::Let { var, value, .. }
180        if matches!(value, Expr::New { .. }) && ctx.affine_array(*var).is_some())
181}
182
183/// A statement that BUILDS a constant-table local (its `Let` or one of its constant `Push`es). Filtered
184/// out of the body: the table is emitted once as a stack array `[T; N]` at the top of the function, so
185/// its original heap-`Vec` build (`Seq::default()` + `push` × N) is dropped.
186fn is_const_table_stmt(stmt: &Stmt, ctx: &RefinementContext) -> bool {
187    match stmt {
188        Stmt::Let { var, .. } => ctx.const_table(*var).is_some(),
189        Stmt::Push {
190            collection: Expr::Identifier(c),
191            ..
192        } => ctx.const_table(*c).is_some(),
193        _ => false,
194    }
195}
196
197/// Recursively collect every symbol in `stmts` (INCLUDING nested loop / if / match blocks) whose interned
198/// name equals `name`. Needed because the parser mints distinct symbols per occurrence of an identifier,
199/// so a constant-table's `[T; N]` type must be registered for the USE-SITE symbol (e.g. a call argument
200/// inside a loop), not only the `Let`-binding symbol — `variable_types` is symbol-keyed.
201fn collect_named_syms(
202    stmts: &[Stmt],
203    name: &str,
204    interner: &Interner,
205    out: &mut std::collections::HashSet<Symbol>,
206) {
207    for s in stmts {
208        super::worklist::for_each_stmt_expr(s, &mut |e| {
209            super::worklist::visit_idents(e, &mut |sym| {
210                if name == interner.resolve(sym) {
211                    out.insert(sym);
212                }
213            });
214        });
215        match s {
216            Stmt::If {
217                then_block,
218                else_block,
219                ..
220            } => {
221                collect_named_syms(then_block, name, interner, out);
222                if let Some(eb) = else_block {
223                    collect_named_syms(eb, name, interner, out);
224                }
225            }
226            Stmt::While { body, .. } | Stmt::Repeat { body, .. } => {
227                collect_named_syms(body, name, interner, out);
228            }
229            Stmt::Inspect { arms, .. } => {
230                for arm in arms {
231                    collect_named_syms(arm.body, name, interner, out);
232                }
233            }
234            _ => {}
235        }
236    }
237}
238
239/// Run i64→i32 narrowing detection (on by default). `LOGOS_NO_NARROW` is the
240/// kill-switch (A/B and debugging), matching the other codegen toggles. Excludes
241/// deleted-affine and worklist sequences. `LOGOS_NARROW_TRACE` reports what
242/// narrowed and why.
243fn narrow_seqs<'a>(
244    body: &'a [Stmt<'a>],
245    de_rc: &std::collections::HashSet<Symbol>,
246    affine: &HashMap<Symbol, super::affine_array::AffineArrayInfo>,
247    worklists: &HashMap<Symbol, super::worklist::WorklistInfo>,
248    interner: &Interner,
249) -> HashMap<Symbol, super::narrow::NarrowInfo> {
250    if !crate::optimize::active_config().is_on(crate::optimization::Opt::Narrow) {
251        return HashMap::new();
252    }
253    let mut n = super::narrow::detect_narrowable(body, de_rc, interner);
254    n.retain(|sym, _| {
255        // A deleted affine array has no plain `Vec` to narrow — Affine preempts Narrow.
256        if affine.contains_key(sym) {
257            crate::optimize::mark_preempted(
258                crate::optimization::Opt::Affine,
259                crate::optimization::Opt::Narrow,
260            );
261            return false;
262        }
263        !worklists.contains_key(sym)
264    });
265    if !n.is_empty() {
266        crate::optimize::mark_fired(crate::optimization::Opt::Narrow);
267    }
268    if std::env::var_os("LOGOS_NARROW_TRACE").is_some() {
269        for (sym, info) in &n {
270            eprintln!(
271                "LOGOS_NARROW: `{}` → Vec<i32>{}",
272                interner.resolve(*sym),
273                if info.guards.is_empty() {
274                    " (static range)".to_string()
275                } else {
276                    format!(" (guards: {})", info.guards.join(" && "))
277                }
278            );
279        }
280    }
281    n
282}
283
284/// `Opt::BitPack` (on by default): the `Seq of Bool` locals of `body` held one bit per item
285/// (`codegen::bits`), among the uniquely owned sequences no other representation has claimed.
286fn bitpack_seqs(
287    body: &[Stmt],
288    de_rc: &std::collections::HashSet<Symbol>,
289    claimed: &dyn Fn(Symbol) -> bool,
290    interner: &Interner,
291) -> std::collections::HashSet<Symbol> {
292    if !crate::optimize::active_config().is_on(crate::optimization::Opt::BitPack) {
293        return std::collections::HashSet::new();
294    }
295    let mut packed = super::bits::detect_bitpacked(body, de_rc, interner);
296    packed.retain(|s| !claimed(*s));
297    if !packed.is_empty() {
298        crate::optimize::mark_fired(crate::optimization::Opt::BitPack);
299    }
300    packed
301}
302
303/// Register every function's call-site param-role info into a context's
304/// `variable_types`, packing readonly-borrow (`&[T]`), element-`&mut`-borrow, and
305/// value-semantics `mutable`-collection indices into a single slot per function.
306/// A function may hold several roles (e.g. a readonly `Seq` param plus a `mutable`
307/// param), so the sets are combined rather than written as separate overwriting
308/// strings.
309fn register_fn_roles(
310    ctx: &mut RefinementContext,
311    borrow_params_map: &HashMap<Symbol, HashSet<usize>>,
312    mut_borrow_params_map: &HashMap<Symbol, HashSet<usize>>,
313    value_mutable_params_map: &HashMap<Symbol, HashSet<usize>>,
314) {
315    let mut role_fns: HashSet<Symbol> = HashSet::new();
316    role_fns.extend(borrow_params_map.keys().copied());
317    role_fns.extend(mut_borrow_params_map.keys().copied());
318    role_fns.extend(value_mutable_params_map.keys().copied());
319    let empty = HashSet::new();
320    for fn_sym in role_fns {
321        let b = borrow_params_map.get(&fn_sym).unwrap_or(&empty);
322        let m = mut_borrow_params_map.get(&fn_sym).unwrap_or(&empty);
323        let v = value_mutable_params_map.get(&fn_sym).unwrap_or(&empty);
324        ctx.register_variable_type(fn_sym, super::encode_fn_roles(b, m, v));
325    }
326}
327
328/// The fixed length of every local that codegen emits as a `[T; N]` stack array in `body`, keyed by NAME
329/// (the parser mints distinct symbols per occurrence; a call argument's symbol differs from the decl's).
330/// Computed from the SAME detections codegen uses, so it never over-approximates (a size here ⟹ a real
331/// `[T; N]`), which keeps the derived `&[T; N]` parameter type sound.
332fn scope_array_sizes(
333    body: &[Stmt],
334    all_stmts: &[Stmt],
335    is_main: bool,
336    returns_vec: bool,
337    this_ret: Option<&super::affine_array::ArrayReturnInfo>,
338    borrow_params: &HashMap<Symbol, HashSet<usize>>,
339    mut_borrow_params: &HashMap<Symbol, HashSet<usize>>,
340    vec_return_fns: &HashSet<Symbol>,
341    array_return_fns: &HashMap<Symbol, super::affine_array::ArrayReturnInfo>,
342    interner: &Interner,
343) -> HashMap<String, usize> {
344    let de_rc = collect_de_rc_seqs(
345        body,
346        interner,
347        borrow_params,
348        mut_borrow_params,
349        vec_return_fns,
350        returns_vec,
351    );
352    let mut m: HashMap<String, usize> = HashMap::new();
353    let mut put = |sym: Symbol, n: usize| {
354        m.insert(interner.resolve(sym).to_string(), n);
355    };
356    if is_main {
357        // Main scalarizes ONLY via `collect_scalarizable_seqs` (indexed/const O3 walk that disqualifies
358        // call-arg appearances) + straight-line buffers (borrow-aware) + fn-return arrays. The scratch /
359        // indexed / const-table passes are function-body-only, so including them here would over-report.
360        for (v, info) in collect_scalarizable_seqs(body, interner) {
361            put(v, info.len);
362        }
363    } else {
364        for (v, info) in super::affine_array::detect_const_tables(
365            body,
366            all_stmts,
367            &de_rc,
368            borrow_params,
369            interner,
370        ) {
371            put(v, info.values.len());
372        }
373        for (v, info) in
374            super::affine_array::detect_scratch_buffers(body, &de_rc, borrow_params, interner)
375        {
376            put(v, info.len);
377        }
378        for (v, info) in super::affine_array::detect_indexed_buffers(body, &de_rc, interner) {
379            put(v, info.len);
380        }
381    }
382    for (v, (_, len)) in
383        super::affine_array::detect_straightline_buffers(body, &de_rc, borrow_params, interner)
384    {
385        put(v, len);
386    }
387    for (v, ty) in super::affine_array::array_var_types(body, this_ret, array_return_fns) {
388        if let Some(n) = ty
389            .strip_prefix('[')
390            .and_then(|s| s.rsplit_once("; "))
391            .and_then(|(_, n)| n.strip_suffix(']'))
392            .and_then(|n| n.parse::<usize>().ok())
393        {
394            put(v, n);
395        }
396    }
397    m
398}
399
400/// Record the fixed array length of every read-borrow argument of every `Call` in `e` (recursing into
401/// sub-expressions). `None` = a non-fixed argument at a borrow position (that param can't be `&[T; N]`).
402fn record_call_arg_sizes(
403    e: &Expr,
404    borrow_params: &HashMap<Symbol, HashSet<usize>>,
405    sizes: &HashMap<String, usize>,
406    interner: &Interner,
407    agg: &mut HashMap<(Symbol, usize), Option<usize>>,
408) {
409    match e {
410        Expr::Call { function, args } => {
411            if let Some(bset) = borrow_params.get(function) {
412                for (i, a) in args.iter().enumerate() {
413                    if bset.contains(&i) {
414                        let val = if let Expr::Identifier(v) = a {
415                            sizes.get(interner.resolve(*v)).copied()
416                        } else {
417                            None
418                        };
419                        agg.entry((*function, i))
420                            .and_modify(|cur| {
421                                if *cur != val {
422                                    *cur = None;
423                                }
424                            })
425                            .or_insert(val);
426                    }
427                }
428            }
429            for a in args {
430                record_call_arg_sizes(a, borrow_params, sizes, interner, agg);
431            }
432        }
433        Expr::BinaryOp { left, right, .. }
434        | Expr::Union { left, right }
435        | Expr::Intersection { left, right }
436        | Expr::Range {
437            start: left,
438            end: right,
439        } => {
440            record_call_arg_sizes(left, borrow_params, sizes, interner, agg);
441            record_call_arg_sizes(right, borrow_params, sizes, interner, agg);
442        }
443        Expr::Index { collection, index } => {
444            record_call_arg_sizes(collection, borrow_params, sizes, interner, agg);
445            record_call_arg_sizes(index, borrow_params, sizes, interner, agg);
446        }
447        Expr::Not { operand } => {
448            record_call_arg_sizes(operand, borrow_params, sizes, interner, agg)
449        }
450        Expr::Length { collection }
451        | Expr::Copy { expr: collection }
452        | Expr::Give { value: collection }
453        | Expr::OptionSome { value: collection }
454        | Expr::FieldAccess {
455            object: collection, ..
456        } => record_call_arg_sizes(collection, borrow_params, sizes, interner, agg),
457        Expr::CallExpr { callee, args } => {
458            record_call_arg_sizes(callee, borrow_params, sizes, interner, agg);
459            for a in args {
460                record_call_arg_sizes(a, borrow_params, sizes, interner, agg);
461            }
462        }
463        Expr::List(items) | Expr::Tuple(items) => {
464            for it in items {
465                record_call_arg_sizes(it, borrow_params, sizes, interner, agg);
466            }
467        }
468        _ => {}
469    }
470}
471
472fn walk_call_sizes<'a>(
473    scope: &[Stmt<'a>],
474    borrow_params: &HashMap<Symbol, HashSet<usize>>,
475    sizes: &HashMap<String, usize>,
476    interner: &Interner,
477    agg: &mut HashMap<(Symbol, usize), Option<usize>>,
478) {
479    for s in scope {
480        super::worklist::for_each_stmt_expr(s, &mut |e| {
481            record_call_arg_sizes(e, borrow_params, sizes, interner, agg)
482        });
483        match s {
484            Stmt::If {
485                then_block,
486                else_block,
487                ..
488            } => {
489                walk_call_sizes(then_block, borrow_params, sizes, interner, agg);
490                if let Some(eb) = else_block {
491                    walk_call_sizes(eb, borrow_params, sizes, interner, agg);
492                }
493            }
494            Stmt::While { body, .. } | Stmt::Repeat { body, .. } => {
495                walk_call_sizes(body, borrow_params, sizes, interner, agg)
496            }
497            Stmt::Inspect { arms, .. } => {
498                for arm in arms {
499                    walk_call_sizes(arm.body, borrow_params, sizes, interner, agg);
500                }
501            }
502            _ => {}
503        }
504    }
505}
506
507/// Fixed-array borrow-parameter propagation: `(fn, param_idx) → N` when EVERY call site passes a fixed
508/// `[T; N]` array of the same N at that read-borrow position. The parameter then becomes `&[T; N]`, so
509/// LLVM elides the constant-index bounds checks. Value-safe: `&arr` coerces to either form.
510fn fixed_array_params(
511    stmts: &[Stmt],
512    borrow_params: &HashMap<Symbol, HashSet<usize>>,
513    mut_borrow_params: &HashMap<Symbol, HashSet<usize>>,
514    vec_return_fns: &HashSet<Symbol>,
515    array_return_fns: &HashMap<Symbol, super::affine_array::ArrayReturnInfo>,
516    interner: &Interner,
517) -> HashMap<(Symbol, usize), usize> {
518    if !crate::optimize::active_config().is_on(crate::optimization::Opt::Scalarize) {
519        return HashMap::new();
520    }
521    let mut agg: HashMap<(Symbol, usize), Option<usize>> = HashMap::new();
522    let main_sizes = scope_array_sizes(
523        stmts,
524        stmts,
525        true,
526        false,
527        None,
528        borrow_params,
529        mut_borrow_params,
530        vec_return_fns,
531        array_return_fns,
532        interner,
533    );
534    walk_call_sizes(stmts, borrow_params, &main_sizes, interner, &mut agg);
535    for s in stmts {
536        if let Stmt::FunctionDef {
537            name,
538            body,
539            is_native: false,
540            ..
541        } = s
542        {
543            let rv = vec_return_fns.contains(name);
544            let sizes = scope_array_sizes(
545                body,
546                stmts,
547                false,
548                rv,
549                array_return_fns.get(name),
550                borrow_params,
551                mut_borrow_params,
552                vec_return_fns,
553                array_return_fns,
554                interner,
555            );
556            walk_call_sizes(body, borrow_params, &sizes, interner, &mut agg);
557        }
558    }
559    agg.into_iter()
560        .filter_map(|(k, v)| v.map(|n| (k, n)))
561        .collect()
562}
563
564pub fn codegen_program(
565    stmts: &[Stmt],
566    registry: &TypeRegistry,
567    policies: &PolicyRegistry,
568    interner: &Interner,
569    type_env: &crate::analysis::types::TypeEnv,
570    cfg: &OptimizationConfig,
571) -> String {
572    codegen_program_with_proven(
573        stmts, registry, policies, interner, type_env, cfg, "proven", None,
574    )
575}
576
577/// Like [`codegen_program`], but bundles an extracted math/logic module into the
578/// output. `proven` is the body of a Rust module — functions, `check_*` property
579/// fns, a `World`/`holds` model-checker — produced by the Forge's extraction with
580/// NO `fn main`. It is emitted as `pub mod <module_name> { … }` right after the
581/// prelude (before `user_types`), followed by `use <module_name>::*;` so a bare
582/// call in the imperative program below — e.g. `double(21)` — resolves into it.
583/// Naming the module (rather than dumping items at crate root) keeps multiple
584/// proven modules reachable and avoids polluting the imperative namespace. When
585/// `proven` is `None`/blank the output is byte-identical to [`codegen_program`].
586pub fn codegen_program_with_proven(
587    stmts: &[Stmt],
588    registry: &TypeRegistry,
589    policies: &PolicyRegistry,
590    interner: &Interner,
591    type_env: &crate::analysis::types::TypeEnv,
592    cfg: &OptimizationConfig,
593    module_name: &str,
594    proven: Option<&str>,
595) -> String {
596    codegen_program_inner(
597        stmts,
598        registry,
599        policies,
600        interner,
601        type_env,
602        cfg,
603        module_name,
604        proven,
605        None,
606    )
607    .0
608}
609
610/// Like [`codegen_program`], but also builds the rustc→LOGOS [`SourceMap`]:
611/// every generated line maps to the top-level statement that produced it
612/// (`stmt_spans` is the parser's side-table, 1:1 with `stmts`; zero-width
613/// spans mark prelude statements and are skipped), and variable origins carry
614/// ownership roles for the diagnostic bridge. This is the flycheck substrate.
615pub fn codegen_program_mapped(
616    stmts: &[Stmt],
617    registry: &TypeRegistry,
618    policies: &PolicyRegistry,
619    interner: &Interner,
620    type_env: &crate::analysis::types::TypeEnv,
621    cfg: &OptimizationConfig,
622    stmt_spans: &[LogosSpan],
623    logos_source: &str,
624) -> (String, SourceMap) {
625    let (code, map) = codegen_program_inner(
626        stmts,
627        registry,
628        policies,
629        interner,
630        type_env,
631        cfg,
632        "proven",
633        None,
634        Some((stmt_spans, logos_source)),
635    );
636    (code, map.expect("mapping was requested"))
637}
638
639#[allow(clippy::too_many_arguments)]
640/// Emit the panic hook that makes a LOGOS runtime error look the same on the AOT tier as on every
641/// other one: the message alone on stderr, then exit status 1.
642///
643/// Without it the AOT binary reported a runtime error as a Rust panic — the default hook's
644/// `thread '<unnamed>' panicked at …/ops.rs:168` header plus a backtrace note, and exit 101 — while
645/// the tree-walker and the VM printed `Division by zero` and exited 1. Same program, same input,
646/// two different observable failures depending on how it was run. The runtime already carries the
647/// right words; only the presentation was wrong.
648fn emit_logos_panic_hook(output: &mut String, exit_immediately: bool) {
649    // ★ FULLY QUALIFIED, because `use user_types::*;` sits above this and a LOGOS record may
650    // legitimately be called `Box`. A shipping box, a text box, a box of parts — an ordinary
651    // domain noun that shadowed `std::boxed::Box` and made the generated program fail to COMPILE,
652    // with an error pointing at scaffolding the author never wrote. `String` has the same
653    // problem for the same reason; both are spelled out in full wherever the compiler emits them.
654    writeln!(
655        output,
656        "    std::panic::set_hook(::std::boxed::Box::new(|_logos_info| {{"
657    )
658    .unwrap();
659    writeln!(output, "        logicaffeine_system::io::flush_stdout();").unwrap();
660    writeln!(output, "        let _logos_msg = _logos_info.payload().downcast_ref::<&str>().map(|s| s.to_string())").unwrap();
661    writeln!(
662        output,
663        "            .or_else(|| _logos_info.payload().downcast_ref::<String>().cloned())"
664    )
665    .unwrap();
666    writeln!(
667        output,
668        "            .unwrap_or_else(|| \"LOGOS runtime error\".to_string());"
669    )
670    .unwrap();
671    writeln!(output, "        eprintln!(\"{{}}\", _logos_msg);").unwrap();
672    // A failure ends the program, under either panic strategy, unless a runtime boundary catches it: a served
673    // request answers `500` and the server keeps serving. Replay tasks always unwind into the scheduler, which lets
674    // their peers finish and then returns the failed run to main.
675    if exit_immediately {
676        writeln!(
677            output,
678            "        if !logicaffeine_system::failure::is_caught() {{ std::process::exit(1); }}"
679        )
680        .unwrap();
681    }
682    writeln!(output, "    }}));").unwrap();
683}
684
685fn codegen_program_inner(
686    stmts: &[Stmt],
687    registry: &TypeRegistry,
688    policies: &PolicyRegistry,
689    interner: &Interner,
690    type_env: &crate::analysis::types::TypeEnv,
691    cfg: &OptimizationConfig,
692    module_name: &str,
693    proven: Option<&str>,
694    mapping: Option<(&[LogosSpan], &str)>,
695) -> (String, Option<SourceMap>) {
696    // A nest the dependence test lets run in tile order is versioned here, once, for every entry to the emitter
697    // (`optimize::version`): its clone lives in these arenas and what its guard proves in this facts scope, both
698    // for exactly as long as the emission.
699    let (exprs, stmt_arena, types) = (
700        crate::arena::Arena::new(),
701        crate::arena::Arena::new(),
702        crate::arena::Arena::new(),
703    );
704    let _version_facts = crate::optimize::facts::scope();
705    let arenas = crate::ast_map::Arenas {
706        exprs: &exprs,
707        stmts: &stmt_arena,
708        types: &types,
709    };
710    let versioned =
711        crate::optimize::version::version_stmts(stmts.to_vec(), arenas, type_env, interner, cfg);
712    // A lent element or field becomes a binding the call borrows, stored back after it (`optimize::sequence`); its
713    // fresh names live in this emission's own copy of the interner.
714    crate::analysis::callgraph::install_lending_parameters(&versioned);
715    let mut own = None;
716    let versioned = if crate::optimize::sequence::lends_a_place(&versioned, interner) {
717        crate::optimize::sequence::lower_lent_places(versioned, arenas, own.insert(interner.clone()))
718    } else {
719        versioned
720    };
721    // Where a stored `nothing` reaches, on exactly what this emission lowers (`absent`).
722    let absence = super::absent::of_program(&versioned, registry, own.as_ref().unwrap_or(interner));
723    if absence.is_some() {
724        super::absent::intern_operands(own.get_or_insert_with(|| interner.clone()));
725    }
726    let interner = own.as_ref().unwrap_or(interner);
727    let stmts: &[Stmt] = &versioned;
728    let _absence = super::absent::begin_program(absence, stmts, interner);
729    // How each `Repeat` may iterate: the shared optimizer's proofs, on exactly what this emission lowers.
730    crate::optimize::iteration::prove_iteration_facts(stmts, interner);
731    // Mode B replays the interpreter's scheduler, so it lowers exactly the programs the interpreter
732    // runs on one; any other program compiles as it does in Mode A.
733    let replay = super::deterministic_replay_enabled() && crate::concurrency::uses_scheduler(stmts);
734    super::with_replay_mode(replay, || {
735        codegen_program_body(
736            stmts,
737            registry,
738            policies,
739            interner,
740            type_env,
741            cfg,
742            module_name,
743            proven,
744            mapping,
745        )
746    })
747}
748
749#[allow(clippy::too_many_arguments)]
750fn codegen_program_body(
751    stmts: &[Stmt],
752    registry: &TypeRegistry,
753    policies: &PolicyRegistry,
754    interner: &Interner,
755    type_env: &crate::analysis::types::TypeEnv,
756    cfg: &OptimizationConfig,
757    module_name: &str,
758    proven: Option<&str>,
759    mapping: Option<(&[LogosSpan], &str)>,
760) -> (String, Option<SourceMap>) {
761    let _control = super::control::function();
762    crate::optimize::set_active_config(*cfg);
763    // ★ WHICH REPRESENTATION EACH `Int` SLOT GETS — decided ONCE, here, before a single line is
764    // emitted. LOGOS has one integer type; this tier has two machine forms of it, and a struct
765    // field typed from one answer while the value filling it was typed from another is a program
766    // rustc rejects on a type with nothing in it that a LOGOS author wrote. The facts used to be
767    // computed twice from different seeds, and the mutual recursion between fields, returns and
768    // arguments was run twice rather than to a fixpoint. See `bigint_promote::promotion_facts`.
769    super::expr::begin_program_emission();
770    let _tower = super::tower::begin_program(stmts, interner);
771    // The program's own types, which of them show, and each record's layout — read by every field
772    // type the emitter writes, starting with the type definitions themselves.
773    super::types::set_program_types(stmts, registry, interner);
774    let route_refusals: Vec<(Symbol, Symbol, String)> =
775        logicaffeine_language::parser::lgx_lower::route_refusals(stmts, interner, &|sym| {
776            matches!(
777                registry.get(sym),
778                Some(crate::analysis::registry::TypeDef::Struct { .. })
779            )
780        })
781        .into_iter()
782        .map(|(method, path, why)| (method, path, why.message))
783        .collect();
784    super::expr::set_route_refusals(&route_refusals);
785    super::stmt::set_serve_facts(stmts, interner);
786    let promo = super::bigint_promote::promotion_facts(stmts, interner);
787    let mut output = String::new();
788    let replay = requires_async(stmts) && super::deterministic_replay_enabled();
789    if replay || serves(stmts) {
790        output.push_str(super::UNWIND_PROFILE_HEADER);
791    }
792    // (rust line, LOGOS span) records; materialized into the SourceMap at the
793    // end. `line_count(&output)` before/after an emission brackets its lines.
794    let mut line_records: Vec<(u32, LogosSpan)> = Vec::new();
795
796    // Prelude
797    // Use extracted crates instead of logos_core
798    writeln!(output, "#[allow(unused_imports)]").unwrap();
799    writeln!(output, "use std::fmt::Write as _;").unwrap();
800    writeln!(output, "use logicaffeine_data::*;").unwrap();
801    writeln!(output, "use logicaffeine_system::*;\n").unwrap();
802    // Bit-count intrinsics — each emitted ONLY when the program calls it (so
803    // unrelated codegen is byte-identical). Free functions so every codegen path
804    // renders the call plainly; two's-complement faithful, matching the
805    // tree-walker/VM builtins (optimize::popcount_leaf inserts them).
806    if program_calls_named(stmts, interner, "count_ones") {
807        writeln!(
808            output,
809            "#[inline(always)]\nfn count_ones(x: i64) -> i64 {{ (x as u64).count_ones() as i64 }}\n"
810        )
811        .unwrap();
812    }
813    if program_calls_named(stmts, interner, "leading_zeros") {
814        writeln!(
815            output,
816            "#[inline(always)]\nfn leading_zeros(x: i64) -> i64 {{ (x as u64).leading_zeros() as i64 }}\n"
817        )
818        .unwrap();
819    }
820    if program_calls_named(stmts, interner, "trailing_zeros") {
821        writeln!(
822            output,
823            "#[inline(always)]\nfn trailing_zeros(x: i64) -> i64 {{ (x as u64).trailing_zeros() as i64 }}\n"
824        )
825        .unwrap();
826    }
827    // SIMD substring-count kernel — emitted ONLY when the program contains a
828    // recognized naive-search nest (unrelated codegen stays byte-identical). The
829    // recognizer (peephole::try_emit_naive_search) lowers the nest to a call
830    // into this kernel; the generated binary cannot link the compiler, so the
831    // kernel travels with it, like the emitted `fn args()` wrapper.
832    if super::peephole::stmts_contain_naive_search(stmts, interner) {
833        writeln!(output, "{}", super::strsearch::RUNTIME_SRC).unwrap();
834    }
835
836    // FFI: Emit wasm_bindgen preamble if any function is exported for WASM
837    if has_wasm_exports(stmts, interner) {
838        writeln!(output, "use wasm_bindgen::prelude::*;\n").unwrap();
839    }
840
841    // FFI: Emit CStr/CString imports if any C export uses Text types
842    if has_c_exports_with_text(stmts, interner) {
843        writeln!(output, "use std::ffi::{{CStr, CString}};\n").unwrap();
844    }
845
846    // Universal ABI: Emit LogosStatus runtime preamble if any C exports exist
847    let c_exports_exist = has_c_exports(stmts, interner);
848    if c_exports_exist {
849        output.push_str(&codegen_logos_runtime_preamble());
850    }
851
852    // Bundled proven module: the extracted math/logic objects (functions, `check_*`
853    // property fns, `World`/`holds`) the imperative program calls into. Named so
854    // multiple proven modules stay reachable; `use super::*;` gives it the crate
855    // prelude and `use <name>::*;` brings its public items into imperative scope so
856    // a bare `double(21)` resolves into it. Emitted only when the mixed compile
857    // supplies it — otherwise the output is byte-identical to the bare imperative path.
858    if let Some(proven) = proven {
859        if !proven.trim().is_empty() {
860            writeln!(output, "pub mod {module_name} {{").unwrap();
861            writeln!(output, "    #![allow(dead_code, unused, non_snake_case)]").unwrap();
862            writeln!(output, "    use super::*;").unwrap();
863            output.push_str(proven);
864            if !proven.ends_with('\n') {
865                writeln!(output).unwrap();
866            }
867            writeln!(output, "}}").unwrap();
868            writeln!(output, "use {module_name}::*;\n").unwrap();
869        }
870    }
871
872    // Phase 49: Collect CRDT register fields for special SetField handling
873    // LWW fields need timestamp, MV fields don't
874    let (lww_fields, mv_fields) = collect_crdt_register_fields(registry, interner);
875
876    // Phase 54: Collect async functions for Launch codegen
877    let async_functions = collect_async_functions(stmts);
878
879    // Purity analysis for memoization
880    let pure_functions = collect_pure_functions(stmts, interner);
881
882    // Phase 54: Collect pipe declarations (variables with _tx/_rx suffixes)
883    let main_pipe_vars = collect_pipe_vars(stmts);
884
885    // Phase 102: Collect boxed fields for recursive enum handling
886    let boxed_fields = collect_boxed_fields(registry, interner);
887
888    // Collect value-type struct names used in C exports (need #[repr(C)])
889    let c_abi_value_structs: HashSet<Symbol> = if c_exports_exist {
890        collect_c_export_value_type_structs(stmts, interner, registry)
891    } else {
892        HashSet::new()
893    };
894
895    // Collect reference-type struct names used in C exports (need serde derives for from_json/to_json)
896    let c_abi_ref_structs: HashSet<Symbol> = if c_exports_exist {
897        collect_c_export_ref_structs(stmts, interner, registry)
898    } else {
899        HashSet::new()
900    };
901
902    // Collect user-defined structs from registry (Phase 34: generics, Phase 47: is_portable, Phase 49: is_shared)
903    let mut structs: Vec<_> = registry
904        .iter_types()
905        .filter(|(sym, def)| super::types::emits_user_type(**sym, def))
906        .filter_map(|(name, def)| match def {
907            TypeDef::Struct {
908                fields,
909                generics,
910                is_portable,
911                is_shared,
912            } => Some((
913                *name,
914                fields.clone(),
915                generics.clone(),
916                *is_portable,
917                *is_shared,
918            )),
919            _ => None,
920        })
921        .collect();
922    // DETERMINISM: `iter_types` walks a HashMap (random per-run order). Sort by
923    // name so the emitted Rust is byte-identical across recompiles (Rust resolves
924    // top-level types order-independently, so this can't affect correctness).
925    structs.sort_by(|a, b| interner.resolve(a.0).cmp(interner.resolve(b.0)));
926
927    // Phase 33/34: Collect user-defined enums from registry (generics, Phase 47: is_portable, Phase 49: is_shared)
928    let mut enums: Vec<_> = registry
929        .iter_types()
930        .filter(|(sym, def)| super::types::emits_user_type(**sym, def))
931        .filter_map(|(name, def)| match def {
932            TypeDef::Enum {
933                variants,
934                generics,
935                is_portable,
936                is_shared,
937            } => Some((
938                *name,
939                variants.clone(),
940                generics.clone(),
941                *is_portable,
942                *is_shared,
943            )),
944            _ => None,
945        })
946        .collect();
947    enums.sort_by(|a, b| interner.resolve(a.0).cmp(interner.resolve(b.0)));
948
949    // Emit struct and enum definitions in user_types module if any exist
950    if !structs.is_empty() || !enums.is_empty() {
951        writeln!(output, "pub mod user_types {{").unwrap();
952        writeln!(output, "    use super::*;\n").unwrap();
953
954        // An imported type reaches the registry under BOTH its bare simple name
955        // (from the inline splice) and its canonical `Alias::Name` (from import
956        // discovery). Emit the canonical struct ONCE and make the bare spelling a
957        // `type` alias to it, rather than a dead duplicate struct — Rust resolves
958        // struct construction through a type alias, so `a new Point` still works.
959        // A struct field fed a bignum-promoted value (json's `JNum { n: m }`) must be stored as
960        // `LogosInt`, not `i64`. Record which `(struct, field)` pairs BEFORE emitting struct defs —
961        // the def below reads this thread-local to type such a field. `bigint_fns` is a pure fn of
962        // `stmts` (recomputed here so the record is available this early; the later copy is identical).
963        super::expr::set_bigint_struct_fields(&promo.bigint_fields, registry);
964
965        let twins = registry.namespaced_twins(interner);
966
967        for (name, fields, generics, is_portable, is_shared) in &structs {
968            if let Some(twin) = twins.get(name) {
969                emit_bare_type_alias(
970                    &mut output,
971                    interner.resolve(*name),
972                    interner.resolve(*twin),
973                    generics,
974                    interner,
975                );
976                continue;
977            }
978            output.push_str(&codegen_struct_def(
979                *name,
980                fields,
981                generics,
982                *is_portable,
983                *is_shared,
984                interner,
985                4,
986                &c_abi_value_structs,
987                &c_abi_ref_structs,
988            ));
989        }
990
991        // Same single-emit for imported enums: canonical `Alias__Enum` once, with
992        // a `type Bare = Alias__Enum;` alias for the bare spelling.
993        for (name, variants, generics, is_portable, is_shared) in &enums {
994            if let Some(twin) = twins.get(name) {
995                emit_bare_type_alias(
996                    &mut output,
997                    interner.resolve(*name),
998                    interner.resolve(*twin),
999                    generics,
1000                    interner,
1001                );
1002                continue;
1003            }
1004            output.push_str(&codegen_enum_def(
1005                *name,
1006                variants,
1007                generics,
1008                *is_portable,
1009                *is_shared,
1010                interner,
1011                4,
1012            ));
1013        }
1014
1015        writeln!(output, "}}\n").unwrap();
1016        writeln!(output, "use user_types::*;\n").unwrap();
1017    }
1018
1019    // Phase 50: Generate policy impl blocks with predicate and capability methods
1020    output.push_str(&codegen_policy_impls(policies, interner));
1021
1022    // Mutual TCO: Detect pairs of mutually tail-calling functions
1023    let mutual_tce_pairs = detect_mutual_tce_pairs(stmts, interner);
1024    let mut mutual_tce_members: HashSet<Symbol> = HashSet::new();
1025    for (a, b) in &mutual_tce_pairs {
1026        mutual_tce_members.insert(*a);
1027        mutual_tce_members.insert(*b);
1028    }
1029    let mut mutual_tce_emitted: HashSet<Symbol> = HashSet::new();
1030
1031    // Pre-pass: Build borrow_params_map — identifies which function params
1032    // can be borrowed as &[T] instead of owned Vec<T>.
1033    // Uses whole-program transitive readonly analysis (ReadonlyParams) instead of
1034    // local-body-only detection so that params passed to mutating callees are
1035    // correctly excluded from borrow optimization.
1036    let callgraph = CallGraph::build(stmts, interner);
1037    let readonly_params = ReadonlyParams::analyze(stmts, &callgraph, type_env);
1038
1039    let mut borrow_params_map: HashMap<Symbol, HashSet<usize>> = HashMap::new();
1040    for stmt in stmts {
1041        if let Stmt::FunctionDef {
1042            name,
1043            params,
1044            body,
1045            is_native,
1046            is_exported,
1047            opt_flags,
1048            ..
1049        } = stmt
1050        {
1051            // Native wrappers pass each Seq param straight to the underlying kernel (which takes
1052            // `&[i64]`), reading but never mutating it — so every Seq param is readonly-borrowed.
1053            // This makes the whole native call path zero-copy: a caller's `&[i64]` Seq param flows
1054            // through the wrapper to the kernel with no `LogosSeq` materialization.
1055            if *is_native {
1056                if crate::optimize::active_config()
1057                    .merged(opt_flags)
1058                    .is_on(Opt::Borrow)
1059                {
1060                    let indices: HashSet<usize> = params
1061                        .iter()
1062                        .enumerate()
1063                        .filter(|(_, (_, param_type))| is_vec_type_expr(param_type, interner))
1064                        .map(|(i, _)| i)
1065                        .collect();
1066                    if !indices.is_empty() {
1067                        borrow_params_map.insert(*name, indices);
1068                    }
1069                }
1070                continue;
1071            }
1072            // Skip exported, TCE, accumulator, and mutual TCE functions
1073            if *is_exported || mutual_tce_members.contains(name) {
1074                continue;
1075            }
1076            // Respect ## No Borrow / ## No Optimize annotations
1077            if !crate::optimize::active_config()
1078                .merged(opt_flags)
1079                .is_on(Opt::Borrow)
1080            {
1081                continue;
1082            }
1083            // Only DIRECT tail recursion conflicts with a borrowed param (TCE
1084            // reassigns it). A `Set/Let x = self(args); Return x` pair can keep
1085            // the borrow — pair-TCE yields to it in the `is_tce` gate below.
1086            if is_tail_recursive(*name, body) {
1087                continue;
1088            }
1089            if detect_accumulator_pattern(*name, body).is_some() {
1090                continue;
1091            }
1092            // Skip functions with escape blocks — raw Rust code may assume specific param types
1093            if body_contains_escape(body) {
1094                continue;
1095            }
1096            let indices: HashSet<usize> = params
1097                .iter()
1098                .enumerate()
1099                .filter(|(_, (sym, param_type))| {
1100                    readonly_params.is_readonly(*name, *sym)
1101                        && (is_vec_type_expr(param_type, interner)
1102                            || super::marshal::is_text_type(param_type, interner))
1103                })
1104                .map(|(i, _)| i)
1105                .collect();
1106            if !indices.is_empty() {
1107                let give_indices = collect_give_arg_indices(*name, stmts);
1108                let filtered: HashSet<usize> = indices.difference(&give_indices).copied().collect();
1109                if !filtered.is_empty() {
1110                    borrow_params_map.insert(*name, filtered);
1111                    crate::optimize::mark_fired(Opt::Borrow);
1112                }
1113            }
1114        }
1115    }
1116
1117    // Enum params that are only ever inspected or lent on are passed as `&T` (`codegen::lent`), under the same
1118    // gates as the sequence borrow above.
1119    let enum_eligible = |stmt: &Stmt| match stmt {
1120        Stmt::FunctionDef {
1121            name,
1122            body,
1123            is_native,
1124            is_exported,
1125            opt_flags,
1126            ..
1127        } => {
1128            !*is_native
1129                && !*is_exported
1130                && !mutual_tce_members.contains(name)
1131                && crate::optimize::active_config()
1132                    .merged(opt_flags)
1133                    .is_on(Opt::Borrow)
1134                && !is_tail_recursive(*name, body)
1135                && detect_accumulator_pattern(*name, body).is_none()
1136                && !body_contains_escape(body)
1137        }
1138        _ => false,
1139    };
1140    for (name, slots) in super::lent::enum_borrow_params(stmts, registry, interner, &enum_eligible)
1141    {
1142        borrow_params_map.entry(name).or_default().extend(slots);
1143        crate::optimize::mark_fired(Opt::Borrow);
1144    }
1145
1146    // Mutable borrow analysis: detect Seq params that are only mutated via SetIndex
1147    // (element-only, no Push/Pop) and returned. These get &mut [T] instead of owned Vec<T>.
1148    let mutable_borrow_params = MutableBorrowParams::analyze(stmts, &callgraph, type_env);
1149
1150    let mut mut_borrow_params_map: HashMap<Symbol, HashSet<usize>> = HashMap::new();
1151    for stmt in stmts {
1152        if let Stmt::FunctionDef {
1153            name,
1154            params,
1155            body,
1156            is_native,
1157            is_exported,
1158            opt_flags,
1159            ..
1160        } = stmt
1161        {
1162            if *is_native || *is_exported || mutual_tce_members.contains(name) {
1163                continue;
1164            }
1165            // Respect ## No Borrow / ## No Optimize annotations
1166            if !crate::optimize::active_config()
1167                .merged(opt_flags)
1168                .is_on(Opt::Borrow)
1169            {
1170                continue;
1171            }
1172            if is_tail_recursive(*name, body) || detect_accumulator_pattern(*name, body).is_some() {
1173                continue;
1174            }
1175            if body_contains_escape(body) {
1176                continue;
1177            }
1178            // Skip if already has readonly borrow params (readonly takes precedence)
1179            let readonly_indices = borrow_params_map.get(name).cloned().unwrap_or_default();
1180            let indices: HashSet<usize> = params
1181                .iter()
1182                .enumerate()
1183                .filter(|(i, (sym, param_type))| {
1184                    // Under value semantics this in-place lowering stays EXACT:
1185                    // every call site is the consuming `Set x to f(x, ...)` shape
1186                    // (enforced by `collect_incompatible_mut_borrow_callsites`)
1187                    // and the call site `cow()`s the handle first, so the
1188                    // callee's element writes land on a buffer no other live
1189                    // handle can observe.
1190                    mutable_borrow_params.is_mutable_borrow(*name, *sym)
1191                        && !readonly_indices.contains(i)
1192                        && is_vec_type_expr(param_type, interner)
1193                })
1194                .map(|(i, _)| i)
1195                .collect();
1196            if !indices.is_empty() {
1197                mut_borrow_params_map.insert(*name, indices);
1198                crate::optimize::mark_fired(Opt::Borrow);
1199            }
1200        }
1201    }
1202
1203    // `mutable` collection params (value semantics): passed by shared `&LogosSeq`/
1204    // `&LogosMap` so the callee's in-place mutation reaches the caller. Distinct
1205    // from the `&mut [T]` borrow opt (which has no `.push()`). Skip functions
1206    // already using the readonly borrow opt (mixed readonly+mutable is rare and
1207    // would clobber the single-slot call-site encoding).
1208    let mut value_mutable_params_map: HashMap<Symbol, HashSet<usize>> = HashMap::new();
1209    if crate::semantics::collections::value_semantics_enabled() {
1210        for stmt in stmts {
1211            if let Stmt::FunctionDef {
1212                name,
1213                params,
1214                is_native: false,
1215                ..
1216            } = stmt
1217            {
1218                let idx: HashSet<usize> = params
1219                    .iter()
1220                    .enumerate()
1221                    .filter(|(_, (_, ty))| matches!(ty, crate::ast::stmt::TypeExpr::Mutable { .. }))
1222                    .map(|(i, _)| i)
1223                    .collect();
1224                if !idx.is_empty() {
1225                    value_mutable_params_map.insert(*name, idx);
1226                }
1227            }
1228        }
1229    }
1230    crate::analysis::callgraph::install_lending_parameters(stmts);
1231
1232    // Pass 2: what is live after every statement of every body (backward dataflow), installed for the whole
1233    // emission so a statement may move a value it uses for the last time (OPT-1C, `flow`).
1234    let _liveness = super::flow::install(LivenessResult::analyze(stmts).into_statement_table());
1235
1236    // De-Rc Phase 4: functions whose every Return is a uniquely-owned fresh Seq
1237    // return `Vec<T>` instead of `LogosSeq<T>` — removing the per-call Rc
1238    // clone/borrow and unblocking de-Rc on the locals that capture the result
1239    // (`Set left to mergeSort(left)`). The mergesort allocation keystone.
1240    let mut vec_return_fns =
1241        collect_vec_return_fns(stmts, interner, &borrow_params_map, &mut_borrow_params_map);
1242    // Opt::TextSliceReturn — fns returning a contiguous sub-slice of a Text param lower to a borrowed
1243    // `&'a str` return (the trim family), when no caller lets the slice escape. The slice-builder shape
1244    // provably only READS the source param, so this pass DRIVES borrowing it: inject each slice fn's
1245    // source-param index into borrow_params_map so the signature takes `&'a str` and call sites pass
1246    // `&s` (no clone). Scoped to the recognized slice fns — no program-wide Text-borrow blast radius.
1247    let str_slice_return_fns =
1248        super::peephole::collect_str_slice_return_fns(stmts, interner, &borrow_params_map);
1249    // Opt::AsciiClassMask: pure Int->Bool classification predicates → their 256-bit membership masks.
1250    let ascii_masks = crate::optimize::ascii_class_masks(stmts, interner);
1251    for (f, &si) in &str_slice_return_fns {
1252        borrow_params_map.entry(*f).or_default().insert(si);
1253    }
1254    // Opt::ByteSliceReturn — fns returning a contiguous sub-slice of a `Seq of Int` param lower to a
1255    // borrowed `&'a [i64]` return (the bytes-trim family), same borrow-driving as TextSliceReturn.
1256    // Exclude them from vec-return so the borrowed-slice path (not an owned `Vec`) is authoritative.
1257    let byte_slice_return_fns =
1258        super::peephole::collect_byte_slice_return_fns(stmts, interner, &borrow_params_map);
1259    for (f, &si) in &byte_slice_return_fns {
1260        borrow_params_map.entry(*f).or_default().insert(si);
1261    }
1262    vec_return_fns.retain(|f| !byte_slice_return_fns.contains_key(f));
1263    // Both slice families return a BORROW, and a caller marshalling an argument at a borrow
1264    // position has to know that — otherwise it wraps an already-borrowed `&[T]` in `.borrow()`.
1265    super::expr::set_borrowed_return_fns(
1266        &str_slice_return_fns
1267            .keys()
1268            .chain(byte_slice_return_fns.keys())
1269            .copied()
1270            .collect(),
1271    );
1272    // Step 3b: functions returning a fixed-size buffer return `[T; N]` by value (a stack array). Disjoint
1273    // from vec-return (the array is the stricter, zero-heap representation) — exclude them from vec-return
1274    // so the array path is authoritative.
1275    let array_return_fns =
1276        super::affine_array::collect_array_return_fns(stmts, &borrow_params_map, interner);
1277    vec_return_fns.retain(|f| !array_return_fns.contains_key(f));
1278    // Fixed-array borrow-parameter propagation: a read-borrow param passed only fixed `[T; N]` arrays
1279    // becomes `&[T; N]` (LLVM elides its constant-index bounds checks).
1280    let fixed_array_param_map = fixed_array_params(
1281        stmts,
1282        &borrow_params_map,
1283        &mut_borrow_params_map,
1284        &vec_return_fns,
1285        &array_return_fns,
1286        interner,
1287    );
1288
1289    // Build function return type map for variable type inference at call sites.
1290    // Phase 4: a return-type-de-Rc'd function returns `Vec<T>`, so callers infer
1291    // the result var as `Vec` (not `LogosSeq`) — keeping its uses Rc-free. Step 3b:
1292    // an array-return function's callers infer the result var as `[T; N]`.
1293    let mut fn_returns_map: HashMap<Symbol, String> = stmts
1294        .iter()
1295        .filter_map(|s| {
1296            if let Stmt::FunctionDef {
1297                name,
1298                return_type: Some(rt),
1299                ..
1300            } = s
1301            {
1302                let ty = codegen_type_expr(rt, interner);
1303                let ty = if let Some(info) = array_return_fns.get(name) {
1304                    format!("[{}; {}]", info.elem_ty, info.len)
1305                } else if vec_return_fns.contains(name) {
1306                    ty.replacen("LogosSeq<", "Vec<", 1)
1307                } else {
1308                    ty
1309                };
1310                Some((*name, ty))
1311            } else {
1312                None
1313            }
1314        })
1315        .collect();
1316
1317    // Overflow-promoting return: the whole-program set of `Int`-returning functions whose value can
1318    // exceed i64 (a running product/power, or a call to another such function). Their signature
1319    // becomes `-> LogosInt`, and a caller's binding of the result is itself promotable. Record the
1320    // `|__bigint` sentinel so a call result classifies as Int (exact-arith path) yet stores LogosInt.
1321    // Selective higher-order-overflow analysis: a SCALAR exact-HOF (`apply(f, x)` — Int/Nat return,
1322    // a `fn`-typed param, no seq param) exactifies its fn-param + int-params + return to the promoting
1323    // `LogosInt`, so an overflowing closure body promotes to a bignum == the VM. Folded into
1324    // `bigint_fns` (its return becomes `-> LogosInt`) AND threaded to expr codegen for the call-site
1325    // half (exact closure args + integer-arg promotion). Seq-HOFs are excluded, so `map`/`fold`/
1326    // `reduceSeq` closures stay `i64` — no regression. Mirrors AST-C's `is_exact_hof`. The set is
1327    // call-site-refined (see `exact_hof_fns`): only HOFs receiving inline closures at every site
1328    // exactify, and a HOF whose every site is provably within `i64` keeps plain `i64` signatures.
1329    let exact_hofs = promo.exact_hofs.clone();
1330    let bigint_fns = promo.bigint_fns.clone();
1331    let bigint_fields = promo.bigint_fields.clone();
1332    let exact_result_fns = promo.exact_result_fns.clone();
1333    let _ = &bigint_fields;
1334    for f in &bigint_fns {
1335        fn_returns_map.insert(*f, "i64|__bigint".to_string());
1336    }
1337    // A function the exact extension reaches returns the compiled exact value, whatever its
1338    // declared type.
1339    for f in fn_returns_map.keys().copied().collect::<Vec<_>>() {
1340        if super::tower::returns(f) {
1341            fn_returns_map.insert(f, super::tower::VALUE.to_string());
1342        }
1343    }
1344    // Record the bignum-returning set for the expression codegen, so an INLINE call to such a
1345    // function is detected as a promoted `LogosInt` operand and routed through the exact helper
1346    // (a bare `LogosInt <op> LogosInt` has no operator impl — see `mentions_bigint_var`).
1347    // A program's OWN function shadows a stdlib name of the same spelling: install its declared
1348    // return types BEFORE anything is emitted, so a call's result type comes from the program's
1349    // declaration rather than math.lg's `-> Real` name list.
1350    super::expr::set_fn_return_types(&fn_returns_map);
1351    super::expr::set_bigint_returning_fns(&bigint_fns);
1352    super::expr::set_exact_hofs(&exact_hofs);
1353    super::instantiation::install(stmts, registry, interner);
1354
1355    // Whole-program function → parameter Rust types, so a call passing an integer to an `f64`
1356    // (`Real`) parameter coerces with `as f64` at the emit — matching the interpreter/VM, which
1357    // coerce int→Real at the call boundary. Without it a Real-parameter function called with an
1358    // integer literal (`sin(0)`, `cConj(3, 4)`) fails to type-check on the AOT tier while passing
1359    // on tree-walker/VM, a cross-tier divergence. Native functions are excluded (their params bind
1360    // to hand-written host signatures, not this coercion path). An exact-HOF's parameter types are
1361    // EXACTIFIED (`i64` → `LogosInt`, inside `impl Fn(..)` too) so the call-site half promotes a
1362    // closure / integer argument to the exactified parameter.
1363    let fn_param_types_map: HashMap<Symbol, Vec<String>> = stmts
1364        .iter()
1365        .filter_map(|s| match s {
1366            Stmt::FunctionDef {
1367                name,
1368                params,
1369                is_native: false,
1370                ..
1371            } => {
1372                let is_exact = exact_hofs.contains(name);
1373                Some((
1374                    *name,
1375                    params
1376                        .iter()
1377                        .map(|(_, ty)| {
1378                            let t = codegen_type_expr(ty, interner);
1379                            if is_exact {
1380                                exactify_rust_int_type(&t)
1381                            } else {
1382                                t
1383                            }
1384                        })
1385                        .collect(),
1386                ))
1387            }
1388            _ => None,
1389        })
1390        .collect();
1391    super::expr::set_fn_param_types(&fn_param_types_map);
1392
1393    // O1 borrow hoisting: analyze the oracle ONCE on this exact statement
1394    // slice (loop alias snapshots are keyed by Stmt address; codegen walks
1395    // the same Stmts, so the pointers match). One forward pass with bounded
1396    // per-loop fixpoints; gated for very large programs and by LOGOS_HOIST=0.
1397    const MAX_HOIST_ORACLE_STMTS: usize = 5_000;
1398    let oracle: Option<std::rc::Rc<crate::optimize::OracleFacts>> =
1399        if super::hoist::hoisting_disabled() || stmts.len() > MAX_HOIST_ORACLE_STMTS {
1400            None
1401        } else {
1402            Some(std::rc::Rc::new(
1403                crate::optimize::oracle_analyze_with_entry_guards(stmts, interner),
1404            ))
1405        };
1406
1407    // The range oracle: the whole program's range facts, computed on this exact
1408    // statement slice — the same one codegen walks, so expression addresses match
1409    // — or the borrow-hoist `oracle` above when that exists. It answers whether an
1410    // Int op stays in i64 (`oracle_proves_int_op_in_range`) and whether an access
1411    // names an item (`range_proves_index`), with what the emitted program's own
1412    // guards establish recorded in it (`mark_index_in_range`). Borrow-hoisting /
1413    // BCE / fast-div read the `ExprCtx` oracle. Installed for this compile and
1414    // removed when it ends, so a freed arena's reused addresses never meet it.
1415    let range_oracle: Option<std::rc::Rc<crate::optimize::OracleFacts>> =
1416        oracle.clone().or_else(|| {
1417            (stmts.len() <= MAX_HOIST_ORACLE_STMTS).then(|| {
1418                std::rc::Rc::new(crate::optimize::oracle_analyze_with_entry_guards(
1419                    stmts, interner,
1420                ))
1421            })
1422        });
1423    let _range_oracle_scope = super::expr::install_range_oracle(range_oracle);
1424    let _emission_facts = crate::optimize::facts::scope();
1425
1426    let aot_compiled = crate::analysis::callgraph::aot_compiled_functions(stmts, interner);
1427    // Phase 32/38: Emit function definitions before main
1428    for (top_idx, stmt) in stmts.iter().enumerate() {
1429        let fn_emit_start = line_count(&output) + 1;
1430        if let Stmt::FunctionDef {
1431            name,
1432            params,
1433            generics,
1434            body,
1435            return_type,
1436            is_native,
1437            native_path,
1438            is_exported,
1439            export_target,
1440            opt_flags,
1441        } = stmt
1442        {
1443            // ★ A SERVER BINARY CARRIES NO DOCUMENT CALLS. The browser half of a page's lowering
1444            // (`__render_`, `__act_`, `__mount_`, …) and every function that calls into it or into a
1445            // browser-only builtin need a live document, which this tier does not have; a server
1446            // render (`__serve_<C>`, `__html_<C>`) and the vdom.lg it draws with are ordinary code
1447            // and stay (`callgraph::aot_compiled_functions`).
1448            if !aot_compiled.contains(name) {
1449                continue;
1450            }
1451            if mutual_tce_members.contains(name) {
1452                // Part of a mutual pair — emit merged function when we see the first member
1453                if !mutual_tce_emitted.contains(name) {
1454                    // Find the pair this function belongs to
1455                    if let Some((a, b)) = mutual_tce_pairs
1456                        .iter()
1457                        .find(|(a, b)| *a == *name || *b == *name)
1458                    {
1459                        output.push_str(&codegen_mutual_tce_pair(
1460                            *a,
1461                            *b,
1462                            stmts,
1463                            interner,
1464                            &lww_fields,
1465                            &mv_fields,
1466                            &async_functions,
1467                            &boxed_fields,
1468                            registry,
1469                            type_env,
1470                        ));
1471                        mutual_tce_emitted.insert(*a);
1472                        mutual_tce_emitted.insert(*b);
1473                    }
1474                }
1475                // Skip individual emission — already emitted as part of merged pair
1476            } else {
1477                output.push_str(&codegen_function_def(
1478                    *name,
1479                    generics,
1480                    params,
1481                    body,
1482                    stmts,
1483                    return_type.as_ref().copied(),
1484                    *is_native,
1485                    *native_path,
1486                    *is_exported,
1487                    *export_target,
1488                    interner,
1489                    &lww_fields,
1490                    &mv_fields,
1491                    &async_functions,
1492                    &boxed_fields,
1493                    registry,
1494                    &pure_functions,
1495                    type_env,
1496                    &borrow_params_map,
1497                    &mut_borrow_params_map,
1498                    &value_mutable_params_map,
1499                    opt_flags,
1500                    &fn_returns_map,
1501                    &vec_return_fns,
1502                    &str_slice_return_fns,
1503                    &byte_slice_return_fns,
1504                    &array_return_fns,
1505                    &fixed_array_param_map,
1506                    oracle.as_ref(),
1507                    &bigint_fns,
1508                    &exact_hofs,
1509                    &exact_result_fns,
1510                    &ascii_masks,
1511                ));
1512            }
1513            if let Some((spans, _)) = mapping {
1514                record_emitted_lines(
1515                    &output,
1516                    fn_emit_start,
1517                    spans.get(top_idx).copied(),
1518                    &mut line_records,
1519                );
1520            }
1521        }
1522    }
1523
1524    // Universal ABI: Emit accessor/free functions for reference types in C exports
1525    if c_exports_exist {
1526        let ref_types = collect_c_export_reference_types(stmts, interner, registry);
1527        for ref_ty in &ref_types {
1528            output.push_str(&codegen_c_accessors(ref_ty, interner, registry));
1529        }
1530    }
1531
1532    // Grand Challenge: Collect variables that need to be mutable
1533    let main_stmts: Vec<&Stmt> = stmts
1534        .iter()
1535        .filter(|s| !matches!(s, Stmt::FunctionDef { .. }))
1536        .collect();
1537    let mut main_mutable_vars = HashSet::new();
1538    for stmt in &main_stmts {
1539        collect_mutable_vars_stmt(stmt, &mut main_mutable_vars);
1540    }
1541
1542    // OPT: Detect single-char text variables (emit u8 instead of String)
1543    let single_char_vars = collect_single_char_text_vars(stmts, interner);
1544
1545    // Main function
1546    // Phase 51: Use async main when async operations are present
1547    if replay {
1548        // Mode B: the main task and every task it launches run on the replay executor, under a
1549        // current-thread host reactor for any real I/O a task awaits.
1550        writeln!(output, "fn main() {{").unwrap();
1551        emit_logos_panic_hook(&mut output, false);
1552        writeln!(
1553            output,
1554            "    let _logos_outcome = std::thread::Builder::new()"
1555        )
1556        .unwrap();
1557        writeln!(output, "        .stack_size(67_108_864)").unwrap();
1558        writeln!(output, "        .spawn(|| {{").unwrap();
1559        writeln!(
1560            output,
1561            "            tokio::runtime::Builder::new_current_thread()"
1562        )
1563        .unwrap();
1564        writeln!(output, "                .enable_all()").unwrap();
1565        writeln!(output, "                .build()").unwrap();
1566        writeln!(
1567            output,
1568            "                .expect(\"the LOGOS runtime starts\")"
1569        )
1570        .unwrap();
1571        writeln!(
1572            output,
1573            "                .block_on(logicaffeine_system::replay::run(_logos_main()))"
1574        )
1575        .unwrap();
1576        writeln!(output, "        }})").unwrap();
1577        writeln!(output, "        .unwrap().join();").unwrap();
1578        writeln!(output, "    logicaffeine_system::io::flush_stdout();").unwrap();
1579        writeln!(output, "    match _logos_outcome {{").unwrap();
1580        writeln!(output, "        Ok(Ok(())) => {{}}").unwrap();
1581        writeln!(output, "        Ok(Err(failure)) => {{").unwrap();
1582        writeln!(output, "            if failure == logicaffeine_system::replay::Failure::Deadlock {{ eprintln!(\"{{}}\", failure); }}").unwrap();
1583        writeln!(output, "            std::process::exit(1);").unwrap();
1584        writeln!(output, "        }}").unwrap();
1585        writeln!(output, "        Err(_) => std::process::exit(1),").unwrap();
1586        writeln!(output, "    }}").unwrap();
1587        writeln!(output, "}}").unwrap();
1588        writeln!(output, "async fn _logos_main() {{").unwrap();
1589    } else if requires_async(stmts) {
1590        writeln!(output, "#[tokio::main]").unwrap();
1591        writeln!(output, "async fn main() {{").unwrap();
1592        emit_logos_panic_hook(&mut output, true);
1593    } else {
1594        // `Main` runs on a deep stack of its own, switched to on the thread that started the program: a waiting
1595        // second thread would put every `malloc` and `free` on the C library's locked path. A runtime failure ends
1596        // the program in the hook, one message and exit status 1, as on every tier.
1597        writeln!(output, "fn main() {{").unwrap();
1598        emit_logos_panic_hook(&mut output, true);
1599        writeln!(output, "    logicaffeine_system::stack::run_main(_logos_main);").unwrap();
1600        writeln!(output, "}}").unwrap();
1601        writeln!(output, "fn _logos_main() {{").unwrap();
1602    }
1603    // Phase 53: Inject VFS when file operations or persistence is used
1604    if requires_vfs(stmts) {
1605        writeln!(output, "    let vfs: std::sync::Arc<dyn logicaffeine_system::fs::Vfs + Send + Sync> = std::sync::Arc::from(logicaffeine_system::fs::get_platform_vfs());").unwrap();
1606    }
1607    let mut main_ctx = RefinementContext::from_type_env(type_env);
1608    // Opt::StrengthReducePow2: the Main body's always-non-negative variables (walking `stmts` skips
1609    // FunctionDef bodies, so this is exactly Main's set). Per-function registration does not cover Main.
1610    super::expr::set_nonneg_vars(super::expr::collect_always_nonneg(stmts));
1611    // SIMD-reduce lifter needs the program's function bodies (the Main body has the transcendental
1612    // accumulator loops; per-function registration in codegen_function_def does not cover Main).
1613    main_ctx.set_simd_fns(super::simd_reduce::build_fn_map(stmts));
1614    // O1 borrow hoisting: seed the oracle (pointer-keyed loop alias
1615    // snapshots must match the Stmts codegen walks).
1616    if let Some(o) = &oracle {
1617        main_ctx.set_oracle(o.clone());
1618    }
1619    // Local Vec optimization: detect which collection vars escape main
1620    let main_escaping = collect_escaping_collection_vars(stmts);
1621    main_ctx.set_escaping_vars(main_escaping);
1622    // Overflow-promoting Int bindings: which integer vars must store `LogosInt`.
1623    // A LOCAL and a FIELD must be decided from the SAME answer to "can this exceed i64", or a
1624    // decoder's local is a `LogosInt` while the record it fills holds an `i64`. `promo_fns` is the
1625    // fixpoint's own seed — the set `bigint_struct_fields` was computed against.
1626    let promotable_vars = crate::codegen::bigint_promote::promotable_int_vars(
1627        stmts,
1628        &promo.promo_fns,
1629        &promo.bigint_fields,
1630        &HashSet::new(),
1631    );
1632    // Opt::WideAccumulator: Main's bounded counting accumulators safe to widen to i128. A qualifying
1633    // loop bound must be i64, so pass the promotable/bignum set to reject a bignum-bounded loop.
1634    super::expr::set_wide_acc(crate::codegen::stmt::collect_wide_accumulators(
1635        stmts,
1636        &promotable_vars,
1637        &pure_functions,
1638    ));
1639    main_ctx.set_promotable_candidates(promotable_vars);
1640    let main_joins =
1641        super::rational::joins(
1642            stmts,
1643            &HashSet::new(),
1644            super::rational::Typing { interner, variable_types: main_ctx.get_variable_types(), registry },
1645        );
1646    main_ctx.set_rational_joins(main_joins);
1647    // OPT: Register single-char text vars as u8 type for optimized codegen
1648    for sym in &single_char_vars {
1649        main_ctx.register_variable_type(*sym, "__single_char_u8".to_string());
1650    }
1651    // O3: scalarize fixed-size, non-escaping Seqs to `[T; N]` arrays (Main only).
1652    let scalarizable_seqs = collect_scalarizable_seqs(stmts, interner);
1653    // AoS interleaving: fuse co-indexed same-type groups (round-robin pushes)
1654    // into one `[[T; W]; N]` backing array reusing the first member's symbol, so
1655    // per-entity fields are memory-adjacent (C's struct-array layout) and LLVM
1656    // packs them instead of gathering separate arrays with shuffles. Members are
1657    // registered as AoS columns INSTEAD of plain `[T; N]` scalarized arrays.
1658    let aos_groups = collect_interleaved_groups(stmts, &scalarizable_seqs, interner);
1659    let aos_names = RustNames::new(interner);
1660    let mut aos_member_syms: HashSet<Symbol> = HashSet::new();
1661    for group in &aos_groups {
1662        let width = group.members.len();
1663        // The fused backing array reuses the first member's emitted identifier.
1664        // RustNames is a deterministic resolve+sanitize, so this matches the name
1665        // every access site produces for that symbol.
1666        let backing = aos_names.ident(group.members[0]);
1667        for (col, m) in group.members.iter().enumerate() {
1668            main_ctx.register_variable_type(
1669                *m,
1670                format!(
1671                    "__aos:{}:{}:{}:{}:{}",
1672                    backing, col, width, group.len, group.elem_ty
1673                ),
1674            );
1675            main_ctx.init_array_fill(*m);
1676            aos_member_syms.insert(*m);
1677        }
1678    }
1679    for (sym, info) in &scalarizable_seqs {
1680        if aos_member_syms.contains(sym) {
1681            continue; // handled as an AoS column above
1682        }
1683        main_ctx.register_variable_type(*sym, format!("[{}; {}]", info.elem_ty, info.len));
1684        main_ctx.init_array_fill(*sym);
1685    }
1686    // Step 3b: register the `[T; N]` type for Main's result variables bound to an array-return fn (the
1687    // per-function registration in `codegen_function_def` does not cover the top-level Main body).
1688    for (sym, ty) in super::affine_array::array_var_types(stmts, None, &array_return_fns) {
1689        let name = interner.resolve(sym).to_string();
1690        let mut syms: HashSet<Symbol> = HashSet::new();
1691        collect_named_syms(stmts, &name, interner, &mut syms);
1692        for s in syms {
1693            main_ctx.register_variable_type(s, ty.clone());
1694        }
1695    }
1696    // O2 de-Rc: Seqs proven to never need reference semantics → plain Vec<T>
1697    // (no Rc/RefCell). A var already scalarized to `[T; N]` (O3) wins — exclude it.
1698    let mut de_rc_seqs = collect_de_rc_seqs(
1699        stmts,
1700        interner,
1701        &borrow_params_map,
1702        &mut_borrow_params_map,
1703        &vec_return_fns,
1704        false,
1705    );
1706    for (sym, _) in &scalarizable_seqs {
1707        // A `[T; N]`-scalarized var already gets the win — it preempts de-Rc here.
1708        if de_rc_seqs.remove(sym) {
1709            crate::optimize::mark_preempted(Opt::Scalarize, Opt::Unbox);
1710        }
1711    }
1712    // Straight-line-push fixed buffers in Main → `[T; K]` (borrow-aware — the scalarizer disqualifies any
1713    // call-arg, even a read-only borrow, so Main's small input buffers stayed heap Vecs). The O3 `Let`/
1714    // `Push` handlers emit the stack array + `buf[k]=expr` fills.
1715    let main_sl = super::affine_array::detect_straightline_buffers(
1716        stmts,
1717        &de_rc_seqs,
1718        &borrow_params_map,
1719        interner,
1720    );
1721    for (sym, (elem_ty, len)) in &main_sl {
1722        let ty = format!("[{}; {}]", elem_ty, len);
1723        de_rc_seqs.remove(sym);
1724        let name = interner.resolve(*sym).to_string();
1725        let mut syms: HashSet<Symbol> = HashSet::new();
1726        collect_named_syms(stmts, &name, interner, &mut syms);
1727        for s in syms {
1728            main_ctx.register_variable_type(s, ty.clone());
1729        }
1730    }
1731    // Append-only worklist → pre-sized buffer + register tail (BFS frontier).
1732    let main_worklists = super::worklist::detect_worklists(stmts, &de_rc_seqs, interner);
1733    // Affine read-only array → delete it, substitute the closed form at reads
1734    // (CSR offset array `adjStarts[v] == v*5` becomes C's `v*5` shift). An O3
1735    // scalarized (`[T;N]`) or worklist symbol is already claimed — exclude it.
1736    let mut main_affine = super::affine_array::detect_affine_arrays(stmts, &de_rc_seqs, interner);
1737    main_affine.retain(|sym, _| {
1738        // A scalarized sequence is already claimed — Scalarize preempts Affine.
1739        if scalarizable_seqs.contains_key(sym) {
1740            crate::optimize::mark_preempted(Opt::Scalarize, Opt::Affine);
1741            return false;
1742        }
1743        !main_worklists.contains_key(sym)
1744    });
1745    for (sym, info) in &main_affine {
1746        main_ctx.register_variable_type(
1747            *sym,
1748            format!(
1749                "__affine_array:{}:{}:{}",
1750                info.coeff, info.offset, info.trip
1751            ),
1752        );
1753    }
1754    // i64→i32 element-width narrowing (gated by LOGOS_NARROW, default off): a
1755    // `Seq of Int` whose every value provably fits i32 is stored as `Vec<i32>`.
1756    // Exclude deleted (affine) and worklist sequences — they are not plain Vecs.
1757    let main_narrowed = narrow_seqs(stmts, &de_rc_seqs, &main_affine, &main_worklists, interner);
1758    for sym in main_narrowed.keys() {
1759        // Register the i32 element type so the borrow-hoist and indexed-read
1760        // dispatch treat the buffer as `&[i32]`/`Vec<i32>`; the decl paths emit
1761        // the matching `Vec<i32>` and the access sites convert.
1762        main_ctx.register_variable_type(*sym, "Vec<i32>".to_string());
1763    }
1764    let main_bits = bitpack_seqs(
1765        stmts,
1766        &de_rc_seqs,
1767        &|s| main_worklists.contains_key(&s) || main_affine.contains_key(&s),
1768        interner,
1769    );
1770    for sym in &main_bits {
1771        main_ctx.register_variable_type(*sym, "LogosBits".to_string());
1772    }
1773    main_ctx.set_de_rc_vars(de_rc_seqs);
1774    main_ctx.set_worklists(main_worklists);
1775    main_ctx.set_affine_arrays(main_affine);
1776    main_ctx.set_narrowed(main_narrowed);
1777    main_ctx.set_bitpacked(main_bits);
1778    // Non-aliased local `Map of Int to Int` → specialized `LogosI64Map`, or the
1779    // keys-only `LogosI64Set` when the value is never read.
1780    let main_i64 = super::i64_map::detect_i64_maps(stmts, interner);
1781    // Dense tier: maps whose key domain the oracle proved bounded within their
1782    // capacity hint lower to a direct-addressed flat array (no hashing/probing).
1783    if let Some(o) = oracle.as_deref() {
1784        let dense = super::i64_map::detect_dense_i64_maps(&main_i64, o, interner);
1785        let (i32m, i32s) = super::i64_map::detect_i32_maps(&main_i64, &dense, o);
1786        main_ctx.set_dense_i64(dense);
1787        main_ctx.set_i32_maps(i32m, i32s);
1788    }
1789    main_ctx.set_i64_sets(main_i64.sets);
1790    main_ctx.set_i64_maps(main_i64.maps);
1791    // Pre-size push-built Vecs that a later counted loop index-reads to a bound.
1792    // A deleted affine array must not also be pre-sized (its declaration is gone).
1793    let mut main_presize = super::peephole::detect_vec_presize(stmts, interner);
1794    main_presize.retain(|sym, _| main_ctx.affine_array(*sym).is_none());
1795    main_ctx.set_vec_presize(main_presize);
1796    // Loop-invariant positive divisors → precomputed `LogosDivU64` magic multiply.
1797    main_ctx.set_fast_div(super::fast_div::detect_fast_div(
1798        stmts,
1799        oracle.as_deref(),
1800        interner,
1801    ));
1802    // Register function param-role info on main context for call-site lowering:
1803    // readonly borrow (`&[T]`), element-mutating borrow (`&mut [T]`), and
1804    // value-semantics `mutable` collection (`&LogosSeq`/`&LogosMap`). A function
1805    // can play several at once, so all its roles pack into ONE slot (else the last
1806    // registered would clobber the rest and every call site mis-lower the others).
1807    register_fn_roles(
1808        &mut main_ctx,
1809        &borrow_params_map,
1810        &mut_borrow_params_map,
1811        &value_mutable_params_map,
1812    );
1813    // Register function return types for variable type inference at call sites
1814    for (fn_sym, rt_str) in &fn_returns_map {
1815        main_ctx.register_fn_return(*fn_sym, rt_str.clone());
1816    }
1817    let mut main_synced_vars = HashSet::new(); // Phase 52: Track synced variables in main
1818                                               // Phase 56: Pre-scan for Mount+Sync combinations
1819    let main_var_caps = analyze_variable_capabilities(stmts, interner);
1820    {
1821        let stmt_refs: Vec<&Stmt> = stmts.iter().collect();
1822        let mut i = 0;
1823        while i < stmt_refs.len() {
1824            // Skip function definitions - they're already emitted above
1825            if matches!(stmt_refs[i], Stmt::FunctionDef { .. }) {
1826                i += 1;
1827                continue;
1828            }
1829            // An affine read-only array is deleted entirely — emit no declaration.
1830            // (Its build push is suppressed and every read substitutes the closed
1831            // form.) Skip the decl here, before any peephole pattern can
1832            // re-materialize it as a pre-sized/with_capacity Vec.
1833            if let Stmt::Let { var, value, .. } = stmt_refs[i] {
1834                if matches!(value, Expr::New { .. }) && main_ctx.affine_array(*var).is_some() {
1835                    i += 1;
1836                    continue;
1837                }
1838            }
1839            // Statement-sequence peepholes (naive-search, cascade fold, presize,
1840            // for-range, swap, …) — one shared chain for every block context.
1841            if let Some((code, skip)) = super::peephole::try_block_peepholes(
1842                &stmt_refs,
1843                i,
1844                interner,
1845                1,
1846                &main_mutable_vars,
1847                &mut main_ctx,
1848                &lww_fields,
1849                &mv_fields,
1850                &mut main_synced_vars,
1851                &main_var_caps,
1852                &async_functions,
1853                &main_pipe_vars,
1854                &boxed_fields,
1855                registry,
1856                type_env,
1857            ) {
1858                let emit_start = line_count(&output) + 1;
1859                output.push_str(&code);
1860                if let Some((spans, _)) = mapping {
1861                    // A peephole fuses statements i..=i+skip: map its lines to
1862                    // the merged span of everything it consumed.
1863                    let merged = match (spans.get(i), spans.get(i + skip)) {
1864                        (Some(a), Some(b)) if a.start < b.end => {
1865                            Some(LogosSpan::new(a.start, b.end))
1866                        }
1867                        (Some(a), _) => Some(*a),
1868                        _ => None,
1869                    };
1870                    record_emitted_lines(&output, emit_start, merged, &mut line_records);
1871                }
1872                i += 1 + skip;
1873                continue;
1874            }
1875            let emit_start = line_count(&output) + 1;
1876            output.push_str(&codegen_stmt(
1877                stmt_refs[i],
1878                interner,
1879                1,
1880                &main_mutable_vars,
1881                &mut main_ctx,
1882                &lww_fields,
1883                &mv_fields,
1884                &mut main_synced_vars,
1885                &main_var_caps,
1886                &async_functions,
1887                &main_pipe_vars,
1888                &boxed_fields,
1889                registry,
1890                type_env,
1891            ));
1892            if let Some((spans, _)) = mapping {
1893                record_emitted_lines(
1894                    &output,
1895                    emit_start,
1896                    spans.get(i).copied(),
1897                    &mut line_records,
1898                );
1899            }
1900            i += 1;
1901        }
1902    }
1903    writeln!(output, "}}").unwrap();
1904
1905    let map = mapping.map(|(spans, logos_source)| {
1906        let mut builder = SourceMapBuilder::new(logos_source);
1907        for (line, span) in line_records {
1908            builder.record_line_at(line, span);
1909        }
1910        record_var_origins(stmts, spans, interner, &mut builder);
1911        builder.build()
1912    });
1913    (output, map)
1914}
1915
1916/// Newlines emitted so far — brackets each statement's generated line range.
1917fn line_count(s: &str) -> u32 {
1918    s.bytes().filter(|&b| b == b'\n').count() as u32
1919}
1920
1921/// Map every line an emission produced (`start..=` the current line) to the
1922/// statement's span. Zero-width spans are prelude sentinels — skipped, so
1923/// prelude-generated code never claims user-source positions.
1924fn record_emitted_lines(
1925    output: &str,
1926    start_line: u32,
1927    span: Option<LogosSpan>,
1928    records: &mut Vec<(u32, LogosSpan)>,
1929) {
1930    let Some(span) = span else { return };
1931    if span.start >= span.end {
1932        return;
1933    }
1934    let mut end_line = line_count(output);
1935    if !output.ends_with('\n') {
1936        end_line += 1;
1937    }
1938    for line in start_line..=end_line.max(start_line) {
1939        records.push((line, span));
1940    }
1941}
1942
1943/// Ownership-role priority: when one variable plays several roles, the move
1944/// is what a borrow-check error will be about.
1945fn role_rank(role: OwnershipRole) -> u8 {
1946    match role {
1947        // The move itself: E0382 phrasing hangs off it.
1948        OwnershipRole::GiveObject => 7,
1949        // Zone membership is structural — E0597 escape phrasing needs it even
1950        // when the variable is also shown or set inside the zone.
1951        OwnershipRole::ZoneLocal => 6,
1952        OwnershipRole::ShowObject => 5,
1953        OwnershipRole::SetTarget => 4,
1954        OwnershipRole::GiveRecipient => 3,
1955        OwnershipRole::ShowRecipient => 2,
1956        OwnershipRole::LetBinding => 1,
1957    }
1958}
1959
1960/// Walk the program recording each variable's Rust name → LOGOS origin.
1961/// Nested statements attribute to their containing top-level statement's
1962/// span; higher-priority roles win when a variable plays several.
1963fn record_var_origins(
1964    stmts: &[Stmt],
1965    stmt_spans: &[LogosSpan],
1966    interner: &Interner,
1967    builder: &mut SourceMapBuilder,
1968) {
1969    use std::collections::HashMap as Map;
1970    let mut best: Map<String, (u8, Symbol, LogosSpan, OwnershipRole)> = Map::new();
1971
1972    fn ident_of(expr: &Expr, interner: &Interner) -> Option<(String, Symbol)> {
1973        if let Expr::Identifier(sym) = expr {
1974            Some((super::escape_rust_ident(interner.resolve(*sym)), *sym))
1975        } else {
1976            None
1977        }
1978    }
1979
1980    fn note(
1981        best: &mut Map<String, (u8, Symbol, LogosSpan, OwnershipRole)>,
1982        name: String,
1983        sym: Symbol,
1984        span: LogosSpan,
1985        role: OwnershipRole,
1986    ) {
1987        let rank = role_rank(role);
1988        match best.get(&name) {
1989            Some((existing, ..)) if *existing >= rank => {}
1990            _ => {
1991                best.insert(name, (rank, sym, span, role));
1992            }
1993        }
1994    }
1995
1996    fn walk(
1997        stmts: &[Stmt],
1998        span: LogosSpan,
1999        in_zone: bool,
2000        interner: &Interner,
2001        best: &mut Map<String, (u8, Symbol, LogosSpan, OwnershipRole)>,
2002    ) {
2003        for stmt in stmts {
2004            match stmt {
2005                Stmt::Let { var, .. } => {
2006                    let role = if in_zone {
2007                        OwnershipRole::ZoneLocal
2008                    } else {
2009                        OwnershipRole::LetBinding
2010                    };
2011                    let name = super::escape_rust_ident(interner.resolve(*var));
2012                    note(best, name, *var, span, role);
2013                }
2014                Stmt::Set { target, .. } => {
2015                    let name = super::escape_rust_ident(interner.resolve(*target));
2016                    note(best, name, *target, span, OwnershipRole::SetTarget);
2017                }
2018                Stmt::Give { object, recipient } => {
2019                    if let Some((name, sym)) = ident_of(object, interner) {
2020                        note(best, name, sym, span, OwnershipRole::GiveObject);
2021                    }
2022                    if let Some((name, sym)) = ident_of(recipient, interner) {
2023                        note(best, name, sym, span, OwnershipRole::GiveRecipient);
2024                    }
2025                }
2026                Stmt::Show { object, recipient } => {
2027                    if let Some((name, sym)) = ident_of(object, interner) {
2028                        note(best, name, sym, span, OwnershipRole::ShowObject);
2029                    }
2030                    if let Some((name, sym)) = ident_of(recipient, interner) {
2031                        note(best, name, sym, span, OwnershipRole::ShowRecipient);
2032                    }
2033                }
2034                Stmt::Zone { body, .. } => walk(body, span, true, interner, best),
2035                Stmt::If {
2036                    then_block,
2037                    else_block,
2038                    ..
2039                } => {
2040                    walk(then_block, span, in_zone, interner, best);
2041                    if let Some(else_block) = else_block {
2042                        walk(else_block, span, in_zone, interner, best);
2043                    }
2044                }
2045                Stmt::While { body, .. } => walk(body, span, in_zone, interner, best),
2046                Stmt::Repeat { body, .. } => walk(body, span, in_zone, interner, best),
2047                Stmt::FunctionDef { body, .. } => walk(body, span, in_zone, interner, best),
2048                _ => {}
2049            }
2050        }
2051    }
2052
2053    for (i, stmt) in stmts.iter().enumerate() {
2054        let Some(span) = stmt_spans.get(i).copied() else {
2055            continue;
2056        };
2057        if span.start >= span.end {
2058            continue;
2059        }
2060        walk(std::slice::from_ref(stmt), span, false, interner, &mut best);
2061    }
2062
2063    for (name, (_, sym, span, role)) in best {
2064        builder.record_var(&name, sym, span, role);
2065    }
2066}
2067
2068/// Exactify a codegen'd Rust type's integer parts to the overflow-promoting `LogosInt` — a bare
2069/// `i64` becomes `LogosInt`, and the `i64`s inside an `impl Fn(..) -> ..` become `LogosInt` too
2070/// (scalar exact-HOFs only reach here, so an `impl Fn`'s integer positions are the only `i64`s).
2071/// Any other type is unchanged. The call-site half of the selective higher-order-overflow analysis
2072/// (`exact_hof_fns`) uses this to type a closure/integer argument to the exactified parameter.
2073fn exactify_rust_int_type(t: &str) -> String {
2074    if t == "i64" {
2075        "logicaffeine_data::LogosInt".to_string()
2076    } else if t.starts_with("impl Fn") {
2077        t.replace("i64", "logicaffeine_data::LogosInt")
2078    } else if let Some(rest) = t.strip_prefix("Result<i64,") {
2079        // ★ AN ANSWER'S PAYLOAD IS PART OF THE ANSWER. `jsonInt(v) -> Result of Int and Text`
2080        // hands back a number read from a JSON document, which json.lg stores as a bignum because
2081        // a document may carry one — so the Ok payload has to be exactified with the value it
2082        // carries, or the function returns a type it cannot construct.
2083        format!("Result<logicaffeine_data::LogosInt,{rest}")
2084    } else {
2085        t.to_string()
2086    }
2087}
2088
2089/// Phase 32/38: Generate a function definition.
2090/// Phase 38: Updated for native functions and TypeExpr types.
2091/// Phase 49: Accepts lww_fields for LWWRegister SetField handling.
2092/// Phase 103: Accepts registry for polymorphic enum type inference.
2093/// The `where` clause a generic function's type parameters need. A type parameter stands for any
2094/// LOGOS value, and a generic body uses it as one — copies it (value semantics), compares it,
2095/// shows it — so those are its bounds; every value type has them. A parameter a signature uses as
2096/// a map key or set element also hashes. A clause, not inline bounds, so the head stays `fn f<T>`.
2097fn generic_bounds(
2098    generics: &[Symbol],
2099    params: &[(Symbol, &TypeExpr)],
2100    return_type: Option<&TypeExpr>,
2101    interner: &Interner,
2102) -> String {
2103    if generics.is_empty() {
2104        return String::new();
2105    }
2106    fn keyed_params(
2107        t: &TypeExpr,
2108        generics: &[Symbol],
2109        interner: &Interner,
2110        keyed: &mut HashSet<Symbol>,
2111    ) {
2112        let each = |ts: &[TypeExpr], keyed: &mut HashSet<Symbol>| {
2113            for t in ts {
2114                keyed_params(t, generics, interner, keyed);
2115            }
2116        };
2117        match t {
2118            TypeExpr::Generic { base, params } => {
2119                if matches!(
2120                    interner.resolve(*base),
2121                    "Map" | "HashMap" | "Set" | "HashSet"
2122                ) {
2123                    if let Some(TypeExpr::Named(k) | TypeExpr::Primitive(k)) = params.first() {
2124                        if generics.contains(k) {
2125                            keyed.insert(*k);
2126                        }
2127                    }
2128                }
2129                each(params, keyed);
2130            }
2131            TypeExpr::Tuple(items) => each(items, keyed),
2132            TypeExpr::Record { field_types, .. } => each(field_types, keyed),
2133            TypeExpr::Function { inputs, output } => {
2134                each(inputs, keyed);
2135                keyed_params(output, generics, interner, keyed);
2136            }
2137            TypeExpr::Refinement { base: inner, .. }
2138            | TypeExpr::Persistent { inner }
2139            | TypeExpr::Mutable { inner } => keyed_params(inner, generics, interner, keyed),
2140            TypeExpr::Primitive(_) | TypeExpr::Named(_) => {}
2141        }
2142    }
2143    let mut keyed = HashSet::new();
2144    for (_, t) in params {
2145        keyed_params(t, generics, interner, &mut keyed);
2146    }
2147    if let Some(t) = return_type {
2148        keyed_params(t, generics, interner, &mut keyed);
2149    }
2150    let clauses: Vec<String> = generics
2151        .iter()
2152        .map(|g| {
2153            let hashes = if keyed.contains(g) { " + Eq + ::std::hash::Hash" } else { "" };
2154            format!(
2155                "{}: Clone + PartialEq + ::std::fmt::Debug + logicaffeine_system::io::Showable{hashes}",
2156                interner.resolve(*g)
2157            )
2158        })
2159        .collect();
2160    format!(" where {}", clauses.join(", "))
2161}
2162
2163fn codegen_function_def(
2164    name: Symbol,
2165    generics: &[Symbol],
2166    params: &[(Symbol, &TypeExpr)],
2167    body: &[Stmt],
2168    all_stmts: &[Stmt],
2169    return_type: Option<&TypeExpr>,
2170    is_native: bool,
2171    native_path: Option<Symbol>,
2172    is_exported: bool,
2173    export_target: Option<Symbol>,
2174    interner: &Interner,
2175    lww_fields: &HashSet<(String, String)>,
2176    mv_fields: &HashSet<(String, String)>, // Phase 49b: MVRegister fields
2177    async_functions: &HashSet<Symbol>,     // Phase 54
2178    boxed_fields: &HashSet<(String, String, String)>, // Phase 102
2179    registry: &TypeRegistry,               // Phase 103
2180    pure_functions: &HashSet<Symbol>,
2181    type_env: &crate::analysis::types::TypeEnv,
2182    borrow_params_map: &HashMap<Symbol, HashSet<usize>>,
2183    mut_borrow_params_map: &HashMap<Symbol, HashSet<usize>>,
2184    value_mutable_params_map: &HashMap<Symbol, HashSet<usize>>,
2185    opt_flags: &OptimizationConfig,
2186    fn_returns_map: &HashMap<Symbol, String>,
2187    vec_return_fns: &HashSet<Symbol>,
2188    str_slice_return_fns: &HashMap<Symbol, usize>,
2189    byte_slice_return_fns: &HashMap<Symbol, usize>,
2190    array_return_fns: &HashMap<Symbol, super::affine_array::ArrayReturnInfo>,
2191    fixed_array_param_map: &HashMap<(Symbol, usize), usize>,
2192    oracle: Option<&std::rc::Rc<crate::optimize::OracleFacts>>,
2193    bigint_fns: &HashSet<Symbol>,
2194    exact_hofs: &HashSet<Symbol>,
2195    // Functions whose `Result of Int and …` payload is a bignum — the SIGNATURE changes, call
2196    // sites do not.
2197    exact_result_fns: &HashSet<Symbol>,
2198    // Opt::AsciiClassMask: predicate name -> its precomputed 256-bit membership mask.
2199    ascii_masks: &HashMap<Symbol, [u64; 4]>,
2200) -> String {
2201    let mut output = String::new();
2202    let _tower_scope = super::tower::enter_scope(Some(name));
2203    let _absent_scope = super::absent::enter_function(name);
2204    // Overflow-promoting return: this `Int`-returning function's value can exceed i64, so it is
2205    // typed `-> LogosInt` and its return value is not narrowed.
2206    let returns_bigint = bigint_fns.contains(&name);
2207    // Scalar exact higher-order function (`apply(f, x)`): its `fn`-param + integer params are
2208    // exactified to `LogosInt` so an overflowing closure body promotes to a bignum == the VM.
2209    let is_exact_hof = exact_hofs.contains(&name);
2210    // De-Rc Phase 4: this function returns an owned `Vec<T>` (every Return is a
2211    // uniquely-owned fresh Seq) instead of `LogosSeq<T>`.
2212    let returns_vec = vec_return_fns.contains(&name);
2213    // Opt::TextSliceReturn: this fn returns a borrowed `&'a str` sub-slice of the param at this index.
2214    let str_slice_src: Option<usize> = str_slice_return_fns.get(&name).copied();
2215    // Opt::ByteSliceReturn: this function returns a borrowed `&'a [i64]` sub-slice of the param at this index.
2216    let byte_slice_src: Option<usize> = byte_slice_return_fns.get(&name).copied();
2217    // Step 3b: this function returns a fixed-size stack array `[T; N]` by value.
2218    let array_return = array_return_fns.get(&name);
2219    let names = RustNames::new(interner);
2220    let raw_name = names.raw(name);
2221    let func_name = names.ident(name);
2222    let export_target_lower = export_target.map(|s| interner.resolve(s).to_lowercase());
2223    // A function the exact extension reaches computes on its value model: the lowerings that rewrite
2224    // a body into machine-integer arithmetic (a byte table, a shift-based closed form, a memo table
2225    // keyed by its arguments) do not apply to it.
2226    let reached_by_tower = super::tower::returns(name)
2227        || params.iter().any(|(p, _)| super::tower::param(name, *p));
2228
2229    // Opt::StrengthReducePow2: this function body's always-non-negative variables, so a `x % 2^k` /
2230    // `x / 2^k` on one of them can lower to `& (2^k-1)` / `>> k`. Set per-body (symbols are name-keyed,
2231    // so a counter `i` in another function must not leak its proof here).
2232    super::expr::set_nonneg_vars(super::expr::collect_always_nonneg(body));
2233    // Opt::WideAccumulator is Main-only in v1 — clear any set from a previous body so a function never
2234    // inherits Main's widened accumulators (symbols are name-keyed).
2235    super::expr::set_wide_acc(std::collections::HashSet::new());
2236
2237    // Opt::AsciiClassMask: this predicate's body IS a 256-bit membership mask — emit the branchless
2238    // mask test in place of the comparison chain, so every caller (LLVM inlines this tiny fn) gets a
2239    // no-load classification that beats C's ctype table. Byte-identical: the mask over [0,256) is the
2240    // CTFE of the predicate, and the `(0<=cc<256)` guard reproduces its false-outside-range behavior.
2241    if let Some(mask) = ascii_masks.get(&name).filter(|_| !reached_by_tower) {
2242        if !is_exported
2243            && crate::optimize::active_config().is_on(crate::optimization::Opt::AsciiClassMask)
2244        {
2245            crate::optimize::mark_fired(crate::optimization::Opt::AsciiClassMask);
2246            let cparam = names.ident(params[0].0);
2247            // A FLAT 256-byte membership table (like C's ctype), not a compact bitmask: measured to
2248            // beat C (~41ms vs 49ms with branchless), whereas the bitmask's per-element shift/mask
2249            // arithmetic (~105ms) is slower than one hot-L1 table load. Built from the CTFE mask.
2250            let table: String = (0..256usize)
2251                .map(|c| (((mask[c >> 6] >> (c & 63)) & 1) as u8).to_string())
2252                .collect::<Vec<_>>()
2253                .join(",");
2254            let mut out = String::new();
2255            out.push_str("#[inline]\n");
2256            writeln!(
2257                out,
2258                "fn {}({}: i64) -> bool {{ static __T: [u8; 256] = [{}]; let __cc = {}; (0 <= __cc && __cc < 256) && __T[__cc as usize] != 0 }}",
2259                func_name, cparam, table, cparam
2260            )
2261            .unwrap();
2262            return out;
2263        }
2264    }
2265
2266    // Phase 54: Detect which parameters are used as pipe senders
2267    let pipe_sender_params = collect_pipe_sender_params(body);
2268    let pipes_used = super::replay::pipes_used(body);
2269
2270    // FFI: Exported functions need special signatures
2271    let is_c_export_early =
2272        is_exported && matches!(export_target_lower.as_deref(), None | Some("c"));
2273
2274    // TCE: Detect tail recursion eligibility (respects ## No TCO / ## No Optimize)
2275    let no_tco = !crate::optimize::active_config()
2276        .merged(opt_flags)
2277        .is_on(Opt::Tco);
2278    // A direct `Return self(args)` always TCE's. The `Set/Let x = self(args);
2279    // Return x` pair TCE's too — UNLESS the function is borrow/mut-borrow-eligible
2280    // (an in-place array recursion like quicksort), where that rewrite is the
2281    // better lowering and pair-TCE would force an owned, cloned parameter. Such
2282    // functions recurse only O(log n) deep, so the constant-stack guarantee is
2283    // moot for them anyway.
2284    let has_tail_pair = body_has_top_level_tail_pair(name, body, params.len());
2285    // A borrow/mut-borrow-eligible function keeps the borrow rather than pair-TCE —
2286    // Borrow preempts Tco (pair) for it.
2287    if has_tail_pair
2288        && (borrow_params_map.contains_key(&name) || mut_borrow_params_map.contains_key(&name))
2289    {
2290        crate::optimize::mark_preempted(Opt::Borrow, Opt::Tco);
2291    }
2292    let pair_tce_ok = has_tail_pair
2293        && !borrow_params_map.contains_key(&name)
2294        && !mut_borrow_params_map.contains_key(&name);
2295    let is_tce = !is_native
2296        && !is_c_export_early
2297        && !no_tco
2298        && (is_tail_recursive(name, body) || pair_tce_ok);
2299    if is_tce {
2300        crate::optimize::mark_fired(Opt::Tco);
2301    }
2302    let param_syms: Vec<Symbol> = params.iter().map(|(s, _)| *s).collect();
2303
2304    // Accumulator Introduction: Detect non-tail single-call + / * patterns
2305    let acc_info = if !is_tce && !is_native && !is_c_export_early {
2306        detect_accumulator_pattern(name, body)
2307    } else {
2308        None
2309    };
2310    let is_acc = acc_info.is_some();
2311
2312    // Closed-form: Detect double recursion f(0)=base, f(d)=k+f(d-1)+f(d-1)
2313    // Emits ((base+k) << d) - k instead of memoization — matches GCC/LLVM -O2.
2314    let closed_form_info = if !is_tce && !is_acc && !is_native && !is_c_export_early && !reached_by_tower {
2315        detect_double_recursion_closed_form(name, params, body, interner)
2316    } else {
2317        None
2318    };
2319    let is_closed_form = closed_form_info.is_some();
2320    if is_closed_form {
2321        // The affine double-recursion collapse (`f(d)=k+f(d-1)+f(d-1)` → `(base+k)<<d - k`)
2322        // is a codegen-time closed form; record it in the firing trace so a
2323        // `## Require closedform` can depend on it, like the optimize-pass collapses.
2324        crate::optimize::mark_fired(Opt::ClosedForm);
2325    }
2326
2327    // Memoization: Detect pure multi-call recursive functions with hashable params
2328    // Respects ## No Memo / ## No Optimize annotations
2329    let no_memo = !crate::optimize::active_config()
2330        .merged(opt_flags)
2331        .is_on(Opt::Memo);
2332    let is_memo = !is_tce
2333        && !is_acc
2334        && !is_closed_form
2335        && !reached_by_tower
2336        && !is_native
2337        && !is_c_export_early
2338        && !no_memo
2339        && should_memoize(
2340            name,
2341            body,
2342            params,
2343            return_type,
2344            pure_functions.contains(&name),
2345            interner,
2346        );
2347    if is_memo {
2348        crate::optimize::mark_fired(Opt::Memo);
2349    }
2350    // A tail-recursive function that WOULD otherwise memoize is claimed by TCE
2351    // instead — Tco preempts Memo (eval `should_memoize` only here, where `is_memo`
2352    // short-circuited it via `!is_tce`, so it is computed at most once).
2353    if is_tce
2354        && !no_memo
2355        && should_memoize(
2356            name,
2357            body,
2358            params,
2359            return_type,
2360            pure_functions.contains(&name),
2361            interner,
2362        )
2363    {
2364        crate::optimize::mark_preempted(Opt::Tco, Opt::Memo);
2365    }
2366
2367    let needs_mut_params = is_tce || is_acc;
2368
2369    // Peephole: respect ## No Peephole / ## No Optimize annotations
2370    let no_peephole = !crate::optimize::active_config()
2371        .merged(opt_flags)
2372        .is_on(Opt::Peephole);
2373
2374    // Get borrow indices for this function (empty set if none)
2375    let borrow_indices = borrow_params_map.get(&name).cloned().unwrap_or_default();
2376
2377    // Get mutable borrow indices (element-only mutation, return same param)
2378    let mut_borrow_indices = mut_borrow_params_map
2379        .get(&name)
2380        .cloned()
2381        .unwrap_or_default();
2382
2383    // Compute mutable vars early for param mutability detection
2384    let func_mutable_vars = collect_mutable_vars(body);
2385
2386    // Build parameter list using TypeExpr
2387    let params_str: Vec<String> = params
2388        .iter()
2389        .enumerate()
2390        .map(|(i, (param_name, param_type))| {
2391            let pname = names.ident(*param_name);
2392            if super::tower::param(name, *param_name) {
2393                let mutable = needs_mut_params || func_mutable_vars.contains(param_name);
2394                return format!("{}{}: {}", if mutable { "mut " } else { "" }, pname, super::tower::VALUE);
2395            }
2396            let ty = codegen_type_expr(param_type, interner);
2397            // A parameter that can hold `nothing` holds the caller's value-or-nothing, lent or passed whole.
2398            if let Some(held) = super::absent::parameter(name, *param_name, &ty) {
2399                return if matches!(param_type, crate::ast::stmt::TypeExpr::Mutable { .. }) {
2400                    format!("{}: &mut {}", pname, held)
2401                } else if needs_mut_params || func_mutable_vars.contains(param_name) {
2402                    format!("mut {}: {}", pname, held)
2403                } else {
2404                    format!("{}: {}", pname, held)
2405                };
2406            }
2407            // Exact-HOF: exactify this parameter's integer types (`i64` → `LogosInt`, inside
2408            // `impl Fn(..)` too), so the fn-param is `impl Fn(LogosInt) -> LogosInt` and an integer
2409            // param is `LogosInt` — the closure/integer arguments the call-site promotes flow in.
2410            let ty = if is_exact_hof {
2411                exactify_rust_int_type(&ty)
2412            } else {
2413                ty
2414            };
2415            // A `mutable` param (value semantics) is lent: a `LogosSeq`/`LogosMap` as a shared `&`
2416            // (its writes go through its own `RefCell`), anything else as `&mut` — either way the
2417            // callee's writes are the caller's value.
2418            if crate::semantics::collections::value_semantics_enabled()
2419                && matches!(param_type, crate::ast::stmt::TypeExpr::Mutable { .. })
2420            {
2421                let lend = if super::expr::lent_by_shared_reference(&ty) {
2422                    "&"
2423                } else {
2424                    "&mut "
2425                };
2426                format!("{}: {}{}", pname, lend, ty)
2427            } else if let Some(pipe) =
2428                super::replay::pipe_param_type(*param_name, param_type, &pipes_used, interner)
2429            {
2430                format!("{}: {}", pname, pipe)
2431            } else if pipe_sender_params.contains(param_name) {
2432                format!("{}: tokio::sync::mpsc::Sender<{}>", pname, ty)
2433            } else if str_slice_src == Some(i) {
2434                // Opt::TextSliceReturn: this borrowed Text param is the source of the returned
2435                // sub-slice, so it carries the named lifetime `'a` tying the `&'a str` return to it.
2436                format!("{}: &'a str", pname)
2437            } else if byte_slice_src == Some(i) {
2438                // Opt::ByteSliceReturn: this borrowed Seq param is the source of the returned
2439                // `&'a [i64]` sub-slice, so it carries the named lifetime `'a`.
2440                let slice_ty = vec_to_slice_type(&ty);
2441                format!("{}: {}", pname, slice_ty.replacen('&', "&'a ", 1))
2442            } else if borrow_indices.contains(&i) && super::lent::is_user_enum(param_type, registry)
2443            {
2444                format!("{}: &{}", pname, ty)
2445            } else if borrow_indices.contains(&i) {
2446                // Read-only Vec param → borrow as `&[T]`, or `&[T; N]` when every caller passes a fixed
2447                // `[T; N]` array (LLVM then elides the constant-index bounds checks).
2448                let slice_ty = vec_to_slice_type(&ty);
2449                let final_ty = match fixed_array_param_map.get(&(name, i)) {
2450                    Some(n) => slice_ty
2451                        .strip_prefix("&[")
2452                        .and_then(|s| s.strip_suffix(']'))
2453                        .map(|elem| format!("&[{}; {}]", elem, n))
2454                        .unwrap_or(slice_ty),
2455                    None => slice_ty,
2456                };
2457                format!("{}: {}", pname, final_ty)
2458            } else if mut_borrow_indices.contains(&i) {
2459                // Element-only mutation Vec param → borrow as &mut [T]
2460                let slice_ty = vec_to_mut_slice_type(&ty);
2461                format!("{}: {}", pname, slice_ty)
2462            } else if needs_mut_params || func_mutable_vars.contains(param_name) {
2463                format!("mut {}: {}", pname, ty)
2464            } else {
2465                format!("{}: {}", pname, ty)
2466            }
2467        })
2468        .collect();
2469
2470    // Get return type string from TypeExpr or infer from body
2471    // If this function has &mut borrow params and returns one of them,
2472    // suppress the return type since the mutation happens in-place.
2473    let has_mut_borrow = !mut_borrow_indices.is_empty();
2474    let return_type_str = if super::tower::returns(name) {
2475        Some(super::tower::VALUE.to_string())
2476    } else if let Some(held) = super::absent::returned(name) {
2477        Some(held)
2478    } else if exact_result_fns.contains(&name) {
2479        return_type.map(|t| exactify_rust_int_type(&codegen_type_expr(t, interner)))
2480    } else if returns_bigint {
2481        // Overflow-promoting: an `Int` return whose value can exceed i64 is a `LogosInt`.
2482        //
2483        // ★ AN ANSWER-SHAPED RETURN KEEPS ITS SHAPE. `jsonInt(v) -> Result of Int and Text` hands
2484        // back a number that a JSON document may have made huge, but it hands it back INSIDE a
2485        // Result — so the payload is exactified and the Result stays a Result. Replacing the
2486        // whole type with `LogosInt` would make the function unable to report the failure it
2487        // exists to report.
2488        match return_type.map(|t| codegen_type_expr(t, interner)) {
2489            Some(t) if t.starts_with("Result<i64,") => Some(exactify_rust_int_type(&t)),
2490            _ => Some("logicaffeine_data::LogosInt".to_string()),
2491        }
2492    } else if str_slice_src.is_some() {
2493        // Opt::TextSliceReturn: a borrowed sub-slice of the input Text.
2494        Some("&'a str".to_string())
2495    } else if byte_slice_src.is_some() {
2496        // Opt::ByteSliceReturn: a borrowed sub-slice of the input Seq (`&'a [i64]`).
2497        return_type
2498            .map(|t| vec_to_slice_type(&codegen_type_expr(t, interner)).replacen('&', "&'a ", 1))
2499    } else if has_mut_borrow {
2500        None // No return type — mutation is in-place via &mut [T]
2501    } else if let Some(info) = array_return {
2502        // Step 3b: `LogosSeq<T>` → a fixed-size stack array `[T; N]` returned by value.
2503        Some(format!("[{}; {}]", info.elem_ty, info.len))
2504    } else if returns_vec {
2505        // Phase 4: `LogosSeq<T>` → owned `Vec<T>`. Replace the `LogosSeq<` head
2506        // of the codegen'd type (`LogosSeq<i64>` → `Vec<i64>`).
2507        return_type.map(|t| codegen_type_expr(t, interner).replacen("LogosSeq<", "Vec<", 1))
2508    } else {
2509        return_type
2510            .map(|t| codegen_type_expr(t, interner))
2511            // An omitted return type: consume the checker's Hindley-Milner
2512            // inference (`type_env`, registry-aware — resolves field-access and
2513            // call returns) before the weaker codegen-local body heuristic. This
2514            // is what keeps `## To f(..):` with a field/call/struct return from
2515            // emitting the illegal `-> _`.
2516            .or_else(|| {
2517                type_env
2518                    .lookup_fn(name)
2519                    .and_then(|sig| logos_return_type_to_rust(&sig.return_type, interner))
2520            })
2521            .or_else(|| infer_return_type_from_body(body, params, registry, interner))
2522    };
2523
2524    // Phase 51/54: Check if function is async (includes transitive async detection)
2525    let is_async = async_functions.contains(&name);
2526    let fn_keyword = if is_async { "async fn" } else { "fn" };
2527
2528    // FFI: Exported functions need special signatures
2529    let is_c_export = is_c_export_early;
2530
2531    // FFI: Check if C export needs type marshaling
2532    // Triggers for: Text params/return, reference types, Result return, refinement params
2533    let needs_c_marshaling = is_c_export && {
2534        let has_text_param = params.iter().any(|(_, ty)| is_text_type(ty, interner));
2535        let has_text_return = return_type.map_or(false, |ty| is_text_type(ty, interner));
2536        let has_ref_param = params.iter().any(|(_, ty)| {
2537            classify_type_for_c_abi(ty, interner, registry) == CAbiClass::ReferenceType
2538        });
2539        let has_ref_return = return_type.map_or(false, |ty| {
2540            classify_type_for_c_abi(ty, interner, registry) == CAbiClass::ReferenceType
2541        });
2542        let has_result_return = return_type.map_or(false, |ty| is_result_type(ty, interner));
2543        let has_refinement_param = params
2544            .iter()
2545            .any(|(_, ty)| matches!(ty, TypeExpr::Refinement { .. }));
2546        // Char crosses the C ABI as uint32_t; route through the marshal path so
2547        // the wrapper validates it via char::from_u32 instead of exposing a raw
2548        // Rust `char` (an out-of-range u32 from C is UB).
2549        let has_char_param = params.iter().any(|(_, ty)| is_char_type(ty, interner));
2550        let has_char_return = return_type.map_or(false, |ty| is_char_type(ty, interner));
2551        has_text_param
2552            || has_text_return
2553            || has_ref_param
2554            || has_ref_return
2555            || has_result_return
2556            || has_refinement_param
2557            || has_char_param
2558            || has_char_return
2559    };
2560
2561    if needs_c_marshaling {
2562        // Generate two-function pattern: inner function + C ABI wrapper
2563        return codegen_c_export_with_marshaling(
2564            name,
2565            params,
2566            body,
2567            return_type,
2568            interner,
2569            lww_fields,
2570            mv_fields,
2571            async_functions,
2572            boxed_fields,
2573            registry,
2574            type_env,
2575        );
2576    }
2577
2578    // Build function signature
2579    let (vis_prefix, abi_prefix) = if is_exported {
2580        match export_target_lower.as_deref() {
2581            None | Some("c") => ("pub ", "extern \"C\" "),
2582            Some("wasm") => ("pub ", ""),
2583            _ => ("pub ", ""),
2584        }
2585    } else {
2586        ("", "")
2587    };
2588
2589    // Generic functions: "fn identity<T>" — resolve each generic Symbol to its name.
2590    // Opt::TextSliceReturn prepends the borrowed-return lifetime `'a`.
2591    let generics_str = if generics.is_empty() {
2592        if str_slice_src.is_some() || byte_slice_src.is_some() {
2593            "<'a>".to_string()
2594        } else {
2595            String::new()
2596        }
2597    } else {
2598        let params_list: Vec<&str> = generics.iter().map(|sym| interner.resolve(*sym)).collect();
2599        if str_slice_src.is_some() || byte_slice_src.is_some() {
2600            format!("<'a, {}>", params_list.join(", "))
2601        } else {
2602            format!("<{}>", params_list.join(", "))
2603        }
2604    };
2605
2606    let signature = if let Some(ref ret_ty) = return_type_str {
2607        if ret_ty != "()" {
2608            format!(
2609                "{}{}{} {}{}({}) -> {}",
2610                vis_prefix,
2611                abi_prefix,
2612                fn_keyword,
2613                func_name,
2614                generics_str,
2615                params_str.join(", "),
2616                ret_ty
2617            )
2618        } else {
2619            format!(
2620                "{}{}{} {}{}({})",
2621                vis_prefix,
2622                abi_prefix,
2623                fn_keyword,
2624                func_name,
2625                generics_str,
2626                params_str.join(", ")
2627            )
2628        }
2629    } else {
2630        format!(
2631            "{}{}{} {}{}({})",
2632            vis_prefix,
2633            abi_prefix,
2634            fn_keyword,
2635            func_name,
2636            generics_str,
2637            params_str.join(", ")
2638        )
2639    };
2640    let signature = format!(
2641        "{signature}{}",
2642        generic_bounds(generics, params, return_type, interner)
2643    );
2644    let _generic_params = super::expr::GenericParamsInScope::enter(
2645        generics
2646            .iter()
2647            .map(|g| interner.resolve(*g).to_string())
2648            .collect(),
2649    );
2650    let _lent_params =
2651        super::expr::LentParamsInScope::enter(match value_mutable_params_map.get(&name) {
2652            Some(lent) => params
2653                .iter()
2654                .enumerate()
2655                .filter(|(i, _)| lent.contains(i))
2656                .map(|(_, (p, _))| *p)
2657                .collect(),
2658            None => HashSet::new(),
2659        });
2660
2661    // Emit #[inline] for small non-recursive, non-exported functions
2662    // Closed-form functions are tiny (2 lines) and should always inline.
2663    if is_closed_form
2664        || (!is_tce && !is_acc && should_inline(name, body, is_native, is_exported, is_async))
2665    {
2666        writeln!(output, "#[inline]").unwrap();
2667    }
2668
2669    // FFI: Emit export attributes before the function
2670    if is_exported {
2671        match export_target_lower.as_deref() {
2672            None | Some("c") => {
2673                writeln!(output, "#[export_name = \"logos_{}\"]", raw_name).unwrap();
2674            }
2675            Some("wasm") => {
2676                writeln!(output, "#[wasm_bindgen]").unwrap();
2677            }
2678            _ => {}
2679        }
2680    }
2681
2682    // Phase 38: Handle native functions
2683    if is_native {
2684        let arg_names: Vec<&str> = params.iter().map(|(n, _)| interner.resolve(*n)).collect();
2685
2686        if let Some(path_sym) = native_path {
2687            // User-defined native path: call the Rust path directly
2688            let path = interner.resolve(path_sym);
2689            // Validate path looks like a valid Rust path (identifiers separated by ::)
2690            let is_valid_path = !path.is_empty()
2691                && path.split("::").all(|seg| {
2692                    !seg.is_empty() && seg.chars().all(|c| c.is_alphanumeric() || c == '_')
2693                });
2694            if is_valid_path {
2695                writeln!(output, "{} {{", signature).unwrap();
2696                writeln!(output, "    {}({})", path, arg_names.join(", ")).unwrap();
2697                writeln!(output, "}}\n").unwrap();
2698            } else {
2699                writeln!(output, "{} {{", signature).unwrap();
2700                writeln!(output, "    compile_error!(\"Invalid native function path: '{}'. Path must be a valid Rust path like \\\"crate::module::function\\\".\")", path).unwrap();
2701                writeln!(output, "}}\n").unwrap();
2702            }
2703        } else {
2704            // Legacy system functions: use map_native_function()
2705            if let Some((module, core_fn)) = map_native_function(raw_name) {
2706                writeln!(output, "{} {{", signature).unwrap();
2707                let call = format!(
2708                    "logicaffeine_system::{}::{}({})",
2709                    module,
2710                    core_fn,
2711                    arg_names.join(", ")
2712                );
2713                // A native fn declared `-> Result of T and E` (e.g. file read/write) has a
2714                // runtime that returns `std::result::Result`, but the wrapper's declared type is
2715                // the LOGOS `user_types::Result` enum (`Ok { value }` / `Err { error }`). Convert
2716                // at the boundary so the primitive actually usable from LOGOS.
2717                if refuses_by_failing(raw_name) {
2718                    // A kernel whose arguments break its contract stops the program with the same
2719                    // report the tree-walker and the VM give (`NativeKernel::failure`).
2720                    writeln!(output, "    match {call} {{").unwrap();
2721                    writeln!(output, "        ::std::result::Result::Ok(v) => v,").unwrap();
2722                    writeln!(
2723                        output,
2724                        "        ::std::result::Result::Err(why) => panic!(\"{{}}(): {{}}\", {:?}, why),",
2725                        raw_name
2726                    )
2727                    .unwrap();
2728                    writeln!(output, "    }}").unwrap();
2729                } else if signature.contains("-> Result<") {
2730                    writeln!(output, "    match {call} {{").unwrap();
2731                    writeln!(
2732                        output,
2733                        "        ::std::result::Result::Ok(v) => Result::Ok {{ value: v }},"
2734                    )
2735                    .unwrap();
2736                    writeln!(
2737                        output,
2738                        "        ::std::result::Result::Err(e) => Result::Err {{ error: e }},"
2739                    )
2740                    .unwrap();
2741                    writeln!(output, "    }}").unwrap();
2742                } else if let Some(int) = ["i64", "u64"]
2743                    .into_iter()
2744                    .find(|int| signature.ends_with(&format!("-> {int}")))
2745                {
2746                    // The system function's integer width is its own; the declaration names the LOGOS
2747                    // one (`Int`, or `Nat`), so the wrapper answers in that.
2748                    writeln!(output, "    ({call}) as {int}").unwrap();
2749                } else {
2750                    writeln!(output, "    {call}").unwrap();
2751                }
2752                writeln!(output, "}}\n").unwrap();
2753            } else {
2754                writeln!(output, "{} {{", signature).unwrap();
2755                writeln!(
2756                    output,
2757                    "    compile_error!({:?})",
2758                    crate::semantics::builtins::unimplemented_native(raw_name, None)
2759                )
2760                .unwrap();
2761                writeln!(output, "}}\n").unwrap();
2762            }
2763        }
2764    } else {
2765        // Non-native: emit body (also used for exported functions which have bodies)
2766        writeln!(output, "{} {{", signature).unwrap();
2767
2768        // Entry precondition guard (BCE for recursive 1-based partitions): make
2769        // the function's `1 <= lo` and `hi <= len` precondition explicit so LLVM
2770        // drops the per-access bounds checks across the hot partition loop.
2771        // Gated on `lo < hi` (the indexing path) so it never fires for the
2772        // base-case range; only emitted for pure (no-I/O) functions, so the
2773        // abort is equivalent to the out-of-range access it pre-empts. Emitted
2774        // even for a tail-call-eliminated partition (value semantics makes the
2775        // `Set result to qs(...)` threading TCE-able): the assert runs on the
2776        // INITIAL params before the loop (sound), and every in-loop access keeps
2777        // its own oracle `assert_unchecked` hint.
2778        if !is_acc {
2779            if let Some(g) = super::entry_guard::detect_entry_guard(params, body, interner) {
2780                let arr = names.ident(g.arr);
2781                let lo = names.ident(g.lo);
2782                let hi = names.ident(g.hi);
2783                let adj = g.hi_len_adjust;
2784                writeln!(
2785                    output,
2786                    "    if ({lo}) < ({hi}) {{ let __{arr}_glen = {arr}.len() as i64 + {adj}; assert!(({lo}) >= 1 && ({hi}) <= __{arr}_glen, \"LOGOS precondition guard: 1-based index range\"); }}"
2787                )
2788                .unwrap();
2789                // The same precondition (`hi <= arr.len()`) that licenses the
2790                // unchecked indexing also bounds the partition counters, so their
2791                // `+ 1` cannot overflow — lower it raw. Sound; see the fn's doc.
2792                super::entry_guard::mark_deguardable_counters(params, body, &g, interner);
2793            } else if let Some(g) =
2794                super::entry_guard::detect_heap_sift_guard(params, body, interner)
2795            {
2796                // Affine-index descent: the precondition `start >= 0 && end < arr.len()`
2797                // (guarded on the descent-entry `2*start+1 <= end`, the indexing path)
2798                // lets the oracle prove every `[0, end]` index in range. Pure fn, so the
2799                // abort is equivalent to the out-of-range access it pre-empts.
2800                let arr = names.ident(g.arr);
2801                let start = names.ident(g.start);
2802                let end = names.ident(g.end);
2803                writeln!(
2804                    output,
2805                    "    if (2i64.wrapping_mul({start}).wrapping_add(1)) <= ({end}) {{ let __{arr}_glen = {arr}.len() as i64; assert!(({start}) >= 0 && ({end}) < __{arr}_glen, \"LOGOS precondition guard: affine index range\"); }}"
2806                )
2807                .unwrap();
2808                // The same `end < arr.len()` precondition bounds every heap index in
2809                // the descent, so its affine index arithmetic (`2*root+1`, `child+1`,
2810                // …) provably fits `i64` for a wide (`>= 8` byte) element — lower it
2811                // raw instead of the overflow-promote form. Sound; see the fn's doc.
2812                super::entry_guard::mark_heap_sift_index_arith(params, body, &g, interner);
2813            }
2814        }
2815
2816        // Wrap exported C functions in catch_unwind for panic safety
2817        let wrap_catch_unwind = is_c_export;
2818        if wrap_catch_unwind {
2819            writeln!(
2820                output,
2821                "    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {{"
2822            )
2823            .unwrap();
2824        }
2825
2826        let mut func_ctx = RefinementContext::new();
2827        // SIMD-reduce lifter needs the program's function bodies (to inline liftable transcendentals).
2828        func_ctx.set_simd_fns(super::simd_reduce::build_fn_map(all_stmts));
2829        // O1 borrow hoisting: same oracle, keyed by the loop Stmts in this
2830        // body (sub-slice of the program codegen analyzed).
2831        if let Some(o) = oracle {
2832            func_ctx.set_oracle(o.clone());
2833        }
2834        // Local Vec optimization: detect which collection vars escape this function
2835        let func_escaping = collect_escaping_collection_vars(body);
2836        func_ctx.set_escaping_vars(func_escaping);
2837        // Overflow-promoting Int bindings in this function body (a call to a bignum function counts
2838        // as a bignum-producing RHS). A promoted variable that is RETURNED makes this function
2839        // `-> LogosInt` (`returns_bigint`, computed by the whole-program fixpoint).
2840        // An exactified function's machine-word parameters hold bignums (registered `LogosInt` below),
2841        // so what the body sets from one is a candidate too — the same seeds the analysis used.
2842        let exact_params = if is_exact_hof {
2843            crate::codegen::bigint_promote::exact_param_seeds(params, interner)
2844        } else {
2845            HashSet::new()
2846        };
2847        func_ctx.set_promotable_candidates(crate::codegen::bigint_promote::promotable_int_vars(
2848            body,
2849            bigint_fns,
2850            &crate::codegen::expr::bigint_struct_fields_snapshot(),
2851            &exact_params,
2852        ));
2853        // O2 de-Rc: function-LOCAL Seqs that never need reference semantics →
2854        // plain Vec<T>. The use-scan disqualifies any returned/escaping/aliased
2855        // handle, so only genuinely-local buffers (sieve flags, scratch arrays)
2856        // de-Rc. Parameters are not candidates (Phase 3 handles those).
2857        let func_de_rc = collect_de_rc_seqs(
2858            body,
2859            interner,
2860            borrow_params_map,
2861            mut_borrow_params_map,
2862            vec_return_fns,
2863            returns_vec,
2864        );
2865        let func_worklists = super::worklist::detect_worklists(body, &func_de_rc, interner);
2866        let mut func_affine =
2867            super::affine_array::detect_affine_arrays(body, &func_de_rc, interner);
2868        func_affine.retain(|sym, _| !func_worklists.contains_key(sym));
2869        // Constant-table locals → stack arrays `[T; N]` (zero heap, direct index). Detected while
2870        // `func_de_rc` is still borrowable; excluded from affine/narrow so no other pass re-claims them,
2871        // and registered with the `[T; N]` type so the Index codegen emits a direct array read.
2872        let func_const_tables = super::affine_array::detect_const_tables(
2873            body,
2874            all_stmts,
2875            &func_de_rc,
2876            borrow_params_map,
2877            interner,
2878        );
2879        // Fixed-size, non-escaping scratch buffers → in-place `[T; N]` via from_fn (disjoint from constant
2880        // tables: those have constant values and hoist; these have per-iteration values and stay in place).
2881        let mut func_scratch = super::affine_array::detect_scratch_buffers(
2882            body,
2883            &func_de_rc,
2884            borrow_params_map,
2885            interner,
2886        );
2887        func_scratch.retain(|sym, _| !func_const_tables.contains_key(sym));
2888        // Zero-init + indexed-write fixed-size buffers → `[T; N]` stack arrays. Disjoint from scratch/const
2889        // (those are push-built read-only; these are indexed-written).
2890        let mut func_indexed =
2891            super::affine_array::detect_indexed_buffers(body, &func_de_rc, interner);
2892        func_indexed.retain(|sym, _| {
2893            !func_const_tables.contains_key(sym) && !func_scratch.contains_key(sym)
2894        });
2895        func_scratch.retain(|sym, _| !func_indexed.contains_key(sym));
2896        // Straight-line-push fixed buffers → `[T; K]` (borrow-aware; the O3 `Let`/`Push` handlers emit the
2897        // stack array + `buf[k]=expr` fills). Disjoint from the fixed-size passes above.
2898        let mut func_sl = super::affine_array::detect_straightline_buffers(
2899            body,
2900            &func_de_rc,
2901            borrow_params_map,
2902            interner,
2903        );
2904        func_sl.retain(|sym, _| {
2905            !func_const_tables.contains_key(sym)
2906                && !func_scratch.contains_key(sym)
2907                && !func_indexed.contains_key(sym)
2908        });
2909        // Cursor-filled fixed-size buffers → `[T; N]` + a runtime fill cursor. Reaches the
2910        // SELF-REFERENTIAL / multi-phase push builds the straight-line/from_fn/const-table
2911        // passes reject — sha256's message schedule `w[t] = f(w[t-2], …)`, built by a copy
2912        // loop then a self-referential compute loop. `sf_fixed_len` resolves a `for _ in coll`
2913        // copy phase's element count from the fixed-array params + the buffers already claimed.
2914        let mut sf_fixed_len: HashMap<Symbol, usize> = HashMap::new();
2915        for (i, (psym, _)) in params.iter().enumerate() {
2916            if let Some(&n) = fixed_array_param_map.get(&(name, i)) {
2917                sf_fixed_len.insert(*psym, n);
2918            }
2919        }
2920        for (s, info) in &func_const_tables {
2921            sf_fixed_len.insert(*s, info.values.len());
2922        }
2923        for (s, info) in &func_scratch {
2924            sf_fixed_len.insert(*s, info.len);
2925        }
2926        for (s, info) in &func_indexed {
2927            sf_fixed_len.insert(*s, info.len);
2928        }
2929        for (s, (_, n)) in &func_sl {
2930            sf_fixed_len.insert(*s, *n);
2931        }
2932        let mut func_seq_fill = super::affine_array::detect_seq_fill_buffers(
2933            body,
2934            &func_de_rc,
2935            borrow_params_map,
2936            &|sym| sf_fixed_len.get(&sym).copied(),
2937            interner,
2938        );
2939        func_seq_fill.retain(|sym, _| {
2940            !func_const_tables.contains_key(sym)
2941                && !func_scratch.contains_key(sym)
2942                && !func_indexed.contains_key(sym)
2943                && !func_sl.contains_key(sym)
2944        });
2945        func_affine.retain(|sym, _| {
2946            !func_const_tables.contains_key(sym)
2947                && !func_scratch.contains_key(sym)
2948                && !func_seq_fill.contains_key(sym)
2949        });
2950        for (sym, info) in &func_affine {
2951            func_ctx.register_variable_type(
2952                *sym,
2953                format!(
2954                    "__affine_array:{}:{}:{}",
2955                    info.coeff, info.offset, info.trip
2956                ),
2957            );
2958        }
2959        let mut func_narrowed =
2960            narrow_seqs(body, &func_de_rc, &func_affine, &func_worklists, interner);
2961        func_narrowed.retain(|sym, _| {
2962            !func_const_tables.contains_key(sym)
2963                && !func_scratch.contains_key(sym)
2964                && !func_indexed.contains_key(sym)
2965                && !func_sl.contains_key(sym)
2966                && !func_seq_fill.contains_key(sym)
2967        });
2968        for sym in func_narrowed.keys() {
2969            func_ctx.register_variable_type(*sym, "Vec<i32>".to_string());
2970        }
2971        let func_bits = bitpack_seqs(
2972            body,
2973            &func_de_rc,
2974            &|s| {
2975                func_worklists.contains_key(&s)
2976                    || func_affine.contains_key(&s)
2977                    || func_const_tables.contains_key(&s)
2978                    || func_scratch.contains_key(&s)
2979                    || func_indexed.contains_key(&s)
2980                    || func_sl.contains_key(&s)
2981                    || func_seq_fill.contains_key(&s)
2982            },
2983            interner,
2984        );
2985        for sym in &func_bits {
2986            func_ctx.register_variable_type(*sym, "LogosBits".to_string());
2987        }
2988        func_ctx.set_de_rc_vars(func_de_rc);
2989        func_ctx.set_worklists(func_worklists);
2990        func_ctx.set_affine_arrays(func_affine);
2991        func_ctx.set_narrowed(func_narrowed);
2992        func_ctx.set_bitpacked(func_bits);
2993        let func_i64 = super::i64_map::detect_i64_maps(body, interner);
2994        if let Some(o) = oracle {
2995            let dense = super::i64_map::detect_dense_i64_maps(&func_i64, o.as_ref(), interner);
2996            let (i32m, i32s) = super::i64_map::detect_i32_maps(&func_i64, &dense, o.as_ref());
2997            func_ctx.set_dense_i64(dense);
2998            func_ctx.set_i32_maps(i32m, i32s);
2999        }
3000        func_ctx.set_i64_sets(func_i64.sets);
3001        func_ctx.set_i64_maps(func_i64.maps);
3002        let mut func_presize = super::peephole::detect_vec_presize(body, interner);
3003        func_presize.retain(|sym, _| {
3004            func_ctx.affine_array(*sym).is_none()
3005                && !func_const_tables.contains_key(sym)
3006                && !func_scratch.contains_key(sym)
3007                && !func_indexed.contains_key(sym)
3008                && !func_sl.contains_key(sym)
3009                && !func_seq_fill.contains_key(sym)
3010        });
3011        func_ctx.set_vec_presize(func_presize);
3012        func_ctx.set_fast_div(super::fast_div::detect_fast_div(
3013            body,
3014            oracle.map(|o| o.as_ref()),
3015            interner,
3016        ));
3017        func_ctx.set_returns_vec(returns_vec);
3018        func_ctx.set_str_slice_source(str_slice_src);
3019        func_ctx.set_byte_slice_source(byte_slice_src);
3020        func_ctx.set_returns_bigint(returns_bigint);
3021        func_ctx.set_returns_rationals(
3022            fn_returns_map.get(&name).filter(|t| t.contains(super::rational::RATIONAL)).cloned(),
3023        );
3024        // OPT: Detect single-char text vars in function body
3025        let func_single_char_vars = collect_single_char_text_vars(body, interner);
3026        for sym in &func_single_char_vars {
3027            func_ctx.register_variable_type(*sym, "__single_char_u8".to_string());
3028        }
3029        let mut func_synced_vars = HashSet::new(); // Phase 52: Track synced variables in function
3030                                                   // Phase 56: Pre-scan for Mount+Sync combinations in function body
3031        let func_var_caps = analyze_variable_capabilities(body, interner);
3032
3033        // Phase 50: Register parameter types for capability Check resolution
3034        // Borrow-optimized params get &[T] or &mut [T] type so downstream codegen handles them correctly
3035        for (i, (param_name, param_type)) in params.iter().enumerate() {
3036            let type_name = codegen_type_expr(param_type, interner);
3037            if let Some(held) = super::absent::parameter(name, *param_name, &type_name) {
3038                func_ctx.register_variable_type(*param_name, held);
3039            } else if super::tower::param(name, *param_name) {
3040                func_ctx.register_variable_type(*param_name, super::tower::VALUE.to_string());
3041            } else if let Some(pipe) =
3042                super::replay::pipe_param_type(*param_name, param_type, &pipes_used, interner)
3043            {
3044                func_ctx.register_variable_type(*param_name, pipe);
3045            } else if borrow_indices.contains(&i) && super::lent::is_user_enum(param_type, registry)
3046            {
3047                func_ctx.register_variable_type(*param_name, format!("&{}", type_name));
3048            } else if borrow_indices.contains(&i) {
3049                let slice_ty = vec_to_slice_type(&type_name);
3050                let reg_ty = match fixed_array_param_map.get(&(name, i)) {
3051                    Some(n) => slice_ty
3052                        .strip_prefix("&[")
3053                        .and_then(|s| s.strip_suffix(']'))
3054                        .map(|elem| format!("&[{}; {}]", elem, n))
3055                        .unwrap_or(slice_ty),
3056                    None => slice_ty,
3057                };
3058                func_ctx.register_variable_type(*param_name, reg_ty);
3059            } else if mut_borrow_indices.contains(&i) {
3060                func_ctx.register_variable_type(*param_name, vec_to_mut_slice_type(&type_name));
3061            } else if is_exact_hof
3062                && matches!(param_type, crate::ast::stmt::TypeExpr::Function { .. })
3063            {
3064                // An exactified `fn`-typed param (`impl Fn(LogosInt) -> LogosInt`). The `|__exact_fnptr`
3065                // sentinel tells the call emit that CALLING this param (`f(x)`) must promote its integer
3066                // arguments to `LogosInt` (they flow into a `LogosInt` closure param).
3067                func_ctx.register_variable_type(
3068                    *param_name,
3069                    format!("{}{}", exactify_rust_int_type(&type_name), "|__exact_fnptr"),
3070                );
3071            } else if is_exact_hof && type_name == "i64" {
3072                // An exactified integer param — promoted (`__bigint`) so the body's arithmetic on it is
3073                // exact and it passes into a `LogosInt`-param closure without narrowing.
3074                func_ctx.register_variable_type(*param_name, "i64|__bigint".to_string());
3075            } else {
3076                func_ctx.register_variable_type(*param_name, type_name);
3077            }
3078        }
3079
3080        let given: HashSet<Symbol> = params.iter().map(|(p, _)| *p).collect();
3081        let func_joins = super::rational::joins(
3082            body,
3083            &given,
3084            super::rational::Typing { interner, variable_types: func_ctx.get_variable_types(), registry },
3085        );
3086        func_ctx.set_rational_joins(func_joins);
3087
3088        // Register function param-role info on func context for call-site lowering
3089        // (readonly `&[T]` / element `&mut [T]` / value-semantics `mutable`). All of
3090        // a function's roles pack into one slot — see the main-context registration.
3091        register_fn_roles(
3092            &mut func_ctx,
3093            borrow_params_map,
3094            mut_borrow_params_map,
3095            value_mutable_params_map,
3096        );
3097        // Register function return types for variable type inference at call sites
3098        for (fn_sym, rt_str) in fn_returns_map {
3099            func_ctx.register_fn_return(*fn_sym, rt_str.clone());
3100        }
3101
3102        // Phase 54: Functions receive pipe senders as parameters, no local pipe declarations
3103        let func_pipe_vars = HashSet::new();
3104
3105        // Emit the constant-table stack arrays once at the top of the body (before every emission path);
3106        // their original heap-`Vec` `Let`/`Push` build is filtered out (`is_const_table_stmt`), and reads
3107        // hit the `[T; N]` array via the registered type. Zero-alloc constant tables — MD5's shift words.
3108        for (sym, info) in &func_const_tables {
3109            writeln!(
3110                output,
3111                "    let {}: [{}; {}] = [{}];",
3112                names.ident(*sym),
3113                info.elem_ty,
3114                info.values.len(),
3115                info.values.join(", ")
3116            )
3117            .unwrap();
3118            // Register the `[T; N]` type for EVERY body symbol resolving to this table's name — the
3119            // parser mints distinct symbols for the same identifier in different positions (a bare call
3120            // argument vs the `Let` binding), and `variable_types` is symbol-keyed, so a single `Let`-
3121            // symbol registration would miss at a use site. Registered LAST so it also wins over any
3122            // fn-return inference of the binding. (Const-table names are unique in the function body.)
3123            let ty = format!("[{}; {}]", info.elem_ty, info.values.len());
3124            let name = interner.resolve(*sym).to_string();
3125            let mut syms: HashSet<Symbol> = HashSet::new();
3126            collect_named_syms(body, &name, interner, &mut syms);
3127            for s in syms {
3128                func_ctx.register_variable_type(s, ty.clone());
3129            }
3130        }
3131        func_ctx.set_const_tables(func_const_tables);
3132
3133        // Register the `[T; N]` type for every use-site symbol of each scratch buffer (same reason as the
3134        // constant tables above: `variable_types` is symbol-keyed and the parser mints distinct symbols
3135        // per occurrence). The fill loop is emitted in place as `from_fn` by the `Stmt::Repeat` handler;
3136        // only the `new Seq` DECL is filtered (the from_fn becomes the binding).
3137        for (sym, info) in &func_scratch {
3138            let ty = format!("[{}; {}]", info.elem_ty, info.len);
3139            let name = interner.resolve(*sym).to_string();
3140            let mut syms: HashSet<Symbol> = HashSet::new();
3141            collect_named_syms(body, &name, interner, &mut syms);
3142            for s in syms {
3143                func_ctx.register_variable_type(s, ty.clone());
3144            }
3145        }
3146        func_ctx.set_scratch_buffers(func_scratch);
3147
3148        // Register the `[T; N]` type for every use-site symbol of each indexed buffer, so the O3 `[T; N]`
3149        // path emits `let mut buf: [T; N] = [0; N]` and the SetIndex/Index codegen store/read the array.
3150        for (sym, info) in &func_indexed {
3151            let ty = format!("[{}; {}]", info.elem_ty, info.len);
3152            let name = interner.resolve(*sym).to_string();
3153            let mut syms: HashSet<Symbol> = HashSet::new();
3154            collect_named_syms(body, &name, interner, &mut syms);
3155            for s in syms {
3156                func_ctx.register_variable_type(s, ty.clone());
3157            }
3158        }
3159        func_ctx.set_indexed_buffers(func_indexed);
3160
3161        // Straight-line-push buffers: register `[T; K]` so the O3 `Let`/`Push` handlers emit the stack
3162        // array and `buf[k]=expr` fills. (init_array_fill runs inside the O3 `Let` handler.)
3163        for (sym, (elem_ty, len)) in &func_sl {
3164            let ty = format!("[{}; {}]", elem_ty, len);
3165            let name = interner.resolve(*sym).to_string();
3166            let mut syms: HashSet<Symbol> = HashSet::new();
3167            collect_named_syms(body, &name, interner, &mut syms);
3168            for s in syms {
3169                func_ctx.register_variable_type(s, ty.clone());
3170            }
3171        }
3172
3173        // Cursor-filled buffers: register `[T; N]` + a fill cursor for every use-site symbol, so
3174        // the `Let` handler emits `let mut V: [T; N] = [<zero>; N]; let mut __V_fill = 0;` and each
3175        // `Push x to V` lowers to `V[__V_fill] = x; __V_fill += 1;` (the loop_fill_array path the
3176        // array-return digest already uses). The reads hit the `[T; N]` array via the registered type.
3177        for (sym, info) in &func_seq_fill {
3178            let ty = format!("[{}; {}]", info.elem_ty, info.len);
3179            let bufname = interner.resolve(*sym).to_string();
3180            let cursor = format!("__{}_fill", names.ident(*sym));
3181            let mut syms: HashSet<Symbol> = HashSet::new();
3182            collect_named_syms(body, &bufname, interner, &mut syms);
3183            for s in syms {
3184                func_ctx.register_variable_type(s, ty.clone());
3185                func_ctx.set_loop_fill_array(s, cursor.clone());
3186            }
3187        }
3188
3189        // Step 3b: register the `[T; N]` type for this function's own fixed-size return buffer and for every
3190        // caller result variable bound to an array-return fn — for every name-matching symbol, so the O3
3191        // `[T; N]` scalarization (stack decl + indexed-write fill) and the array-aware call/borrow/iterate
3192        // codegen all dispatch on it. Registered here (after const-table/scratch) so nothing overwrites it.
3193        for (sym, ty) in super::affine_array::array_var_types(body, array_return, array_return_fns)
3194        {
3195            let name = interner.resolve(sym).to_string();
3196            let mut syms: HashSet<Symbol> = HashSet::new();
3197            collect_named_syms(body, &name, interner, &mut syms);
3198            for s in syms {
3199                func_ctx.register_variable_type(s, ty.clone());
3200            }
3201        }
3202        // A LOOP-built return buffer (the digest) fills its `[T; N]` through a runtime cursor. Register the
3203        // return buffer (the `Return out` identifier) so the `Let` declares the cursor and each `Push`
3204        // becomes `out[cursor]=v; cursor+=1` instead of the compile-time O3 fill (which only counts static
3205        // push sites — a loop would write slot 0 repeatedly).
3206        if array_return.map_or(false, |i| i.loop_built) {
3207            if let Some(Stmt::Return {
3208                value: Some(Expr::Identifier(out)),
3209            }) = body.last()
3210            {
3211                let cursor = format!("__{}_fill", names.ident(*out));
3212                let name = interner.resolve(*out).to_string();
3213                let mut syms: HashSet<Symbol> = HashSet::new();
3214                collect_named_syms(body, &name, interner, &mut syms);
3215                for s in syms {
3216                    func_ctx.set_loop_fill_array(s, cursor.clone());
3217                }
3218            }
3219        }
3220
3221        // Leaf-outlining: a self-recursive `&mut [T]` in-place function keeps its
3222        // hot loop embedded in the recursion, where LLVM optimizes it worse than a
3223        // hand-written leaf `partition`. When eligible, the plain-body branch below
3224        // extracts the non-recursive work region into an `#[inline(never)]` leaf
3225        // helper, rendered here and prepended to the wrapper at return.
3226        let mut outlined_helper = String::new();
3227
3228        if is_tce {
3229            // TCE: Wrap body in loop, use TCE-aware statement emitter
3230            writeln!(output, "    loop {{").unwrap();
3231            let stmt_refs: Vec<&Stmt> = body
3232                .iter()
3233                .filter(|s| {
3234                    !is_affine_array_decl(s, &func_ctx) && !is_const_table_stmt(s, &func_ctx)
3235                })
3236                .collect();
3237            let mut si = 0;
3238            while si < stmt_refs.len() {
3239                // Self-tail-call PAIR: `Set/Let x = self(args); Return x` lowers to
3240                // the same loop-back as a direct `Return self(args)` (the binding
3241                // flows straight into the return). Matches the VM and tree-walker.
3242                if si + 1 < stmt_refs.len() {
3243                    if let Some(call_args) = crate::tail_call::tail_pair_args(
3244                        stmt_refs[si],
3245                        stmt_refs[si + 1],
3246                        name,
3247                        param_syms.len(),
3248                    ) {
3249                        output.push_str(&codegen_tce_loopback(
3250                            call_args,
3251                            &param_syms,
3252                            interner,
3253                            2,
3254                            &mut func_ctx,
3255                            &mut func_synced_vars,
3256                            async_functions,
3257                        ));
3258                        si += 2;
3259                        continue;
3260                    }
3261                }
3262                if !no_peephole {
3263                    if let Some((code, skip)) = super::peephole::try_block_peepholes(
3264                        &stmt_refs,
3265                        si,
3266                        interner,
3267                        2,
3268                        &func_mutable_vars,
3269                        &mut func_ctx,
3270                        lww_fields,
3271                        mv_fields,
3272                        &mut func_synced_vars,
3273                        &func_var_caps,
3274                        async_functions,
3275                        &func_pipe_vars,
3276                        boxed_fields,
3277                        registry,
3278                        type_env,
3279                    ) {
3280                        output.push_str(&code);
3281                        si += 1 + skip;
3282                        continue;
3283                    }
3284                }
3285                output.push_str(&codegen_stmt_tce(
3286                    stmt_refs[si],
3287                    name,
3288                    &param_syms,
3289                    interner,
3290                    2,
3291                    &func_mutable_vars,
3292                    &mut func_ctx,
3293                    lww_fields,
3294                    mv_fields,
3295                    &mut func_synced_vars,
3296                    &func_var_caps,
3297                    async_functions,
3298                    &func_pipe_vars,
3299                    boxed_fields,
3300                    registry,
3301                    type_env,
3302                ));
3303                si += 1;
3304            }
3305            writeln!(output, "    }}").unwrap();
3306        } else if let Some(ref acc) = acc_info {
3307            // Accumulator Introduction: Wrap body in loop with accumulator variable
3308            if super::tower::returns(name) {
3309                writeln!(
3310                    output,
3311                    "    let mut __acc: {} = LogosValue::Int({}_i64);",
3312                    super::tower::VALUE,
3313                    acc.identity
3314                )
3315                .unwrap();
3316            } else {
3317                writeln!(output, "    let mut __acc: i64 = {};", acc.identity).unwrap();
3318            }
3319            writeln!(output, "    loop {{").unwrap();
3320            let stmt_refs: Vec<&Stmt> = body
3321                .iter()
3322                .filter(|s| {
3323                    !is_affine_array_decl(s, &func_ctx) && !is_const_table_stmt(s, &func_ctx)
3324                })
3325                .collect();
3326            let mut si = 0;
3327            while si < stmt_refs.len() {
3328                if !no_peephole {
3329                    if let Some((code, skip)) = super::peephole::try_block_peepholes(
3330                        &stmt_refs,
3331                        si,
3332                        interner,
3333                        2,
3334                        &func_mutable_vars,
3335                        &mut func_ctx,
3336                        lww_fields,
3337                        mv_fields,
3338                        &mut func_synced_vars,
3339                        &func_var_caps,
3340                        async_functions,
3341                        &func_pipe_vars,
3342                        boxed_fields,
3343                        registry,
3344                        type_env,
3345                    ) {
3346                        output.push_str(&code);
3347                        si += 1 + skip;
3348                        continue;
3349                    }
3350                }
3351                output.push_str(&codegen_stmt_acc(
3352                    stmt_refs[si],
3353                    name,
3354                    &param_syms,
3355                    acc,
3356                    interner,
3357                    2,
3358                    &func_mutable_vars,
3359                    &mut func_ctx,
3360                    lww_fields,
3361                    mv_fields,
3362                    &mut func_synced_vars,
3363                    &func_var_caps,
3364                    async_functions,
3365                    &func_pipe_vars,
3366                    boxed_fields,
3367                    registry,
3368                    type_env,
3369                ));
3370                si += 1;
3371            }
3372            writeln!(output, "    }}").unwrap();
3373        } else if let Some(ref cf) = closed_form_info {
3374            // Closed-form: f(d) = ((base + k) << d) - k
3375            let param_name = names.ident(params[0].0);
3376            let base_plus_k = cf.base + cf.k;
3377            writeln!(
3378                output,
3379                "    if {} == 0 {{ return {}; }}",
3380                param_name, cf.base
3381            )
3382            .unwrap();
3383            // Multiply by 2^d with a shift that yields 0 once d reaches the i64
3384            // bit width, matching the recurrence's repeated WRAPPING doubling
3385            // (a raw `<< d` is UB in debug and masks the count in release for
3386            // d >= 64, diverging from the interpreter/VM).
3387            let pow2d = format!(
3388                "(if ({p} as u64) >= 64 {{ 0i64 }} else {{ 1i64 << {p} }})",
3389                p = param_name
3390            );
3391            if cf.k == 0 {
3392                writeln!(output, "    {}i64.wrapping_mul({})", base_plus_k, pow2d).unwrap();
3393            } else {
3394                writeln!(
3395                    output,
3396                    "    ({}i64.wrapping_mul({})).wrapping_sub({})",
3397                    base_plus_k, pow2d, cf.k
3398                )
3399                .unwrap();
3400            }
3401        } else if is_memo {
3402            // Memoization: Wrap body in closure with thread-local cache
3403            let ret_ty = return_type_str.as_deref().unwrap_or("i64");
3404            let memo_name = format!("__MEMO_{}", func_name.to_uppercase());
3405
3406            // Build key type and key expression
3407            let (key_type, key_expr, copy_method) = if params.len() == 1 {
3408                let ty = codegen_type_expr(params[0].1, interner);
3409                let pname = interner.resolve(params[0].0).to_string();
3410                let copy = if is_copy_type_expr(params[0].1, interner) {
3411                    "copied"
3412                } else {
3413                    "cloned"
3414                };
3415                (ty, pname, copy)
3416            } else {
3417                let types: Vec<String> = params
3418                    .iter()
3419                    .map(|(_, t)| codegen_type_expr(t, interner))
3420                    .collect();
3421                let names: Vec<String> = params
3422                    .iter()
3423                    .map(|(n, _)| interner.resolve(*n).to_string())
3424                    .collect();
3425                let copy = if params.iter().all(|(_, t)| is_copy_type_expr(t, interner)) {
3426                    "copied"
3427                } else {
3428                    "cloned"
3429                };
3430                (
3431                    format!("({})", types.join(", ")),
3432                    format!("({})", names.join(", ")),
3433                    copy,
3434                )
3435            };
3436
3437            writeln!(output, "    use std::cell::RefCell;").unwrap();
3438            writeln!(output, "    thread_local! {{").unwrap();
3439            writeln!(output, "        static {}: RefCell<FxHashMap<{}, {}>> = RefCell::new(FxHashMap::default());", memo_name, key_type, ret_ty).unwrap();
3440            writeln!(output, "    }}").unwrap();
3441            writeln!(
3442                output,
3443                "    if let Some(__v) = {}.with(|c| c.borrow().get(&{}).{}()) {{",
3444                memo_name, key_expr, copy_method
3445            )
3446            .unwrap();
3447            writeln!(output, "        return __v;").unwrap();
3448            writeln!(output, "    }}").unwrap();
3449            writeln!(output, "    let __memo_result = (|| -> {} {{", ret_ty).unwrap();
3450            let stmt_refs: Vec<&Stmt> = body
3451                .iter()
3452                .filter(|s| {
3453                    !is_affine_array_decl(s, &func_ctx) && !is_const_table_stmt(s, &func_ctx)
3454                })
3455                .collect();
3456            let mut si = 0;
3457            while si < stmt_refs.len() {
3458                if !no_peephole {
3459                    if let Some((code, skip)) = super::peephole::try_block_peepholes(
3460                        &stmt_refs,
3461                        si,
3462                        interner,
3463                        2,
3464                        &func_mutable_vars,
3465                        &mut func_ctx,
3466                        lww_fields,
3467                        mv_fields,
3468                        &mut func_synced_vars,
3469                        &func_var_caps,
3470                        async_functions,
3471                        &func_pipe_vars,
3472                        boxed_fields,
3473                        registry,
3474                        type_env,
3475                    ) {
3476                        output.push_str(&code);
3477                        si += 1 + skip;
3478                        continue;
3479                    }
3480                }
3481                output.push_str(&codegen_stmt(
3482                    stmt_refs[si],
3483                    interner,
3484                    2,
3485                    &func_mutable_vars,
3486                    &mut func_ctx,
3487                    lww_fields,
3488                    mv_fields,
3489                    &mut func_synced_vars,
3490                    &func_var_caps,
3491                    async_functions,
3492                    &func_pipe_vars,
3493                    boxed_fields,
3494                    registry,
3495                    type_env,
3496                ));
3497                si += 1;
3498            }
3499            writeln!(output, "    }})();").unwrap();
3500            writeln!(
3501                output,
3502                "    {}.with(|c| c.borrow_mut().insert({}, __memo_result));",
3503                memo_name, key_expr
3504            )
3505            .unwrap();
3506            writeln!(output, "    __memo_result").unwrap();
3507        } else {
3508            let stmt_refs: Vec<&Stmt> = body
3509                .iter()
3510                .filter(|s| {
3511                    !is_affine_array_decl(s, &func_ctx) && !is_const_table_stmt(s, &func_ctx)
3512                })
3513                .collect();
3514
3515            // Codegen a contiguous span `[lo, hi)` of `stmt_refs` through the exact
3516            // peephole+statement path the plain body uses, into `$target`. A
3517            // sub-slice bounds the peephole look-ahead to the span.
3518            macro_rules! emit_span {
3519                ($target:expr, $lo:expr, $hi:expr) => {{
3520                    let sub = &stmt_refs[$lo..$hi];
3521                    let mut k = 0usize;
3522                    while k < sub.len() {
3523                        if !no_peephole {
3524                            if let Some((code, skip)) = super::peephole::try_block_peepholes(
3525                                sub,
3526                                k,
3527                                interner,
3528                                1,
3529                                &func_mutable_vars,
3530                                &mut func_ctx,
3531                                lww_fields,
3532                                mv_fields,
3533                                &mut func_synced_vars,
3534                                &func_var_caps,
3535                                async_functions,
3536                                &func_pipe_vars,
3537                                boxed_fields,
3538                                registry,
3539                                type_env,
3540                            ) {
3541                                $target.push_str(&code);
3542                                k += 1 + skip;
3543                                continue;
3544                            }
3545                        }
3546                        $target.push_str(&codegen_stmt(
3547                            sub[k],
3548                            interner,
3549                            1,
3550                            &func_mutable_vars,
3551                            &mut func_ctx,
3552                            lww_fields,
3553                            mv_fields,
3554                            &mut func_synced_vars,
3555                            &func_var_caps,
3556                            async_functions,
3557                            &func_pipe_vars,
3558                            boxed_fields,
3559                            registry,
3560                            type_env,
3561                        ));
3562                        k += 1;
3563                    }
3564                }};
3565            }
3566
3567            // Eligibility: a Borrow-lowered (`&mut [T]`) self-recursive function
3568            // matching the divide-and-conquer shape.
3569            let outline_plan = if !mut_borrow_indices.is_empty()
3570                && crate::optimize::active_config()
3571                    .merged(opt_flags)
3572                    .is_on(Opt::Borrow)
3573                && std::env::var("LOGOS_NO_OUTLINE").is_err()
3574            {
3575                mut_borrow_indices
3576                    .iter()
3577                    .min()
3578                    .and_then(|&i| params.get(i))
3579                    .and_then(|(slice_param, _)| {
3580                        super::outline::plan_outline(name, &stmt_refs, *slice_param)
3581                    })
3582            } else {
3583                None
3584            };
3585
3586            if let Some(plan) = outline_plan {
3587                crate::optimize::mark_fired(Opt::Borrow);
3588                // The leaf helper's body IS the work region — rendered through the
3589                // ordinary path, so BCE and the counter de-guard land identically.
3590                // Repeat the entry precondition assert at the top of the leaf: the
3591                // hard `hi <= arr.len()` bound (not just the per-access
3592                // `assert_unchecked` hints) is what lets LLVM optimize the whole
3593                // loop, and the leaf is a separate function the wrapper's assert
3594                // cannot reach into.
3595                let mut helper_body = String::new();
3596                if let Some(g) = super::entry_guard::detect_entry_guard(params, body, interner) {
3597                    let arr = names.ident(g.arr);
3598                    let lo = names.ident(g.lo);
3599                    let hi = names.ident(g.hi);
3600                    let adj = g.hi_len_adjust;
3601                    writeln!(
3602                        helper_body,
3603                        "    if ({lo}) < ({hi}) {{ let __{arr}_glen = {arr}.len() as i64 + {adj}; assert!(({lo}) >= 1 && ({hi}) <= __{arr}_glen, \"LOGOS precondition guard: 1-based index range\"); }}"
3604                    )
3605                    .unwrap();
3606                }
3607                emit_span!(helper_body, plan.region_start, plan.region_end);
3608                // The wrapper: base-case guards, the helper call, the alias, then
3609                // the recursive calls. `func_ctx` already learned the region's
3610                // locals (`i`, `result`), so the trailing calls type-check.
3611                emit_span!(output, 0, plan.region_start);
3612                let liveouts: Vec<String> =
3613                    plan.live_outs.iter().map(|s| names.ident(*s)).collect();
3614                let args: Vec<String> = params.iter().map(|(s, _)| names.ident(*s)).collect();
3615                let bind = if liveouts.len() == 1 {
3616                    liveouts[0].clone()
3617                } else {
3618                    format!("({})", liveouts.join(", "))
3619                };
3620                writeln!(
3621                    output,
3622                    "    let {} = {}__part({});",
3623                    bind,
3624                    func_name,
3625                    args.join(", ")
3626                )
3627                .unwrap();
3628                for lo in &plan.live_outs {
3629                    func_ctx.register_variable_type(*lo, "i64".to_string());
3630                }
3631                if let Some(ai) = plan.alias_idx {
3632                    emit_span!(output, ai, ai + 1);
3633                }
3634                emit_span!(output, plan.region_end, stmt_refs.len());
3635                // Assemble the leaf (prepended before the wrapper at return). Same
3636                // parameter list as the wrapper (`&mut [T]`, scalars), returning the
3637                // live-outs — assumed `i64` (LOGOS `Int`); a wrong assumption is a
3638                // loud compile error, never silent corruption.
3639                let ret_ty = if liveouts.len() == 1 {
3640                    "i64".to_string()
3641                } else {
3642                    format!("({})", vec!["i64"; liveouts.len()].join(", "))
3643                };
3644                let ret_expr = if liveouts.len() == 1 {
3645                    liveouts[0].clone()
3646                } else {
3647                    format!("({})", liveouts.join(", "))
3648                };
3649                outlined_helper = format!(
3650                    "#[inline(never)]\nfn {}__part({}) -> {} {{\n{}    {}\n}}\n\n",
3651                    func_name,
3652                    params_str.join(", "),
3653                    ret_ty,
3654                    helper_body,
3655                    ret_expr
3656                );
3657            } else {
3658                emit_span!(output, 0, stmt_refs.len());
3659            }
3660        }
3661
3662        if wrap_catch_unwind {
3663            writeln!(output, "    }})) {{").unwrap();
3664            writeln!(output, "        Ok(__v) => __v,").unwrap();
3665            writeln!(output, "        Err(__panic) => {{").unwrap();
3666            writeln!(output, "            let __msg = if let Some(s) = __panic.downcast_ref::<String>() {{ s.clone() }} else if let Some(s) = __panic.downcast_ref::<&str>() {{ s.to_string() }} else {{ \"Unknown panic\".to_string() }};").unwrap();
3667            writeln!(output, "            logos_set_last_error(__msg);").unwrap();
3668            // Determine default for panic case based on return type
3669            if let Some(ref ret_str) = return_type_str {
3670                if ret_str != "()" {
3671                    writeln!(output, "            Default::default()").unwrap();
3672                }
3673            }
3674            writeln!(output, "        }}").unwrap();
3675            writeln!(output, "    }}").unwrap();
3676        }
3677
3678        writeln!(output, "}}\n").unwrap();
3679
3680        // Emit the outlined leaf helper before its wrapper.
3681        if !outlined_helper.is_empty() {
3682            output = format!("{}{}", outlined_helper, output);
3683        }
3684    }
3685
3686    output
3687}
3688
3689/// Whether the `logicaffeine_system` function behind native `name` answers `Result<T, String>` and
3690/// its `Err` is a failure of the program, not a value: crypto.lg's kernels and the FIPS-202 hashes.
3691fn refuses_by_failing(name: &str) -> bool {
3692    crate::semantics::native_kernels::NativeKernel::from_name(name).is_some()
3693        || crate::semantics::builtins::rust_only_native(name).is_some()
3694}
3695
3696/// Phase 38: Map native function names to logicaffeine_system module paths.
3697/// For system functions only — user-defined native paths bypass this entirely.
3698/// Returns None for unknown functions (caller emits compile_error!).
3699fn map_native_function(name: &str) -> Option<(&'static str, &'static str)> {
3700    // crypto.lg's kernels come from the ONE table every tier reads (the tree-walker and VM call
3701    // the same functions through `NativeKernel::call`).
3702    if let Some(kernel) = crate::semantics::native_kernels::NativeKernel::from_name(name) {
3703        return Some(kernel.rust_path());
3704    }
3705    if let Some(linked) = crate::semantics::builtins::rust_only_native(name) {
3706        return Some(linked);
3707    }
3708    match name {
3709        "read" => Some(("file", "read")),
3710        "write" => Some(("file", "write")),
3711        "tcpConnect" => Some(("tcp", "connect")),
3712        "tcpConnectTls" => Some(("tcp", "connect_tls")),
3713        "tcpUpgradeTls" => Some(("tcp", "upgrade_tls")),
3714        "tcpSend" => Some(("tcp", "send")),
3715        "tcpRecv" => Some(("tcp", "recv")),
3716        "tcpRecvExact" => Some(("tcp", "recv_exact")),
3717        "tcpClose" => Some(("tcp", "close")),
3718        "tcpSetTimeout" => Some(("tcp", "set_timeout")),
3719        "tcpListen" => Some(("tcp", "listen")),
3720        "tcpAccept" => Some(("tcp", "accept")),
3721        "tcpListenerPort" => Some(("tcp", "listener_port")),
3722        "tcpShutdownWrite" => Some(("tcp", "shutdown_write")),
3723        "now" => Some(("time", "now")),
3724        "sleep" => Some(("time", "sleep")),
3725        "randomInt" => Some(("random", "randomInt")),
3726        "randomFloat" => Some(("random", "randomFloat")),
3727        "get" => Some(("env", "get")),
3728        "args" => Some(("env", "args")),
3729        "parseInt" => Some(("text", "parseInt")),
3730        "parseFloat" => Some(("text", "parseFloat")),
3731        "chr" => Some(("text", "chr")),
3732        "format" => Some(("fmt", "format")),
3733        _ => None,
3734    }
3735}