Skip to main content

logicaffeine_compile/codegen_c/
mod.rs

1use std::collections::HashMap;
2use std::fmt::Write;
3
4use crate::analysis::TypeRegistry;
5use crate::ast::stmt::*;
6use crate::intern::{Interner, Symbol};
7use logicaffeine_language::ast_depth::{expr_children, for_each_node, walk_nodes, Visited, Walk};
8
9pub mod concurrency;
10pub mod cshake;
11pub(crate) mod emit;
12mod absent;
13mod equality;
14mod exact;
15pub mod from_program;
16mod numbers;
17pub(crate) mod runtime;
18mod sharing;
19mod stepped;
20pub(crate) mod tower;
21pub(crate) mod types;
22pub mod value_runtime;
23mod values;
24mod word_ranges;
25pub(crate) mod words;
26
27use runtime::{
28    c_net_runtime, c_runtime, C_CONCURRENCY_RUNTIME, C_CRDT_RUNTIME, C_STEPPED_HOST,
29    STEPPED_SCHEDULER,
30};
31
32/// Marks the boundary between the fixed runtime/type prelude and the program's own
33/// code in a `codegen_program_c` translation unit. The CUDA AOT tier splits here to
34/// lift the user code onto the device; it is an ordinary C comment to gcc.
35pub const USER_CODE_SENTINEL: &str = "// ==== LOGOS user code (device-liftable) ====";
36
37/// The C family's scheduler: `logicaffeine_runtime::Scheduler::process_step` ported once, in C every
38/// tier compiles — the host C and RISC-V coroutine runtimes, and the stepped tier's frames CUDA and the
39/// bytecode walker run. A tier defines its qualifiers, its allocator and its own task fields before
40/// this text, and supplies only the yield (see the file's header).
41pub const SCHED_CORE: &str = include_str!("sched_core.c");
42
43/// The C family's convergent collections: the data crate's observed-remove set (add-wins and remove-wins) and
44/// its observed-remove map of last-writer values, ported once, in C every tier compiles — both C generators,
45/// the stepped tier and RISC-V. A tier defines its qualifiers and its allocator before this text (see the
46/// file's header).
47pub const CRDT_CORE: &str = include_str!("crdt_core.c");
48
49/// The files a program reads, writes and mounts (`Read … from file`, `Write … to file`, `Mount`), resolved under
50/// the working directory as the native file system resolves them. Emitted only for a program that uses one.
51pub const FILE_RUNTIME: &str = include_str!("file_io.c");
52
53/// The list of values-or-nothing (`Seq_logos_opt`): its storage, whatever the values hold.
54const OPT_SEQ_FAMILY: &str = "typedef struct { logos_opt *data; size_t len; size_t cap; } Seq_logos_opt;
55__attribute__((unused)) static Seq_logos_opt seq_logos_opt_new(void) { return (Seq_logos_opt){NULL, 0, 0}; }
56__attribute__((unused)) static void seq_logos_opt_push(Seq_logos_opt *s, logos_opt val) { if (s->len == s->cap) { s->cap = s->cap ? s->cap * 2 : 8; s->data = (logos_opt *)lc_gc_realloc(s->data, s->cap * sizeof(logos_opt)); } s->data[s->len++] = val; }
57__attribute__((unused)) static logos_opt seq_logos_opt_get(Seq_logos_opt *s, int64_t idx) { return s->data[logos_idx0(idx, s->len)]; }
58__attribute__((unused)) static void seq_logos_opt_set(Seq_logos_opt *s, int64_t idx, logos_opt val) { s->data[logos_idx0(idx, s->len)] = val; }
59__attribute__((unused)) static int64_t seq_logos_opt_len(Seq_logos_opt *s) { return (int64_t)s->len; }
60";
61
62/// A value-or-nothing (`logos_opt`) for a program without the scheduler, whose runtime carries it otherwise.
63const OPT_RUNTIME: &str = concat!(
64    "\n#ifndef LOGOS_API\n#define LOGOS_API static __attribute__((unused))\n#endif\n",
65    include_str!("opt.c"),
66);
67
68/// The names a zone or a spawned agent binds to nothing that the program also reads or sets by name: the only
69/// ones a variable is needed for.
70fn nothing_names(stmts: &[Stmt]) -> std::collections::HashSet<Symbol> {
71    let (mut bound, mut named) = (
72        std::collections::HashSet::new(),
73        std::collections::HashSet::new(),
74    );
75    for_each_node(stmts, |node| match node {
76        Visited::Stmt(Stmt::Zone { name, .. } | Stmt::Spawn { name, .. }) => {
77            bound.insert(*name);
78        }
79        Visited::Expr(Expr::Identifier(sym)) | Visited::Stmt(Stmt::Set { target: sym, .. }) => {
80            named.insert(*sym);
81        }
82        _ => {}
83    });
84    bound.intersection(&named).copied().collect()
85}
86
87/// The functions a call to which neither fails nor acts: every parameter and the result a number or a truth
88/// value, and a body of bindings of its own names, branches, loops and `Return`s over sums, differences,
89/// products and comparisons of numbers (which never fail: an `Int` past `i64` is exact) and calls to such
90/// functions — nothing read from outside the call. The largest such set: a function assumed quiet stays so unless
91/// its body proves otherwise, so a recursive one is quiet when its recursion is.
92fn quiet_functions(stmts: &[Stmt], interner: &Interner) -> std::collections::HashSet<Symbol> {
93    use std::collections::HashSet;
94    let scalar = |t: &TypeExpr| matches!(t, TypeExpr::Primitive(n) | TypeExpr::Named(n) if matches!(interner.resolve(*n), "Int" | "Real" | "Float" | "Bool"));
95    let candidates: Vec<(Symbol, HashSet<Symbol>, &[Stmt])> = stmts
96        .iter()
97        .filter_map(|s| match s {
98            Stmt::FunctionDef {
99                name,
100                params,
101                body,
102                return_type: Some(rt),
103                is_native: false,
104                ..
105            } if scalar(rt) && params.iter().all(|(_, t)| scalar(t)) => {
106                Some((*name, params.iter().map(|(p, _)| *p).collect(), *body))
107            }
108            _ => None,
109        })
110        .collect();
111    let mut quiet: HashSet<Symbol> = candidates.iter().map(|(n, _, _)| *n).collect();
112    fn expr_quiet(e: &Expr, names: &HashSet<Symbol>, quiet: &HashSet<Symbol>) -> bool {
113        match e {
114            Expr::Literal(
115                crate::ast::stmt::Literal::Number(_)
116                | crate::ast::stmt::Literal::Float(_)
117                | crate::ast::stmt::Literal::Boolean(_),
118            ) => true,
119            Expr::Identifier(s) => names.contains(s),
120            Expr::Not { operand } => expr_quiet(operand, names, quiet),
121            Expr::BinaryOp { op, left, right } => {
122                use crate::ast::stmt::BinaryOpKind as Op;
123                matches!(
124                    op,
125                    Op::Add
126                        | Op::Subtract
127                        | Op::Multiply
128                        | Op::Eq
129                        | Op::NotEq
130                        | Op::Lt
131                        | Op::Gt
132                        | Op::LtEq
133                        | Op::GtEq
134                        | Op::And
135                        | Op::Or
136                ) && expr_quiet(left, names, quiet)
137                    && expr_quiet(right, names, quiet)
138            }
139            Expr::Call { function, args } => {
140                quiet.contains(function) && args.iter().all(|a| expr_quiet(a, names, quiet))
141            }
142            _ => false,
143        }
144    }
145    fn block_quiet(body: &[Stmt], names: &mut HashSet<Symbol>, quiet: &HashSet<Symbol>) -> bool {
146        body.iter().all(|s| match s {
147            Stmt::Let { var, value, .. } => {
148                let ok = expr_quiet(value, names, quiet);
149                names.insert(*var);
150                ok
151            }
152            Stmt::Set { target, value } => {
153                names.contains(target) && expr_quiet(value, names, quiet)
154            }
155            Stmt::If {
156                cond,
157                then_block,
158                else_block,
159            } => {
160                expr_quiet(cond, names, quiet)
161                    && block_quiet(then_block, &mut names.clone(), quiet)
162                    && else_block.map_or(true, |b| block_quiet(b, &mut names.clone(), quiet))
163            }
164            Stmt::While { cond, body, .. } => {
165                expr_quiet(cond, names, quiet) && block_quiet(body, &mut names.clone(), quiet)
166            }
167            Stmt::Return { value: Some(v) } => expr_quiet(v, names, quiet),
168            _ => false,
169        })
170    }
171    loop {
172        let before = quiet.len();
173        for (name, params, body) in &candidates {
174            if quiet.contains(name) && !block_quiet(body, &mut params.clone(), &quiet) {
175                quiet.remove(name);
176            }
177        }
178        if quiet.len() == before {
179            return quiet;
180        }
181    }
182}
183
184/// The C of a program every run of which fails before any output, `reason` on stderr: what a program the VM
185/// refuses before running it does.
186pub fn refused_program(reason: &str) -> String {
187    format!(
188        "#include <stdio.h>\n\nint main(void) {{\n    fputs({}, stderr);\n    return 1;\n}}\n",
189        emit::c_string_literal(&format!("{reason}\n"))
190    )
191}
192
193/// Texts a program appends to in place, and texts joined from several parts (see `text_builder.c`).
194const TEXT_BUILDER: &str = include_str!("text_builder.c");
195/// Machine-word arithmetic that notices when it leaves the word, and the exact `&` it falls back to.
196const CHECKED_INT: &str = include_str!("checked_int.c");
197
198/// A function value: the code it runs, which takes the environment first, and the environment.
199const CLOSURE_TYPE: &str = "\ntypedef struct { void *call; void *env; } LClosure;\n";
200
201/// Whether the program reads, writes or mounts a file anywhere.
202fn program_uses_files(stmts: &[Stmt]) -> bool {
203    let mut uses = false;
204    for_each_node(stmts, |node| {
205        uses |= matches!(
206            node,
207            Visited::Stmt(
208                Stmt::ReadFrom {
209                    source: ReadSource::File(_),
210                    ..
211                } | Stmt::WriteFile { .. }
212                    | Stmt::Mount { .. }
213            )
214        );
215    });
216    uses
217}
218
219/// How a concurrent program's tasks run: as coroutines on stacks of their own (`ucontext`, host C), or as
220/// resumable step functions over heap frames (the stepped tier: the host walker and the GPU).
221#[derive(Clone, Copy, Debug, PartialEq, Eq)]
222pub enum TaskTier {
223    Coroutines,
224    Stepped,
225}
226
227/// Is this statement one of LOGOS's deterministic-concurrency operations — channels, tasks, `Await the
228/// first of`, virtual-time `Sleep`?
229pub(super) fn is_concurrency_stmt(s: &Stmt) -> bool {
230    matches!(
231        s,
232        Stmt::LaunchTask { .. }
233            | Stmt::LaunchTaskWithHandle { .. }
234            | Stmt::CreatePipe { .. }
235            | Stmt::SendPipe { .. }
236            | Stmt::ReceivePipe { .. }
237            | Stmt::TrySendPipe { .. }
238            | Stmt::TryReceivePipe { .. }
239            | Stmt::StopTask { .. }
240            | Stmt::CloseChannel { .. }
241            | Stmt::AwaitTask { .. }
242            | Stmt::Select { .. }
243            | Stmt::Sleep { .. }
244    )
245}
246
247/// Whether the program uses concurrency anywhere — Main, every function body, every nested block. This
248/// is the GATE for the scheduler runtime and the `main`-as-a-task bootstrap: when it is `false`,
249/// `codegen_program_c` emits the C a world without the scheduler would, byte for byte.
250pub(crate) fn program_uses_concurrency(stmts: &[Stmt]) -> bool {
251    let mut uses = false;
252    for_each_node(stmts, |node| {
253        if let Visited::Stmt(s) = node {
254            uses |= is_concurrency_stmt(s);
255        }
256    });
257    uses
258}
259
260/// Whether a statement uses the offline networking transport — the same kind of gate as
261/// `program_uses_concurrency`, so a non-net program emits byte-identical C (the ~1246 non-net tests stay
262/// fixed). `Listen`/`ConnectTo`/`LetPeerAgent`/`Sync`/`SendMessage`/`StreamMessage`/`AwaitMessage`.
263fn stmt_uses_net(s: &Stmt) -> bool {
264    match s {
265        Stmt::Listen { .. }
266        | Stmt::ConnectTo { .. }
267        | Stmt::LetPeerAgent { .. }
268        | Stmt::Sync { .. }
269        | Stmt::SendMessage { .. }
270        | Stmt::StreamMessage { .. }
271        | Stmt::AwaitMessage { .. } => true,
272        Stmt::If {
273            then_block,
274            else_block,
275            ..
276        } => {
277            then_block.iter().any(stmt_uses_net)
278                || else_block
279                    .map(|b| b.iter().any(stmt_uses_net))
280                    .unwrap_or(false)
281        }
282        Stmt::While { body, .. } | Stmt::Repeat { body, .. } | Stmt::FunctionDef { body, .. } => {
283            body.iter().any(stmt_uses_net)
284        }
285        _ => false,
286    }
287}
288
289/// Whether the whole program uses the offline networking transport (Main + every function body).
290fn program_uses_net(stmts: &[Stmt]) -> bool {
291    stmts.iter().any(stmt_uses_net)
292}
293
294/// NOTHING delegates to the AST-C backend anymore — the flat Op-walker lowers EVERY bytecode op it can reach
295/// natively, including the LAST holdout, the real-socket duplex TCP client (`Tcp`, over the `C_TCP_RUNTIME`
296/// POSIX socket runtime), alongside the offline networking transport (`Net*`, the loopback `c_net_runtime`),
297/// the single-replica CRDT lattice (`Crdt*`/`NewCrdt`), and runtime authorization (`CheckPolicy`). The gate is
298/// EMPTY: this always returns `false`. It is kept (rather than deleted) as the honest, self-documenting proof
299/// that the delegation set is closed — a future op that genuinely cannot be lowered would be added to
300/// `ASTC_ONLY_OPS` here, and the census locks would force that decision. Reading the FINALIZED bytecode (not
301/// the AST) means it can never disagree with what actually runs.
302pub(crate) fn program_needs_astc_delegation(program: &crate::vm::CompiledProgram) -> bool {
303    const ASTC_ONLY_OPS: &[&str] = &[];
304    // Every function body is compiled into the single flat `code` op stream (indexed by `entry_pc`),
305    // so one scan of `code` sees Main and every function.
306    program
307        .code
308        .iter()
309        .any(|op| ASTC_ONLY_OPS.contains(&op.name()))
310}
311
312/// Whether a field's DECLARED type is a single-replica counter CRDT — a `ConvergentCount` (grow-only
313/// G-Counter) or a `Tally` (PN-Counter). Such a field's C cell holds a `logos_crdt*` handle (cast to the
314/// `int64_t` the declared `Int` field lays out as); reading it SUMS the per-replica map. The `GCounter`/
315/// `PNCounter` aliases are the internal names the same types are known by (matching the tree-walker's
316/// `new_counter`/`new_pn_counter` field detection + the RISC-V tier).
317fn field_type_is_counter_crdt(ft: &crate::analysis::FieldType, interner: &Interner) -> bool {
318    matches!(
319        ft,
320        crate::analysis::FieldType::Named(sym) | crate::analysis::FieldType::Primitive(sym)
321            if matches!(interner.resolve(*sym), "ConvergentCount" | "GCounter" | "Tally" | "PNCounter")
322    )
323}
324
325/// Every `(struct symbol, field symbol)` in the registry whose field is a counter CRDT. This is the
326/// side-set the codegen consults: seeding a `New` struct's counter fields, projecting a `FieldAccess` on
327/// one to the map SUM, and taking the per-replica MAX on `Merge`/`Join`.
328fn counter_crdt_fields(
329    registry: &TypeRegistry,
330    interner: &Interner,
331) -> std::collections::HashSet<(Symbol, Symbol)> {
332    let mut out = std::collections::HashSet::new();
333    for (name, def) in registry.iter_types() {
334        if let crate::analysis::TypeDef::Struct { fields, .. } = def {
335            for f in fields {
336                if field_type_is_counter_crdt(&f.ty, interner) {
337                    out.insert((*name, f.name));
338                }
339            }
340        }
341    }
342    out
343}
344
345/// Whether the program has ANY counter-CRDT field — the GATE for the `logos_crdt` runtime. When false,
346/// the CRDT runtime is not emitted and the output is byte-identical to a world without it (the invariant
347/// that keeps the ~1246 non-CRDT C tests fixed).
348fn program_uses_crdt_counter(registry: &TypeRegistry, interner: &Interner) -> bool {
349    !counter_crdt_fields(registry, interner).is_empty()
350}
351
352/// What each function's calls read and write of the program's file-scope statics ([`static_reach`]), for the
353/// shared operand sequencing (`optimize::sequence`).
354pub(crate) fn call_effects(stmts: &[Stmt]) -> crate::optimize::sequence::CallEffects {
355    let reach = static_reach(stmts);
356    let nonempty = |m: &HashMap<Symbol, std::collections::HashSet<Symbol>>| {
357        m.iter()
358            .filter(|(_, s)| !s.is_empty())
359            .map(|(f, s)| (*f, s.clone()))
360            .collect()
361    };
362    crate::optimize::sequence::CallEffects {
363        reads: nonempty(&reach.reach),
364        writes: nonempty(&reach.writes),
365    }
366}
367
368/// The texts a `mutable` parameter lends, by name (see `CContext::plain_texts`): each `mutable` Text parameter,
369/// and every name a call passes to one.
370fn lent_texts(stmts: &[Stmt], ctx: &CContext) -> std::collections::HashSet<String> {
371    let lends_text = |function: Symbol, i: usize| {
372        ctx.fn_inout
373            .get(&function)
374            .and_then(|ps| ps.get(i))
375            .copied()
376            .unwrap_or(false)
377            && ctx.fn_params.get(&function).and_then(|ps| ps.get(i)) == Some(&CType::String)
378    };
379    let mut out = std::collections::HashSet::new();
380    logicaffeine_language::ast_depth::for_each_node(stmts, |node| {
381        if let logicaffeine_language::ast_depth::Visited::Stmt(Stmt::FunctionDef {
382            name,
383            params,
384            ..
385        }) = node
386        {
387            for (i, (p, _)) in params.iter().enumerate() {
388                if lends_text(*name, i) {
389                    out.insert(ctx.interner.resolve(*p).to_string());
390                }
391            }
392        }
393    });
394    crate::analysis::callgraph::for_each_call_site(stmts, &mut |function, args| {
395        for (i, arg) in args.iter().enumerate() {
396            if let Expr::Identifier(x) = arg {
397                if lends_text(function, i) {
398                    out.insert(ctx.interner.resolve(*x).to_string());
399                }
400            }
401        }
402    });
403    out
404}
405
406/// The program's bindings a function reaches, and what the C tier refuses about them.
407struct ProgramStatics {
408    /// Each `## Main` root `Let` some `## To` body names, in the order Main binds them.
409    names: Vec<Symbol>,
410    /// Why the C tier cannot keep them faithfully, one sentence each (an `#error` apiece).
411    refusals: Vec<String>,
412}
413
414/// Main's statements at its root, through the blocks that run in place (`Splice`, `Reversibly`).
415fn root_statements<'s, 'a>(stmts: &'s [Stmt<'a>], out: &mut Vec<&'s Stmt<'a>>) {
416    for s in stmts {
417        match s {
418            Stmt::FunctionDef { .. } => {}
419            Stmt::Splice { body } | Stmt::Reversibly { body } => root_statements(body, out),
420            other => out.push(other),
421        }
422    }
423}
424
425/// The names a body reads or sets, and the functions it calls.
426fn names_and_calls(
427    body: &[Stmt],
428) -> (
429    std::collections::HashSet<Symbol>,
430    std::collections::HashSet<Symbol>,
431) {
432    let (mut names, mut calls) = (
433        std::collections::HashSet::new(),
434        std::collections::HashSet::new(),
435    );
436    for_each_node(body, |node| match node {
437        Visited::Expr(Expr::Identifier(sym)) => {
438            names.insert(*sym);
439        }
440        Visited::Expr(Expr::Call { function, .. }) | Visited::Stmt(Stmt::Call { function, .. }) => {
441            calls.insert(*function);
442        }
443        Visited::Stmt(Stmt::Set { target, .. }) => {
444            names.insert(*target);
445        }
446        _ => {}
447    });
448    (names, calls)
449}
450
451/// The program's bindings a function reaches, and, through every call, which of them each function reads and which
452/// it writes.
453pub(super) struct StaticReach<'s, 'a> {
454    /// Each `## Main` root `Let` some `## To` body names, in the order Main binds them.
455    pub(super) names: Vec<Symbol>,
456    /// The bindings each function reads or writes, its callees' included.
457    pub(super) reach: HashMap<Symbol, std::collections::HashSet<Symbol>>,
458    /// The bindings each function writes, its callees' included.
459    pub(super) writes: HashMap<Symbol, std::collections::HashSet<Symbol>>,
460    /// Main's root statements.
461    root: Vec<&'s Stmt<'a>>,
462    /// Each function's body and parameters.
463    functions: HashMap<Symbol, (&'s [Stmt<'a>], Vec<Symbol>)>,
464}
465
466/// The program's bindings a function reaches: every free name of a `## To` body (one it reads or sets but neither
467/// takes nor declares, `optimize::capture::free_names`) that `## Main` binds with a `Let` at its root, each a
468/// file-scope static in C; and what each function reaches and writes of them through the functions it calls.
469pub(super) fn static_reach<'s, 'a>(stmts: &'s [Stmt<'a>]) -> StaticReach<'s, 'a> {
470    let mut root = Vec::new();
471    root_statements(stmts, &mut root);
472    let mut root_lets: Vec<Symbol> = Vec::new();
473    for s in &root {
474        if let Stmt::Let { var, .. } = s {
475            if !root_lets.contains(var) {
476                root_lets.push(*var);
477            }
478        }
479    }
480    let functions: HashMap<Symbol, (&[Stmt], Vec<Symbol>)> = stmts
481        .iter()
482        .filter_map(|s| match s {
483            Stmt::FunctionDef {
484                name,
485                params,
486                body,
487                is_native: false,
488                ..
489            } => Some((*name, (&body[..], params.iter().map(|(p, _)| *p).collect()))),
490            _ => None,
491        })
492        .collect();
493    let mut direct: HashMap<Symbol, std::collections::HashSet<Symbol>> = HashMap::new();
494    let mut direct_writes: HashMap<Symbol, std::collections::HashSet<Symbol>> = HashMap::new();
495    let mut callees: HashMap<Symbol, std::collections::HashSet<Symbol>> = HashMap::new();
496    for (f, (body, params)) in &functions {
497        let (_, calls) = names_and_calls(body);
498        let free = crate::optimize::capture::free_names(params, body);
499        direct.insert(
500            *f,
501            free.into_iter().filter(|n| root_lets.contains(n)).collect(),
502        );
503        let writes = crate::optimize::capture::free_writes(params, body);
504        direct_writes.insert(
505            *f,
506            writes
507                .into_iter()
508                .filter(|n| root_lets.contains(n))
509                .collect(),
510        );
511        callees.insert(
512            *f,
513            calls
514                .into_iter()
515                .filter(|c| functions.contains_key(c))
516                .collect(),
517        );
518    }
519    let names: Vec<Symbol> = root_lets
520        .iter()
521        .copied()
522        .filter(|g| direct.values().any(|reached| reached.contains(g)))
523        .collect();
524    // What each function reaches, and what it writes, through the functions it calls.
525    let through_calls = |mut sets: HashMap<Symbol, std::collections::HashSet<Symbol>>| loop {
526        let mut grew = false;
527        for (f, cs) in &callees {
528            let via: Vec<Symbol> = cs.iter().flat_map(|c| sets[c].iter().copied()).collect();
529            let mine = sets.get_mut(f).expect("every function has a set");
530            for g in via {
531                grew |= mine.insert(g);
532            }
533        }
534        if !grew {
535            return sets;
536        }
537    };
538    let reach = through_calls(direct);
539    let writes = through_calls(direct_writes);
540    StaticReach {
541        names,
542        reach,
543        writes,
544        root,
545        functions,
546    }
547}
548
549/// The program's bindings a function reaches ([`static_reach`]), and what the C tier refuses about them: since the
550/// static would answer where the interpreter fails, a call from Main's root that reaches a binding before its `Let`
551/// has run, and a task launched on a function that reaches one (a task sees none of the program's bindings); and an
552/// expression whose operands the C tier cannot put in order ([`unsequenced_static_reads`]).
553fn program_statics(stmts: &[Stmt], interner: &Interner) -> ProgramStatics {
554    let StaticReach {
555        names,
556        reach,
557        writes,
558        root,
559        functions,
560    } = static_reach(stmts);
561    if names.is_empty() {
562        return ProgramStatics {
563            names,
564            refusals: Vec::new(),
565        };
566    }
567    let first_reached = |f: &Symbol| -> Option<Symbol> {
568        names
569            .iter()
570            .copied()
571            .find(|g| reach.get(f).is_some_and(|r| r.contains(g)))
572    };
573    let mut refusals = Vec::new();
574    for_each_node(stmts, |node| {
575        if let Visited::Stmt(
576            Stmt::LaunchTask { function, .. } | Stmt::LaunchTaskWithHandle { function, .. },
577        ) = node
578        {
579            if let Some(g) = first_reached(function) {
580                refusals.push(format!(
581                    "a task launched on `{}`, which reaches the program's `{}` (a task sees none of the program's bindings)",
582                    interner.resolve(*function),
583                    interner.resolve(g)
584                ));
585            }
586        }
587    });
588    let mut bound: std::collections::HashSet<Symbol> = std::collections::HashSet::new();
589    for s in &root {
590        let (_, calls) = names_and_calls(std::slice::from_ref(*s));
591        for c in calls.iter().filter(|c| functions.contains_key(c)) {
592            if let Some(g) = names
593                .iter()
594                .copied()
595                .find(|g| reach[c].contains(g) && !bound.contains(g))
596            {
597                refusals.push(format!(
598                    "a call to `{}` that reaches the program's `{}` before its Let runs — declare it before the first call",
599                    interner.resolve(*c),
600                    interner.resolve(g)
601                ));
602            }
603        }
604        if let Stmt::Let { var, .. } = s {
605            bound.insert(*var);
606        }
607    }
608    refusals.extend(unsequenced_static_reads(
609        stmts, &names, &reach, &writes, interner,
610    ));
611    ProgramStatics { names, refusals }
612}
613
614/// C leaves unspecified the order it evaluates an operator's operands and a call's arguments in; LOGOS
615/// evaluates them left to right. Once a function can set a program static, the order shows: in
616/// `counter + next()`, where `next` sets `counter`, the interpreter reads 0 and C may read 1. Such an
617/// expression — one operand writing a static a sibling operand reads (directly, or through a call) — is
618/// refused by name, never compiled in an order the program did not state.
619fn unsequenced_static_reads(
620    stmts: &[Stmt],
621    statics: &[Symbol],
622    reach: &HashMap<Symbol, std::collections::HashSet<Symbol>>,
623    writes: &HashMap<Symbol, std::collections::HashSet<Symbol>>,
624    interner: &Interner,
625) -> Vec<String> {
626    use logicaffeine_language::ast_depth::{expr_children, stmt_expr_children};
627    type Set = std::collections::HashSet<Symbol>;
628    // The statics an expression reads and writes, calls included; a closure's body runs later.
629    fn effects(
630        e: &Expr,
631        statics: &[Symbol],
632        reach: &HashMap<Symbol, Set>,
633        writes: &HashMap<Symbol, Set>,
634    ) -> (Set, Set) {
635        let (mut r, mut w) = (Set::new(), Set::new());
636        match e {
637            Expr::Identifier(s) if statics.contains(s) => {
638                r.insert(*s);
639            }
640            Expr::Call { function, .. } => {
641                r.extend(reach.get(function).into_iter().flatten().copied());
642                w.extend(writes.get(function).into_iter().flatten().copied());
643            }
644            _ => {}
645        }
646        for child in expr_children(e) {
647            let (cr, cw) = effects(child, statics, reach, writes);
648            r.extend(cr);
649            w.extend(cw);
650        }
651        (r, w)
652    }
653    let conflict = |children: &[&Expr]| -> Option<Symbol> {
654        let fx: Vec<(Set, Set)> = children
655            .iter()
656            .map(|c| effects(c, statics, reach, writes))
657            .collect();
658        for (i, (_, wi)) in fx.iter().enumerate() {
659            for (j, (rj, _)) in fx.iter().enumerate() {
660                if i != j {
661                    if let Some(s) = statics.iter().find(|s| wi.contains(s) && rj.contains(s)) {
662                        return Some(*s);
663                    }
664                }
665            }
666        }
667        None
668    };
669    let mut refusals = Vec::new();
670    for_each_node(stmts, |node| {
671        let children = match node {
672            Visited::Expr(e) => expr_children(e),
673            Visited::Stmt(s) => stmt_expr_children(s),
674        };
675        if children.len() > 1 {
676            if let Some(s) = conflict(&children) {
677                refusals.push(format!(
678                    "an expression that reads the program's `{}` beside a call that sets it, in an order C does not fix — bind the call's result first",
679                    interner.resolve(s)
680                ));
681            }
682        }
683    });
684    refusals.sort();
685    refusals.dedup();
686    refusals
687}
688
689/// `## Main` lowered: under the stepped tier, its frame and step beside the C `main` that boots the
690/// scheduler on it; otherwise the C `main` alone.
691struct MainCode {
692    frame: String,
693    step: String,
694    entry: String,
695}
696
697/// Lower `## Main`: as the first task under the scheduler when the program is concurrent — a step
698/// function under the stepped tier, a coroutine otherwise — else as `main`.
699fn emit_main(
700    stmts: &[Stmt],
701    ctx: &mut CContext,
702    uses_concurrency: bool,
703    tier: TaskTier,
704) -> MainCode {
705    ctx.nonnegative_vars = crate::codegen::expr::collect_always_nonneg(stmts);
706
707    let mut changed = values::mutated_roots(stmts, &ctx.fn_inout);
708    changed.extend(ctx.changed_statics.iter().copied());
709    ctx.mutated = changed;
710    if uses_concurrency && tier == TaskTier::Stepped {
711        ctx.bigint_vars = ctx.exact.main_locals.clone();
712        ctx.number_locals = numbers::number_locals(stmts, ctx);
713        let body: Vec<Stmt> = stmts
714            .iter()
715            .filter(|s| !matches!(s, Stmt::FunctionDef { .. }))
716            .cloned()
717            .collect();
718        ctx.main_root_depth = Some(ctx.decl_scopes.len() + 1);
719        let (frame, step) = ctx.in_body(true, |ctx| {
720            stepped::emit_step(MAIN_STEP, &[], CType::Void, &body, ctx)
721        });
722        ctx.main_root_depth = None;
723        let mut entry = String::new();
724        writeln!(entry, "int main(int argc, char **argv) {{").unwrap();
725        writeln!(entry, "    _logos_argc = argc;").unwrap();
726        writeln!(entry, "    _logos_argv = argv;").unwrap();
727        writeln!(entry, "    LOGOS_STEP_HOOK();").unwrap();
728        writeln!(
729            entry,
730            "    logos_sched_bootstrap(logos_step_{MAIN_STEP}, sizeof(logos_frame_{MAIN_STEP}), LOGOS_RUN_SEED);"
731        )
732        .unwrap();
733        writeln!(entry, "    return 0;").unwrap();
734        writeln!(entry, "}}").unwrap();
735        return MainCode { frame, step, entry };
736    }
737    let mut out = String::new();
738    // Main's own locals get the same exact-integer pre-pass a function body receives (settled with the
739    // program's slots, see `exact`), so a mutable accumulator declared in Main that overflows i64 — or is
740    // reassigned an exact `**`/`pow`, or a call's exact result — is declared `LInt` from the start (a `Set`
741    // cannot retype a name mid-block). Float-guarded so a `double` accumulator in Main is never mistaken for
742    // an arbitrary-precision integer.
743    ctx.bigint_vars = ctx.exact.main_locals.clone();
744    ctx.number_locals = numbers::number_locals(stmts, ctx);
745    let branchless_words =
746        direct_c_branchless_word_vars(stmts, &ctx.bigint_vars, &ctx.exact.pure_calls);
747    ctx.bigint_vars
748        .retain(|sym| !branchless_words.contains(sym));
749
750    if uses_concurrency {
751        // Main runs AS THE FIRST TASK: its body becomes `logos_main_body` (a `long long`-returning
752        // trampoline-compatible entry), and `main` boots the scheduler with it, draining to quiescence.
753        // Program args are stashed before the scheduler starts (a `Show args` inside a task still works).
754        writeln!(
755            out,
756            "static long long logos_main_body(const long long *__targs) {{"
757        )
758        .unwrap();
759        writeln!(out, "    (void)__targs;").unwrap();
760        ctx.enter_scope();
761        ctx.main_root_depth = Some(ctx.decl_scopes.len());
762        let ownership = body_ownership(stmts, &std::collections::HashSet::new(), ctx);
763        ctx.in_body(true, |ctx| {
764            ctx.ownership = Some(ownership);
765            for stmt in stmts {
766                match stmt {
767                    Stmt::FunctionDef { .. } => continue,
768                    _ => codegen_stmt(stmt, ctx, &mut out, 1),
769                }
770            }
771        });
772        ctx.main_root_depth = None;
773        ctx.exit_scope();
774        writeln!(out, "    return 0;").unwrap();
775        writeln!(out, "}}").unwrap();
776        writeln!(out, "int main(int argc, char **argv) {{").unwrap();
777        writeln!(out, "    _logos_argc = argc;").unwrap();
778        writeln!(out, "    _logos_argv = argv;").unwrap();
779        writeln!(out, "    logos_sched_bootstrap((void *)logos_main_body);").unwrap();
780        writeln!(out, "    return 0;").unwrap();
781        writeln!(out, "}}").unwrap();
782    } else {
783        writeln!(out, "int main(int argc, char **argv) {{").unwrap();
784        writeln!(out, "    _logos_argc = argc;").unwrap();
785        writeln!(out, "    _logos_argv = argv;").unwrap();
786        ctx.enter_scope();
787        ctx.main_root_depth = Some(ctx.decl_scopes.len());
788        let ownership = body_ownership(stmts, &std::collections::HashSet::new(), ctx);
789        ctx.in_body(true, |ctx| {
790            ctx.ownership = Some(ownership);
791            for stmt in stmts {
792                match stmt {
793                    Stmt::FunctionDef { .. } => continue,
794                    _ => codegen_stmt(stmt, ctx, &mut out, 1),
795                }
796            }
797        });
798        ctx.main_root_depth = None;
799        ctx.exit_scope();
800        writeln!(out, "    return 0;").unwrap();
801        writeln!(out, "}}").unwrap();
802    }
803    MainCode {
804        frame: String::new(),
805        step: String::new(),
806        entry: out,
807    }
808}
809
810/// The C name of `## Main`'s step and frame under the stepped tier — one no LOGOS name spells.
811const MAIN_STEP: &str = "__main";
812
813/// Collect, per spawned task function, its argument count (`Launch a task to fn with a, b` → arity 2).
814/// A function may be spawned at several sites; the LOGOS type system fixes its arity, so the max seen is
815/// its true arity. Drives the task-entry wrappers: each spawned function gets a `long long`-returning
816/// trampoline-compatible entry, so the `ucontext` trampoline can call it uniformly by pointer.
817fn collect_spawned_arities(stmts: &[Stmt], out: &mut HashMap<Symbol, usize>) {
818    for_each_node(stmts, |node| {
819        if let Visited::Stmt(
820            Stmt::LaunchTask { function, args } | Stmt::LaunchTaskWithHandle { function, args, .. },
821        ) = node
822        {
823            let e = out.entry(*function).or_insert(0);
824            *e = (*e).max(args.len());
825        }
826    });
827}
828use types::{
829    c_param_decl, c_type_str_resolved, escape_c_ident, field_type_to_ctype,
830    resolve_type_expr_with_registry, tuple_c_name, CContext, CType,
831};
832
833/// Collect every distinct tuple/record `CType` reachable from a function signature (nested-first, deduped
834/// by mangled name) so its `typedef struct { … }` can be emitted before any use.
835fn collect_tuple_types(
836    cty: &CType,
837    seen: &mut std::collections::HashSet<String>,
838    out: &mut Vec<(String, Vec<CType>)>,
839    interner: &Interner,
840) {
841    // A named record SHARES the positional tuple struct, and a Seq-of-tuple's element IS a tuple — so all
842    // three surface the same underlying element tuple.
843    let elems: Option<Vec<CType>> = match cty {
844        CType::Tuple(elems) | CType::SeqTuple(elems) => Some(elems.clone()),
845        CType::Record(fields) => Some(fields.iter().map(|(_, t)| t.clone()).collect()),
846        _ => None,
847    };
848    if let Some(elems) = elems {
849        for e in &elems {
850            collect_tuple_types(e, seen, out, interner);
851        }
852        let name = tuple_c_name(&elems, interner);
853        if seen.insert(name.clone()) {
854            out.push((name, elems));
855        }
856    }
857}
858
859/// Collect every distinct NESTED-sequence `CType::SeqSeq` reachable from a signature (deepest-first,
860/// deduped) so its outer `Seq_<inner>` wrapper typedef can be emitted before use.
861fn collect_seqseq_types(
862    cty: &CType,
863    seen: &mut std::collections::HashSet<String>,
864    out: &mut Vec<CType>,
865    interner: &Interner,
866) {
867    if let CType::SeqSeq(inner) = cty {
868        collect_seqseq_types(inner, seen, out, interner);
869        let name = c_type_str_resolved(cty, interner);
870        if seen.insert(name) {
871            out.push(cty.clone());
872        }
873    }
874}
875
876/// Collect nested-sequence (`CType::SeqSeq`) types reachable from STATEMENT expressions — `Let` values,
877/// `Set` values, `Show` objects, and `Return`s — not just function signatures, so a bare `Show [[1,2]]`
878/// or `Let g be [[1,2]]` gets its `Seq_Seq_…` family emitted. A forward pass registers `Let`/param types
879/// via `infer_expr_type` so a nested-seq bound to a variable and shown later still resolves.
880fn collect_stmt_seqseq_types<'a>(
881    body: &'a [Stmt<'a>],
882    ctx: &mut CContext<'a>,
883    seen: &mut std::collections::HashSet<String>,
884    out: &mut Vec<CType>,
885    interner: &Interner,
886) {
887    for s in body {
888        match s {
889            Stmt::Let { var, value, .. } => {
890                let ty = absent::binding(s, crate::codegen_c::types::infer_expr_type(value, ctx), ctx);
891                collect_seqseq_types(&ty, seen, out, interner);
892                ctx.vars.insert(*var, ty);
893            }
894            Stmt::Set { value, .. } => {
895                let ty = crate::codegen_c::types::infer_expr_type(value, ctx);
896                collect_seqseq_types(&ty, seen, out, interner);
897            }
898            Stmt::Show { object, .. } => {
899                let ty = crate::codegen_c::types::infer_expr_type(object, ctx);
900                collect_seqseq_types(&ty, seen, out, interner);
901            }
902            Stmt::Return { value: Some(v) } => {
903                let ty = crate::codegen_c::types::infer_expr_type(v, ctx);
904                collect_seqseq_types(&ty, seen, out, interner);
905            }
906            Stmt::If {
907                then_block,
908                else_block,
909                ..
910            } => {
911                collect_stmt_seqseq_types(then_block, ctx, seen, out, interner);
912                if let Some(eb) = else_block {
913                    collect_stmt_seqseq_types(eb, ctx, seen, out, interner);
914                }
915            }
916            Stmt::While { body, .. } | Stmt::Repeat { body, .. } => {
917                collect_stmt_seqseq_types(body, ctx, seen, out, interner);
918            }
919            Stmt::FunctionDef {
920                name, body, params, ..
921            } => {
922                let saved = ctx.vars.clone();
923                let saved_scope = std::mem::replace(&mut ctx.tower_scope, Some(*name));
924                for (pn, pt) in params.iter() {
925                    ctx.vars.insert(*pn, collected_param_ctype(ctx, *name, *pn, pt));
926                }
927                collect_stmt_seqseq_types(body, ctx, seen, out, interner);
928                ctx.vars = saved;
929                ctx.tower_scope = saved_scope;
930            }
931            _ => {}
932        }
933    }
934}
935/// The C type a statement collector gives parameter `param` of `function`: a value of the exact extension where the
936/// extension reaches it, else its declared type.
937fn collected_param_ctype(ctx: &CContext, function: Symbol, param: Symbol, declared: &TypeExpr) -> CType {
938    if tower::param(ctx, function, param) {
939        return CType::Tower;
940    }
941    let declared = resolve_type_expr_with_registry(declared, ctx.interner, Some(ctx.registry));
942    absent::parameter(function, param, declared, ctx)
943}
944
945/// Collect tuple/record (`CType::Tuple`/`Record`/`SeqTuple`) types reached from STATEMENT expressions —
946/// `Let`/`Set` values, `Show` objects, `Return`s — not just signatures, so a bare `Show (1, 2)` /
947/// `Let t be (1, 2)` gets its `LTuple_…` family. Mirrors [`collect_stmt_seqseq_types`].
948fn collect_stmt_tuple_types<'a>(
949    body: &'a [Stmt<'a>],
950    ctx: &mut CContext<'a>,
951    seen: &mut std::collections::HashSet<String>,
952    out: &mut Vec<(String, Vec<CType>)>,
953    interner: &Interner,
954) {
955    for s in body {
956        match s {
957            Stmt::Let { var, value, .. } => {
958                let ty = absent::binding(s, crate::codegen_c::types::infer_expr_type(value, ctx), ctx);
959                collect_tuple_types(&ty, seen, out, interner);
960                ctx.vars.insert(*var, ty);
961            }
962            Stmt::Set { value, .. } => {
963                collect_tuple_types(
964                    &crate::codegen_c::types::infer_expr_type(value, ctx),
965                    seen,
966                    out,
967                    interner,
968                );
969            }
970            Stmt::Show { object, .. } => {
971                collect_tuple_types(
972                    &crate::codegen_c::types::infer_expr_type(object, ctx),
973                    seen,
974                    out,
975                    interner,
976                );
977            }
978            Stmt::Return { value: Some(v) } => {
979                collect_tuple_types(
980                    &crate::codegen_c::types::infer_expr_type(v, ctx),
981                    seen,
982                    out,
983                    interner,
984                );
985            }
986            Stmt::If {
987                then_block,
988                else_block,
989                ..
990            } => {
991                collect_stmt_tuple_types(then_block, ctx, seen, out, interner);
992                if let Some(eb) = else_block {
993                    collect_stmt_tuple_types(eb, ctx, seen, out, interner);
994                }
995            }
996            // One name over a map binds each entry, `(key, value)`.
997            Stmt::Repeat {
998                pattern: crate::ast::stmt::Pattern::Identifier(var),
999                iterable,
1000                body,
1001            } => {
1002                let over = crate::codegen_c::types::infer_expr_type(iterable, ctx);
1003                if let Some((key, value)) = crate::codegen_c::types::map_entry_types(&over) {
1004                    let entry = CType::Tuple(vec![key, value]);
1005                    collect_tuple_types(&entry, seen, out, interner);
1006                    ctx.vars.insert(*var, entry);
1007                }
1008                collect_stmt_tuple_types(body, ctx, seen, out, interner);
1009            }
1010            Stmt::While { body, .. } | Stmt::Repeat { body, .. } => {
1011                collect_stmt_tuple_types(body, ctx, seen, out, interner);
1012            }
1013            Stmt::FunctionDef {
1014                name, body, params, ..
1015            } => {
1016                let saved = ctx.vars.clone();
1017                let saved_scope = std::mem::replace(&mut ctx.tower_scope, Some(*name));
1018                for (pn, pt) in params.iter() {
1019                    ctx.vars.insert(*pn, collected_param_ctype(ctx, *name, *pn, pt));
1020                }
1021                collect_stmt_tuple_types(body, ctx, seen, out, interner);
1022                ctx.vars = saved;
1023                ctx.tower_scope = saved_scope;
1024            }
1025            _ => {}
1026        }
1027    }
1028}
1029
1030/// Record a map whose VALUE no fixed family holds — a Seq (`Map of Text to Seq of Int` → `Map_str_Seq_i64`), a value
1031/// of the exact extension (`Map of Int to Hyperreal` → `Map_i64_LTower`) — so its generic family can be synthesized.
1032/// Value-TYPE maps (`Map of Text to Money`) keep their own fixed family, so those are skipped here (avoids a duplicate
1033/// typedef).
1034fn collect_mapvalue_from_ctype(
1035    cty: &CType,
1036    seen: &mut std::collections::HashSet<String>,
1037    out: &mut Vec<CType>,
1038    interner: &Interner,
1039) {
1040    if let CType::MapStrValue(v) | CType::MapI64Value(v) = cty {
1041        if !crate::codegen_c::types::is_c_value_type(v) {
1042            let name = c_type_str_resolved(cty, interner);
1043            if seen.insert(name) {
1044                out.push(cty.clone());
1045            }
1046        }
1047    }
1048}
1049
1050/// Collect seq-valued string-map types reached from STATEMENT expressions (a bare
1051/// `Let m be a new Map of Text to Seq of Int`), not just signatures. Mirrors [`collect_stmt_seqseq_types`].
1052fn collect_stmt_mapvalue_types<'a>(
1053    body: &'a [Stmt<'a>],
1054    ctx: &mut CContext<'a>,
1055    seen: &mut std::collections::HashSet<String>,
1056    out: &mut Vec<CType>,
1057    interner: &Interner,
1058) {
1059    for s in body {
1060        match s {
1061            Stmt::Let { var, value, .. } => {
1062                let ty = crate::codegen_c::types::infer_expr_type(value, ctx);
1063                collect_mapvalue_from_ctype(&ty, seen, out, interner);
1064                ctx.vars.insert(*var, ty);
1065            }
1066            Stmt::Set { value, .. } => {
1067                let ty = crate::codegen_c::types::infer_expr_type(value, ctx);
1068                collect_mapvalue_from_ctype(&ty, seen, out, interner);
1069            }
1070            Stmt::Show { object, .. } => {
1071                let ty = crate::codegen_c::types::infer_expr_type(object, ctx);
1072                collect_mapvalue_from_ctype(&ty, seen, out, interner);
1073            }
1074            Stmt::Return { value: Some(v) } => {
1075                let ty = crate::codegen_c::types::infer_expr_type(v, ctx);
1076                collect_mapvalue_from_ctype(&ty, seen, out, interner);
1077            }
1078            Stmt::If {
1079                then_block,
1080                else_block,
1081                ..
1082            } => {
1083                collect_stmt_mapvalue_types(then_block, ctx, seen, out, interner);
1084                if let Some(eb) = else_block {
1085                    collect_stmt_mapvalue_types(eb, ctx, seen, out, interner);
1086                }
1087            }
1088            Stmt::While { body, .. } | Stmt::Repeat { body, .. } => {
1089                collect_stmt_mapvalue_types(body, ctx, seen, out, interner);
1090            }
1091            Stmt::FunctionDef {
1092                name, body, params, ..
1093            } => {
1094                let saved = ctx.vars.clone();
1095                let saved_scope = std::mem::replace(&mut ctx.tower_scope, Some(*name));
1096                for (pn, pt) in params.iter() {
1097                    ctx.vars.insert(*pn, collected_param_ctype(ctx, *name, *pn, pt));
1098                    collect_mapvalue_from_ctype(
1099                        &resolve_type_expr_with_registry(pt, interner, Some(ctx.registry)),
1100                        seen,
1101                        out,
1102                        interner,
1103                    );
1104                }
1105                collect_stmt_mapvalue_types(body, ctx, seen, out, interner);
1106                ctx.vars = saved;
1107                ctx.tower_scope = saved_scope;
1108            }
1109            _ => {}
1110        }
1111    }
1112}
1113
1114/// Emit the insertion-ordered generic map family of the map C type `map` — `Map_str_<V>` for a `MapStrValue`,
1115/// `Map_i64_<V>` for a `MapI64Value` — for an arbitrary showable VALUE `CType` (Seq values and the exact extension's;
1116/// value types use their own fixed family). Mirrors the fixed families, but renders the value via
1117/// [`c_field_to_string_expr`] so any showable value works, and a read of a key the map does not hold fails as theirs
1118/// do. The value's own C type must already be defined (it is — scalar seqs live in `C_RUNTIME`, value/struct/nested
1119/// seqs are emitted earlier, `LTower` with the extension's runtime). `rendered` false emits no renderer: a map of
1120/// values-or-nothing is one family whatever they hold, and what renders them is the payload's (`c_field_to_string_expr`).
1121fn emit_generic_map_family(output: &mut String, map: &CType, interner: &Interner, rendered: bool) {
1122    use std::fmt::Write;
1123    let (v, k, key_t, key_param, hash, store_key, key_fmt) = match map {
1124        CType::MapStrValue(v) => (v, "str", "char *", "const char *key", "_map_hash_str", "lc_gc_strdup(key)", "%s"),
1125        CType::MapI64Value(v) => (v, "i64", "int64_t ", "int64_t key", "_map_hash", "key", "%\" PRId64 \""),
1126        _ => return,
1127    };
1128    let eq = |slot: &str| match k {
1129        "str" => format!("strcmp({slot}, key) == 0"),
1130        _ => format!("{slot} == key"),
1131    };
1132    let eq_idx = eq("m->keys[idx]");
1133    let ne_i = match k {
1134        "str" => "strcmp(t->keys[i], key) != 0".to_string(),
1135        _ => "t->keys[i] != key".to_string(),
1136    };
1137    let vname = c_type_str_resolved(v, interner); // e.g. "Seq_i64"
1138    let mp = format!("Map_{k}_{vname}");
1139    let f = format!("map_{k}_{vname}");
1140    let vrender = crate::codegen_c::types::c_field_to_string_expr(v, "m->vals[si]", interner);
1141    writeln!(output, "typedef struct {{ {key_t}*keys; {vname} *vals; uint8_t *state; size_t cap; size_t len; size_t *order; size_t ord_len; }} {mp};").unwrap();
1142    writeln!(output, "__attribute__((unused)) static {mp} {f}_new(void) {{ size_t cap = 16; {mp} m = {{({key_t}*)lc_gc_calloc(cap, sizeof({key_t})), ({vname} *)lc_gc_calloc(cap, sizeof({vname})), (uint8_t *)lc_gc_calloc(cap, 1), cap, 0, (size_t *)lc_gc_calloc(cap, sizeof(size_t)), 0}}; return m; }}").unwrap();
1143    writeln!(output, "__attribute__((unused)) static void _{f}_resize({mp} *m) {{ {key_t}*ok = m->keys; {vname} *ov = m->vals; uint8_t *os = m->state; size_t *oo = m->order; size_t ool = m->ord_len; size_t nc = m->cap * 2; m->keys = ({key_t}*)lc_gc_calloc(nc, sizeof({key_t})); m->vals = ({vname} *)lc_gc_calloc(nc, sizeof({vname})); m->state = (uint8_t *)lc_gc_calloc(nc, 1); m->order = (size_t *)lc_gc_calloc(nc, sizeof(size_t)); m->cap = nc; m->len = 0; m->ord_len = 0; for (size_t oi = 0; oi < ool; oi++) {{ size_t si = oo[oi]; if (!os[si]) continue; size_t idx = {hash}(ok[si], nc); while (m->state[idx]) idx = (idx + 1) & (nc - 1); m->keys[idx] = ok[si]; m->vals[idx] = ov[si]; m->state[idx] = 1; m->len++; m->order[m->ord_len++] = idx; }} lc_gc_free(ok); lc_gc_free(ov); lc_gc_free(os); lc_gc_free(oo); }}").unwrap();
1144    writeln!(output, "__attribute__((unused)) static void {f}_set({mp} *m, {key_param}, {vname} val) {{ if (m->ord_len * 4 >= m->cap * 3) _{f}_resize(m); size_t idx = {hash}(key, m->cap); while (m->state[idx]) {{ if ({eq_idx}) {{ m->vals[idx] = val; return; }} idx = (idx + 1) & (m->cap - 1); }} m->keys[idx] = {store_key}; m->vals[idx] = val; m->state[idx] = 1; m->len++; m->order[m->ord_len++] = idx; }}").unwrap();
1145    writeln!(output, "__attribute__((unused)) static {vname} {f}_get({mp} *m, {key_param}) {{ size_t idx = {hash}(key, m->cap); while (m->state[idx]) {{ if ({eq_idx}) return m->vals[idx]; idx = (idx + 1) & (m->cap - 1); }} logos_map_miss(); {vname} z; memset(&z, 0, sizeof({vname})); return z; }}").unwrap();
1146    writeln!(output, "__attribute__((unused)) static bool {f}_contains({mp} *m, {key_param}) {{ size_t idx = {hash}(key, m->cap); while (m->state[idx]) {{ if ({eq_idx}) return true; idx = (idx + 1) & (m->cap - 1); }} return false; }}").unwrap();
1147    writeln!(output, "__attribute__((unused)) static void {f}_remove({mp} *t, {key_param}) {{ size_t mask = t->cap - 1, i = {hash}(key, t->cap); while (t->state[i] && {ne_i}) i = (i + 1) & mask; if (!t->state[i]) return; _logos_order_drop(t->order, &t->ord_len, i); t->len--; for (size_t j = (i + 1) & mask; t->state[j]; j = (j + 1) & mask) {{ if (_logos_slot_backs({hash}(t->keys[j], t->cap), i, j, mask)) {{ t->keys[i] = t->keys[j]; t->vals[i] = t->vals[j]; _logos_order_move(t->order, t->ord_len, j, i); i = j; }} }} t->state[i] = 0; }}").unwrap();
1148    writeln!(output, "__attribute__((unused)) static int64_t {f}_len({mp} *m) {{ return (int64_t)m->len; }}").unwrap();
1149    if !rendered {
1150        return;
1151    }
1152    writeln!(output, "__attribute__((unused)) static char *{f}_to_string({mp} *m) {{ char *out = lc_gc_strdup(\"{{\"); int first = 1; for (size_t oi = 0; oi < m->ord_len; oi++) {{ size_t si = m->order[oi]; if (!m->state[si]) continue; char *__v = {vrender}; char *e = logos_dyn_sprintf(\"%s{key_fmt}: %s\", first ? \"\" : \", \", m->keys[si], __v); lc_gc_free(__v); char *nw = str_concat(out, e); lc_gc_free(out); lc_gc_free(e); out = nw; first = 0; }} char *nw = str_concat(out, \"}}\"); lc_gc_free(out); return nw; }}").unwrap();
1153    writeln!(output, "__attribute__((unused)) static void show_{f}({mp} *m) {{ char *t = {f}_to_string(m); printf(\"%s\\n\", t); lc_gc_free(t); }}").unwrap();
1154}
1155use emit::codegen_stmt;
1156
1157/// Promote an integer `CType` to the EXACT arbitrary-precision `LInt` (`CType::BigInt`) in place, recursing into
1158/// a function-pointer's return + params. Non-integer types are untouched.
1159fn exactify_int_ctype(t: &mut CType) {
1160    match t {
1161        CType::Int64 => *t = CType::BigInt,
1162        CType::FnPtr { ret, params } => {
1163            exactify_int_ctype(ret.as_mut());
1164            for p in params.iter_mut() {
1165                exactify_int_ctype(p);
1166            }
1167        }
1168        _ => {}
1169    }
1170}
1171
1172/// The SHAPE half of an EXACT higher-order function: takes a `fn`-typed (closure) param AND no sequence param
1173/// (a SCALAR HOF like `apply(f, x)`). Its integers become exact `LInt` so a closure that overflows promotes
1174/// instead of wrapping — SELECTIVELY, excluding seq-HOFs (exactifying them breaks passing an i64 seq element to
1175/// an `LInt` closure). The CALL-SITE half (inline closures at every site, sites not provably in range) is the
1176/// shared `codegen::bigint_promote::exact_hof_fns`; both must hold.
1177fn is_exact_hof(param_ctypes: &[CType]) -> bool {
1178    // A higher-order function OVER a seq (`map`/`fold`/`reduceSeq`) is never exactified: its closure receives
1179    // raw (i64/typed) seq elements.
1180    param_ctypes
1181        .iter()
1182        .any(|t| matches!(t, CType::FnPtr { .. }))
1183        && !param_ctypes.iter().any(types::is_seq_ctype)
1184}
1185
1186/// The C type of `param` of `function`: its declared type, every integer of an exact HOF's exactified, and
1187/// `LInt` where the exact-slot analysis found an exact value passed in its position.
1188fn param_ctype(ctx: &CContext, function: Symbol, param: Symbol, declared: &TypeExpr) -> CType {
1189    if tower::param(ctx, function, param) {
1190        return CType::Tower;
1191    }
1192    let mut t = resolve_type_expr_with_registry(declared, ctx.interner, Some(ctx.registry));
1193    if ctx.exact_hofs.contains(&function) {
1194        exactify_int_ctype(&mut t);
1195    } else if t == CType::Int64 && ctx.exact.param_is_exact(function, param) {
1196        t = CType::BigInt;
1197    }
1198    absent::parameter(function, param, t, ctx)
1199}
1200
1201/// The `LInt` locals of `function`'s body: the exact-slot analysis's, for a function it read (every
1202/// top-level one); otherwise the body's own pre-pass under the program's slots.
1203fn body_exact_locals(
1204    ctx: &CContext,
1205    function: Symbol,
1206    body: &[Stmt],
1207    param_types: &[(Symbol, CType)],
1208) -> std::collections::HashSet<Symbol> {
1209    if let Some(locals) = ctx.exact.locals.get(&function) {
1210        return locals.clone();
1211    }
1212    let mut no_int = types::collect_float_vars(body, param_types, ctx.interner, ctx.registry);
1213    no_int.extend(crate::analysis::exactness::word_vars(
1214        body,
1215        &[],
1216        &ctx.exact.word_results,
1217        ctx.registry,
1218        ctx.interner,
1219    ));
1220    let seeds = param_types
1221        .iter()
1222        .filter(|(_, t)| *t == CType::BigInt)
1223        .map(|(p, _)| *p)
1224        .collect();
1225    types::collect_bigint_vars(
1226        body,
1227        &no_int,
1228        ctx.interner,
1229        &ctx.exact,
1230        ctx.int_oracle.as_deref(),
1231        &seeds,
1232    )
1233}
1234
1235/// The sharing and liveness of `body` (see `sharing`), under the program's changed statics and its functions'
1236/// changed parameters, a program static being read at any time; and the ranges of its integer names (see
1237/// `word_ranges`).
1238/// Fresh local buffers the direct-C function owns alone and can destroy before it leaves.
1239fn owned_drop_plan(
1240    body: &[Stmt],
1241    params: &std::collections::HashSet<Symbol>,
1242    sharing: &sharing::Sharing,
1243    ctx: &CContext,
1244) -> std::collections::HashSet<Symbol> {
1245    use std::collections::{HashMap, HashSet};
1246
1247    fn expr_reads(expr: &Expr, out: &mut HashSet<Symbol>) {
1248        if let Expr::Identifier(sym) = expr {
1249            out.insert(*sym);
1250        }
1251        for child in expr_children(expr) {
1252            expr_reads(child, out);
1253        }
1254    }
1255
1256    let mut bindings: HashMap<Symbol, (usize, bool)> = HashMap::new();
1257    let mut return_reads = HashSet::new();
1258    let mut has_nested_scope = false;
1259    walk_nodes(body, |node| match node {
1260        Visited::Stmt(Stmt::FunctionDef { .. }) | Visited::Expr(Expr::Closure { .. }) => {
1261            // A returned closure may capture a local buffer even when the
1262            // sharing graph does not represent that environment edge. Keep
1263            // the lifetime optimization conservative for closure-bearing
1264            // functions until capture ownership is explicit in this backend.
1265            has_nested_scope = true;
1266            Walk::Past
1267        }
1268        Visited::Stmt(Stmt::Let { var, value, .. }) => {
1269            let entry = bindings.entry(*var).or_insert((0, true));
1270            entry.0 += 1;
1271            entry.1 &= values::is_fresh(value);
1272            Walk::Into
1273        }
1274        Visited::Stmt(Stmt::Return { value: Some(value) }) => {
1275            // Cleanup precedes C's return expression, so exclude every value needed to evaluate it,
1276            // not merely buffers the returned result may alias.
1277            expr_reads(value, &mut return_reads);
1278            Walk::Into
1279        }
1280        _ => Walk::Into,
1281    });
1282
1283    if has_nested_scope {
1284        return HashSet::new();
1285    }
1286
1287    let mut escaping = params.clone();
1288    escaping.extend(ctx.program_statics.iter().copied());
1289    escaping.extend(return_reads);
1290    let escaping = sharing.closure(&escaping);
1291
1292    bindings
1293        .into_iter()
1294        .filter_map(|(sym, (count, fresh))| {
1295            (count == 1 && fresh && !escaping.contains(&sym) && sharing.class_of(sym) == vec![sym])
1296                .then_some(sym)
1297        })
1298        .collect()
1299}
1300
1301fn body_ownership(
1302    body: &[Stmt],
1303    params: &std::collections::HashSet<Symbol>,
1304    ctx: &CContext,
1305) -> std::rc::Rc<types::Ownership> {
1306    let sharing = sharing::Sharing::of(
1307        body,
1308        &ctx.changed_statics,
1309        &ctx.mutating,
1310        &ctx.call_shapes,
1311        &ctx.fn_inout,
1312    );
1313    let owned_drops = owned_drop_plan(body, params, &sharing, ctx);
1314    std::rc::Rc::new(types::Ownership {
1315        sharing,
1316        live: sharing::Liveness::of(body, &ctx.program_statics),
1317        words: word_ranges::WordRanges::of(body, &ctx.program_statics),
1318        owned_drops,
1319        bounded_count_accumulators:
1320            crate::codegen::stmt::collect_bounded_count_accumulators_with_purity(
1321                body,
1322                &ctx.bigint_vars,
1323                &ctx.exact.pure_calls,
1324            ),
1325    })
1326}
1327
1328/// Exact integer locals for which direct C can use its native word representation while
1329/// emitting `BranchlessAccumulate`. The shared bounded-counter proof establishes that the value
1330/// starts at zero, is changed only by `+1`, and cannot exceed an `i64` loop bound.
1331///
1332/// Keep the syntactic predicate-guard check here in lockstep with `emit::codegen_stmt`: merely
1333/// proving that an accumulator is bounded must not silently change its representation under an
1334/// optimization that never fires. When the pass is disabled this returns no variables, restoring
1335/// the ordinary exact `LInt` path.
1336fn direct_c_branchless_word_vars(
1337    body: &[Stmt],
1338    bigint_vars: &std::collections::HashSet<Symbol>,
1339    pure_calls: &std::collections::HashSet<Symbol>,
1340) -> std::collections::HashSet<Symbol> {
1341    use crate::optimization::Opt;
1342    use std::collections::HashSet;
1343
1344    if !crate::optimize::active_config().is_on(Opt::BranchlessAccumulate) {
1345        return HashSet::new();
1346    }
1347
1348    let bounded = crate::codegen::stmt::collect_bounded_count_accumulators_with_purity(
1349        body,
1350        bigint_vars,
1351        pure_calls,
1352    );
1353    if bounded.is_empty() {
1354        return HashSet::new();
1355    }
1356
1357    let mut guarded = HashSet::new();
1358    walk_nodes(body, |node| match node {
1359        // A nested definition receives its own exactness and lowering context.
1360        Visited::Stmt(Stmt::FunctionDef { .. }) => Walk::Past,
1361        Visited::Stmt(Stmt::If {
1362            then_block,
1363            else_block: None,
1364            ..
1365        }) if then_block.len() == 1 => {
1366            if let Stmt::Set {
1367                target,
1368                value:
1369                    Expr::BinaryOp {
1370                        op: BinaryOpKind::Add,
1371                        left,
1372                        right,
1373                    },
1374            } = &then_block[0]
1375            {
1376                let unit_self_add = matches!(left, Expr::Identifier(sym) if *sym == *target)
1377                    && matches!(right, Expr::Literal(Literal::Number(1)));
1378                if unit_self_add && bounded.contains(target) {
1379                    guarded.insert(*target);
1380                }
1381            }
1382            Walk::Into
1383        }
1384        _ => Walk::Into,
1385    });
1386    guarded
1387}
1388
1389/// Read-only text_bytes bindings that can borrow their source text as a byte
1390/// view. This consumes the same conservative proof as Rust's TextBytesView:
1391/// the byte binding is used only by length/index/iteration reads, and its
1392/// source text is not used after the binding.
1393fn c_text_bytes_view_plan(
1394    stmts: &[Stmt],
1395    interner: &crate::intern::Interner,
1396) -> HashMap<usize, Symbol> {
1397    fn visit(block: &[Stmt], interner: &crate::intern::Interner, out: &mut HashMap<usize, Symbol>) {
1398        for (idx, stmt) in block.iter().enumerate() {
1399            if let Stmt::Let {
1400                var,
1401                value: Expr::Call { function, args },
1402                mutable: false,
1403                ..
1404            } = stmt
1405            {
1406                if interner.resolve(*function) == "text_bytes"
1407                    && args.len() == 1
1408                    && matches!(args[0], Expr::Identifier(source) if *source != *var)
1409                {
1410                    let Expr::Identifier(source) = args[0] else {
1411                        unreachable!()
1412                    };
1413                    let remaining = &block[idx + 1..];
1414                    let remaining_refs: Vec<&Stmt> = remaining.iter().collect();
1415                    if crate::codegen::peephole::text_bytes_view_safe(remaining, *var)
1416                        && !crate::codegen::detection::symbol_appears_in_stmts(
1417                            *source,
1418                            &remaining_refs,
1419                        )
1420                    {
1421                        out.insert(stmt as *const Stmt as usize, *source);
1422                    }
1423                }
1424            }
1425
1426            match stmt {
1427                Stmt::While { body, .. }
1428                | Stmt::Repeat { body, .. }
1429                | Stmt::FunctionDef { body, .. }
1430                | Stmt::Zone { body, .. }
1431                | Stmt::Splice { body }
1432                | Stmt::Reversibly { body }
1433                | Stmt::During { body, .. }
1434                | Stmt::Concurrent { tasks: body }
1435                | Stmt::Parallel { tasks: body } => visit(body, interner, out),
1436                Stmt::If {
1437                    then_block,
1438                    else_block,
1439                    ..
1440                } => {
1441                    visit(then_block, interner, out);
1442                    if let Some(otherwise) = else_block {
1443                        visit(otherwise, interner, out);
1444                    }
1445                }
1446                Stmt::Inspect { arms, .. } => {
1447                    for arm in arms {
1448                        visit(arm.body, interner, out);
1449                    }
1450                }
1451                _ => {}
1452            }
1453        }
1454    }
1455
1456    if !crate::optimize::active_config().is_on(crate::optimization::Opt::TextBytesView) {
1457        return HashMap::new();
1458    }
1459    let mut out = HashMap::new();
1460    visit(stmts, interner, &mut out);
1461    out
1462}
1463
1464/// Sequence parameters that the C sharing analysis proves read-only. Passing
1465/// a small stack-backed sequence descriptor by value is safe at these sites:
1466/// the callee can read the backing storage but cannot retain or mutate it.
1467fn c_readonly_seq_params(
1468    stmts: &[Stmt],
1469    ctx: &CContext,
1470) -> HashMap<Symbol, std::collections::HashSet<usize>> {
1471    let mut out = HashMap::new();
1472    for stmt in stmts {
1473        let Stmt::FunctionDef {
1474            name,
1475            params,
1476            is_native: false,
1477            ..
1478        } = stmt
1479        else {
1480            continue;
1481        };
1482        let changed = ctx.mutating.get(name);
1483        let readonly = params
1484            .iter()
1485            .enumerate()
1486            .filter_map(|(i, (_, ty))| {
1487                let cty = resolve_type_expr_with_registry(ty, ctx.interner, Some(ctx.registry));
1488                let is_seq = matches!(
1489                    cty,
1490                    CType::SeqI64(_) | CType::SeqBool | CType::SeqStr | CType::SeqF64
1491                );
1492                (is_seq && !changed.and_then(|v| v.get(i)).copied().unwrap_or(true)).then_some(i)
1493            })
1494            .collect::<std::collections::HashSet<_>>();
1495        if !readonly.is_empty() {
1496            out.insert(*name, readonly);
1497        }
1498    }
1499    out
1500}
1501
1502/// Use the shared Rust/C/bytecode proof for stack-backed fixed sequences. The
1503/// owner symbol is part of the key so identically named locals in different
1504/// functions can never steal one another's capacity.
1505fn c_fixed_stack_plan(stmts: &[Stmt], ctx: &CContext) -> HashMap<(Option<Symbol>, Symbol), usize> {
1506    let borrow = c_readonly_seq_params(stmts, ctx);
1507    crate::codegen::affine_array::fixed_stack_seq_plan(stmts, &borrow, ctx.interner)
1508}
1509
1510fn codegen_function(stmt: &Stmt, ctx: &mut CContext, output: &mut String) {
1511    if let Stmt::FunctionDef {
1512        name,
1513        params,
1514        body,
1515        return_type,
1516        is_native,
1517        ..
1518    } = stmt
1519    {
1520        if *is_native {
1521            return;
1522        }
1523
1524        let func_name = escape_c_ident(ctx.interner.resolve(*name));
1525
1526        // The signature the first pass registered (declared types, `LInt` where exact) and the `LInt` locals
1527        // the exact-slot analysis settled on for this body — the same computation that decided the slots,
1528        // so a local and the parameter or field it reaches cannot disagree.
1529        let ret_type = ctx.funcs.get(name).cloned().unwrap_or_else(|| {
1530            return_type.map_or(CType::Void, |rt| {
1531                resolve_type_expr_with_registry(rt, ctx.interner, Some(ctx.registry))
1532            })
1533        });
1534        let param_types: Vec<(crate::intern::Symbol, CType)> = params
1535            .iter()
1536            .map(|(pn, pt)| (*pn, param_ctype(ctx, *name, *pn, pt)))
1537            .collect();
1538        let mut bigint_vars = body_exact_locals(ctx, *name, body, &param_types);
1539        let branchless_words =
1540            direct_c_branchless_word_vars(body, &bigint_vars, &ctx.exact.pure_calls);
1541        bigint_vars.retain(|sym| !branchless_words.contains(sym));
1542        let inout: Vec<bool> = params.iter().map(|(_, pt)| types::is_inout(pt)).collect();
1543        let param_strs: Vec<String> = param_types
1544            .iter()
1545            .zip(&inout)
1546            .map(|((pn, t), &by_ref)| {
1547                if by_ref {
1548                    types::c_inout_param_decl(t, &ctx.resolve(*pn), ctx.interner)
1549                } else {
1550                    c_param_decl(t, &ctx.resolve(*pn), ctx.interner)
1551                }
1552            })
1553            .collect();
1554
1555        write!(
1556            output,
1557            "{} {}({})",
1558            c_type_str_resolved(&ret_type, ctx.interner),
1559            func_name,
1560            param_strs.join(", ")
1561        )
1562        .unwrap();
1563        writeln!(output, " {{").unwrap();
1564
1565        let saved_vars = ctx.vars.clone();
1566        let saved_scope = std::mem::replace(&mut ctx.tower_scope, Some(*name));
1567        let saved_big = std::mem::take(&mut ctx.bigint_vars);
1568        let saved_numbers = std::mem::take(&mut ctx.number_locals);
1569        let saved_returns = ctx.current_fn_returns.clone();
1570        let saved_nonnegative = std::mem::replace(
1571            &mut ctx.nonnegative_vars,
1572            crate::codegen::expr::collect_always_nonneg(body),
1573        );
1574        ctx.bigint_vars = bigint_vars;
1575        ctx.current_fn_returns = ret_type.clone();
1576        // A parameter shares the body's outermost C block: the body's binding of its name with another
1577        // type takes a variable of its own.
1578        ctx.enter_scope();
1579        let entry_vars = ctx.vars.clone();
1580        for (pn, pt) in &param_types {
1581            ctx.vars.insert(*pn, pt.clone());
1582        }
1583        ctx.number_locals = numbers::number_locals(body, ctx);
1584        ctx.vars = entry_vars;
1585        let mut changed = values::mutated_roots(body, &ctx.fn_inout);
1586        changed.extend(ctx.changed_statics.iter().copied());
1587        for ((pname, ptype), &by_ref) in param_types.iter().zip(&inout) {
1588            let cname = ctx.bind_in_place(*pname, ptype.clone());
1589            // A `mutable` parameter is the caller's variable: every read and write of its name goes through the
1590            // pointer, and its text stays in the representation the caller holds.
1591            if by_ref {
1592                ctx.renamed.insert(*pname, format!("(*{cname})"));
1593                continue;
1594            }
1595            // A text the body appends to is a builder of its own; any other parameter the body changes arrives
1596            // as the function's own, its callers having copied it where they read it again (see `sharing`).
1597            if changed.contains(pname)
1598                && *ptype == CType::String
1599                && !ctx.plain_texts.contains(ctx.interner.resolve(*pname))
1600            {
1601                writeln!(output, "    {cname} = logos_text_builder({cname}, 0);").unwrap();
1602            }
1603            // An exact value the body changes in place is a cell of its own; the caller's stays as it was.
1604            if changed.contains(pname) && *ptype == CType::Tower {
1605                writeln!(output, "    {cname} = ltower_own({cname});").unwrap();
1606            }
1607        }
1608        let saved_changed = std::mem::replace(&mut ctx.mutated, changed);
1609        let param_names = param_types.iter().map(|(name, _)| *name).collect();
1610        let ownership = body_ownership(body, &param_names, ctx);
1611        let heap_fast = crate::optimize::active_config()
1612            .is_on(crate::optimization::Opt::Peephole)
1613            .then(|| {
1614                crate::codegen::entry_guard::detect_heap_sift_guard(params, body, ctx.interner)
1615            })
1616            .flatten()
1617            .and_then(|guard| {
1618                let word_vars = crate::codegen::entry_guard::heap_sift_word_vars(
1619                    params,
1620                    body,
1621                    &guard,
1622                    ctx.interner,
1623                )?;
1624                let plain_exact_param = |sym| {
1625                    param_types
1626                        .iter()
1627                        .position(|(name, _)| *name == sym)
1628                        .is_some_and(|i| param_types[i].1 == CType::BigInt && !inout[i])
1629                };
1630                let seq_param = param_types
1631                    .iter()
1632                    .find(|(name, _)| *name == guard.arr)
1633                    .is_some_and(|(_, ty)| types::is_seq_ctype(ty));
1634                (plain_exact_param(guard.start) && plain_exact_param(guard.end) && seq_param)
1635                    .then_some((guard, word_vars))
1636            });
1637
1638        if let Some((guard, word_vars)) = heap_fast {
1639            // Rust's entry-guard lowering keeps these indices as machine words.
1640            // Direct C historically kept the same values in `LInt`, putting
1641            // tagged compares/adds and repeated narrowing in every sift step.
1642            // Preserve exact semantics with a guarded word fast path and emit
1643            // the original exact body unchanged as the cold fallback.
1644            let arr = ctx.resolve(guard.arr).to_string();
1645            let start_exact = ctx.resolve(guard.start).to_string();
1646            let end_exact = ctx.resolve(guard.end).to_string();
1647            writeln!(
1648                output,
1649                "    /* heap-sift indices: guarded native-word fast path */"
1650            )
1651            .unwrap();
1652            writeln!(
1653                output,
1654                "    if (__builtin_expect(!({start_exact}).big && !({end_exact}).big && ({start_exact}).small >= 0 && ({end_exact}).small >= 0 && ({end_exact}).small < (int64_t)({arr}).len, 1)) {{"
1655            )
1656            .unwrap();
1657
1658            ctx.enter_scope();
1659            let exact_bigints = ctx.bigint_vars.clone();
1660            ctx.bigint_vars.retain(|sym| !word_vars.contains(sym));
1661            let start_word = ctx.declare(guard.start, CType::Int64);
1662            let end_word = ctx.declare(guard.end, CType::Int64);
1663            writeln!(
1664                output,
1665                "        int64_t {start_word} = ({start_exact}).small;"
1666            )
1667            .unwrap();
1668            writeln!(output, "        int64_t {end_word} = ({end_exact}).small;").unwrap();
1669            ctx.in_body(false, |ctx| {
1670                ctx.ownership = Some(ownership.clone());
1671                for s in *body {
1672                    codegen_stmt(s, ctx, output, 2);
1673                }
1674            });
1675            ctx.bigint_vars = exact_bigints;
1676            ctx.exit_scope();
1677
1678            writeln!(output, "    }} else {{").unwrap();
1679            ctx.enter_scope();
1680            ctx.in_body(false, |ctx| {
1681                ctx.ownership = Some(ownership.clone());
1682                for s in *body {
1683                    codegen_stmt(s, ctx, output, 2);
1684                }
1685            });
1686            ctx.exit_scope();
1687            writeln!(output, "    }}").unwrap();
1688            crate::optimize::mark_fired(crate::optimization::Opt::Peephole);
1689        } else {
1690            ctx.in_body(false, |ctx| {
1691                ctx.ownership = Some(ownership);
1692                for s in *body {
1693                    codegen_stmt(s, ctx, output, 1);
1694                }
1695            });
1696        }
1697        ctx.mutated = saved_changed;
1698        ctx.exit_scope();
1699
1700        ctx.vars = saved_vars;
1701        ctx.tower_scope = saved_scope;
1702        ctx.bigint_vars = saved_big;
1703        ctx.number_locals = saved_numbers;
1704        ctx.current_fn_returns = saved_returns;
1705        ctx.nonnegative_vars = saved_nonnegative;
1706        writeln!(output, "}}\n").unwrap();
1707    }
1708}
1709
1710// =============================================================================
1711// Entry Point
1712// =============================================================================
1713
1714/// Every OTHER struct/enum a struct or enum's fields name AS A DIRECT VALUE (`Named`/`Primitive`,
1715/// never through a `Seq`/`Map`/`Set` generic) — the true "must be a COMPLETE type first" ordering
1716/// constraint. A container's element is stored behind a pointer (`Seq_<Name>` is `{ Name *data;
1717/// … }`), which C only needs FORWARD-DECLARED, not complete — `codegen_c_type_defs`'s Phase A
1718/// forward-declares every type unconditionally, so a container reference is never an ordering
1719/// dependency at all (treating it as one is what turned `JEntry { val: Json }` / `Json { …
1720/// entries: Seq of JEntry }` into an unresolvable false CYCLE: each direction "needed" the other's
1721/// FULL body). A type's OWN symbol is dropped: self-reference is a per-type LAYOUT concern
1722/// (forward-declare + box the field), never a cross-type ordering constraint.
1723fn type_value_deps(sym: Symbol, registry: &TypeRegistry) -> Vec<Symbol> {
1724    fn direct_dep(ty: &crate::analysis::FieldType, registry: &TypeRegistry, out: &mut Vec<Symbol>) {
1725        if let crate::analysis::FieldType::Named(s) | crate::analysis::FieldType::Primitive(s) = ty
1726        {
1727            if matches!(
1728                registry.get(*s),
1729                Some(
1730                    crate::analysis::TypeDef::Struct { .. } | crate::analysis::TypeDef::Enum { .. }
1731                )
1732            ) {
1733                out.push(*s);
1734            }
1735        }
1736    }
1737    let mut out = Vec::new();
1738    match registry.get(sym) {
1739        Some(crate::analysis::TypeDef::Struct { fields, .. }) => {
1740            for f in fields {
1741                direct_dep(&f.ty, registry, &mut out);
1742            }
1743        }
1744        Some(crate::analysis::TypeDef::Enum { variants, .. }) => {
1745            for v in variants {
1746                for f in &v.fields {
1747                    direct_dep(&f.ty, registry, &mut out);
1748                }
1749            }
1750        }
1751        _ => {}
1752    }
1753    out.retain(|d| *d != sym);
1754    out
1755}
1756
1757/// One declaration order for EVERY struct and enum the program defines (`defined`, see
1758/// `callgraph::program_type_defs`), structs and enums interleaved by dependency — a struct can hold an enum by value (`JEntry { val: Json }`) just as
1759/// readily as an enum can hold another enum (`JsonResult::JOk(v: Json)`), so ordering the two
1760/// kinds as separate blocks (all structs, THEN all enums) leaves a struct-before-its-enum-field
1761/// case with no forward declaration at all (`error: unknown type name 'Json'`) — the C tier bug
1762/// this migration exists to close. `defined` is a hash set, so two independent
1763/// types (no dependency either way) would otherwise emit in a nondeterministic order too; the
1764/// stable name sort below (before the topological pass reorders true dependencies) makes
1765/// `compile_to_c` reproducible for those.
1766fn ordered_type_defs(
1767    registry: &TypeRegistry,
1768    interner: &Interner,
1769    defined: &std::collections::HashSet<Symbol>,
1770) -> Vec<Symbol> {
1771    use std::collections::HashSet;
1772
1773    let mut syms: Vec<Symbol> = defined.iter().copied().collect();
1774    syms.sort_by(|a, b| interner.resolve(*a).cmp(interner.resolve(*b)));
1775
1776    // Simple iterative topological sort (O(n^2) but n is small).
1777    let mut emitted: HashSet<Symbol> = HashSet::new();
1778    let mut ordered: Vec<Symbol> = Vec::new();
1779    let mut remaining = syms;
1780    while !remaining.is_empty() {
1781        let prev_len = remaining.len();
1782        remaining.retain(|sym| {
1783            let deps = type_value_deps(*sym, registry);
1784            if deps.iter().all(|d| emitted.contains(d)) {
1785                emitted.insert(*sym);
1786                ordered.push(*sym);
1787                return false; // remove from remaining
1788            }
1789            true
1790        });
1791        if remaining.len() == prev_len {
1792            // Circular dependency or missing type — emit remaining as-is.
1793            for sym in &remaining {
1794                ordered.push(*sym);
1795            }
1796            break;
1797        }
1798    }
1799    ordered
1800}
1801
1802/// Every aggregate the C tier defines as a `struct` — the program's records and enums, the tuples
1803/// its signatures and statements use, and the nested-sequence wrappers — in four phases, each safe
1804/// only once the PRIOR phase has run for every type (the forward-declare/body split a genuinely
1805/// cyclic container reference needs, see `type_value_deps`):
1806/// A. forward-declare every record, enum and tuple (`typedef struct Name Name;`) — always legal, a
1807///    struct tag can be declared before its members are known.
1808/// B. every CONTAINER — `Seq_<Name>` for each of those, then each nested `Seq_Seq_…` innermost
1809///    first. A container holds its element behind a pointer, so it needs only A's declaration, and
1810///    a record may then hold any sequence by value.
1811/// C. every value body in TRUE by-value dependency order: records and enums interleaved (see
1812///    `ordered_type_defs`), then tuples, which may hold a record but never appear inside one.
1813/// D. every FUNCTION — each container's `new`/`push`/`get`/`set`/`len`, each `_to_string` and
1814///    `show_seq_…` — which copy elements BY VALUE and so need every body from C. Every Phase D
1815///    PROTOTYPE precedes every Phase D definition: the helpers call across types in whatever
1816///    direction the fields point (`Grid_to_string` renders a `Seq of Point` field through
1817///    `seq_Point_to_string`), and a container reference puts no order between the two, so no
1818///    emission order alone can put every callee first.
1819fn codegen_c_aggregates(
1820    registry: &TypeRegistry,
1821    interner: &Interner,
1822    defined: &std::collections::HashSet<Symbol>,
1823    display_names: &HashMap<Symbol, Symbol>,
1824    facts: &exact::FieldFacts,
1825    tuples: &[(String, Vec<CType>)],
1826    seqseqs: &[CType],
1827    output: &mut String,
1828) {
1829    use std::fmt::Write;
1830
1831    let ordered = ordered_type_defs(registry, interner, defined);
1832    let users: Vec<(Symbol, String)> = ordered
1833        .iter()
1834        .map(|sym| (*sym, escape_c_ident(interner.resolve(*sym))))
1835        .collect();
1836
1837    for (_, name) in &users {
1838        writeln!(output, "typedef struct {0} {0};", name).unwrap();
1839    }
1840    for (tname, _) in tuples {
1841        writeln!(output, "typedef struct {0} {0};", tname).unwrap();
1842    }
1843
1844    for name in users
1845        .iter()
1846        .map(|(_, n)| n)
1847        .chain(tuples.iter().map(|(t, _)| t))
1848    {
1849        writeln!(
1850            output,
1851            "typedef struct {{ {name} *data; size_t len; size_t cap; }} Seq_{name};"
1852        )
1853        .unwrap();
1854    }
1855    for st in seqseqs {
1856        if let CType::SeqSeq(inner) = st {
1857            let elem = c_type_str_resolved(inner, interner);
1858            writeln!(
1859                output,
1860                "typedef struct {{ {elem} *data; size_t len; size_t cap; }} Seq_{elem};"
1861            )
1862            .unwrap();
1863        }
1864    }
1865
1866    for body in aggregate_body_order(registry, interner, &users, tuples) {
1867        match body {
1868            Aggregate::User(sym) => match registry.get(sym) {
1869                Some(crate::analysis::TypeDef::Struct { .. }) => {
1870                    emit_struct_body(sym, registry, interner, facts, output)
1871                }
1872                Some(crate::analysis::TypeDef::Enum { .. }) => {
1873                    emit_enum_body(sym, registry, interner, facts, output)
1874                }
1875                _ => {}
1876            },
1877            Aggregate::Tuple(i) => {
1878                let (tname, elems) = &tuples[i];
1879                writeln!(output, "struct {tname} {{").unwrap();
1880                for (k, e) in elems.iter().enumerate() {
1881                    writeln!(output, "    {} f{};", c_type_str_resolved(e, interner), k).unwrap();
1882                }
1883                writeln!(output, "}};").unwrap();
1884            }
1885        }
1886    }
1887
1888    let mut phase_d: Vec<CFn> = Vec::new();
1889    for (sym, name) in &users {
1890        phase_d.extend(seq_family(name, name));
1891        let shown = match registry.get(*sym) {
1892            Some(crate::analysis::TypeDef::Struct { .. }) => {
1893                struct_show(*sym, registry, interner, display_names, facts)
1894            }
1895            Some(crate::analysis::TypeDef::Enum { .. }) => {
1896                enum_show(*sym, registry, interner, display_names, facts)
1897            }
1898            _ => None,
1899        };
1900        if let Some(to_string) = shown {
1901            phase_d.push(to_string);
1902            phase_d.extend(seq_show(name, &format!("{name}_to_string(s->data[i])")));
1903        }
1904    }
1905    for (tname, elems) in tuples {
1906        phase_d.extend(seq_family(tname, tname));
1907        phase_d.push(tuple_show(tname, elems, interner));
1908        phase_d.extend(seq_show(tname, &format!("{tname}_to_string(s->data[i])")));
1909    }
1910    for st in seqseqs {
1911        if let CType::SeqSeq(inner) = st {
1912            let elem = c_type_str_resolved(inner, interner);
1913            phase_d.extend(seq_family(&elem, &elem));
1914            // Each element (itself a `Seq_…`) renders via its own `*_to_string` (`c_field_to_string_expr`
1915            // prepends the `&`), so a nested `Show [[1,2]]` prints `[[1, 2], …]` — matching the oracle.
1916            let render =
1917                crate::codegen_c::types::c_field_to_string_expr(inner, "s->data[i]", interner);
1918            phase_d.extend(seq_show(&elem, &render));
1919        }
1920    }
1921    for f in &phase_d {
1922        writeln!(output, "{};", f.sig).unwrap();
1923    }
1924    for f in &phase_d {
1925        writeln!(output, "{} {}", f.sig, f.body).unwrap();
1926    }
1927}
1928
1929/// One value body Phase C emits: a record or enum, or a tuple (by its index).
1930#[derive(Clone, Copy)]
1931enum Aggregate {
1932    User(Symbol),
1933    Tuple(usize),
1934}
1935
1936/// Every value body in by-value dependency order: a body follows every record, enum and tuple it
1937/// holds by value (a record may hold a tuple, a tuple a record). A container reference holds its
1938/// element behind a pointer and adds no edge, nor does an enum's boxed field naming itself. The
1939/// records keep `ordered_type_defs`' order and the tuples their collected order wherever no edge
1940/// decides; a genuine by-value cycle (not legal C either) is emitted as it stands.
1941fn aggregate_body_order(
1942    registry: &TypeRegistry,
1943    interner: &Interner,
1944    users: &[(Symbol, String)],
1945    tuples: &[(String, Vec<CType>)],
1946) -> Vec<Aggregate> {
1947    fn held(ct: &CType, interner: &Interner, out: &mut Vec<String>) {
1948        match ct {
1949            CType::Struct(s) | CType::Enum(s) => out.push(escape_c_ident(interner.resolve(*s))),
1950            CType::Tuple(_) | CType::Record(_) => out.push(c_type_str_resolved(ct, interner)),
1951            _ => {}
1952        }
1953    }
1954    let deps = |a: Aggregate| -> Vec<String> {
1955        let mut out = Vec::new();
1956        match a {
1957            Aggregate::User(sym) => {
1958                let field_types: Vec<&crate::analysis::FieldType> = match registry.get(sym) {
1959                    Some(crate::analysis::TypeDef::Struct { fields, .. }) => fields.iter().map(|f| &f.ty).collect(),
1960                    Some(crate::analysis::TypeDef::Enum { variants, .. }) => variants
1961                        .iter()
1962                        .flat_map(|v| v.fields.iter().map(|f| &f.ty))
1963                        .filter(|ft| !matches!(ft, crate::analysis::FieldType::Named(fsym) if *fsym == sym))
1964                        .collect(),
1965                    _ => Vec::new(),
1966                };
1967                for ft in field_types {
1968                    held(
1969                        &field_type_to_ctype(ft, interner, registry),
1970                        interner,
1971                        &mut out,
1972                    );
1973                }
1974                let own = escape_c_ident(interner.resolve(sym));
1975                out.retain(|d| *d != own);
1976            }
1977            Aggregate::Tuple(i) => {
1978                for e in &tuples[i].1 {
1979                    held(e, interner, &mut out);
1980                }
1981            }
1982        }
1983        out
1984    };
1985    let name = |a: Aggregate| match a {
1986        Aggregate::User(sym) => escape_c_ident(interner.resolve(sym)),
1987        Aggregate::Tuple(i) => tuples[i].0.clone(),
1988    };
1989    let mut remaining: Vec<Aggregate> = users
1990        .iter()
1991        .map(|(sym, _)| Aggregate::User(*sym))
1992        .chain((0..tuples.len()).map(Aggregate::Tuple))
1993        .collect();
1994    let defined: std::collections::HashSet<String> = remaining.iter().map(|a| name(*a)).collect();
1995    let mut emitted: std::collections::HashSet<String> = std::collections::HashSet::new();
1996    let mut order = Vec::with_capacity(remaining.len());
1997    while !remaining.is_empty() {
1998        let before = remaining.len();
1999        remaining.retain(|a| {
2000            let ready = deps(*a)
2001                .iter()
2002                .all(|d| emitted.contains(d) || !defined.contains(d));
2003            if ready {
2004                emitted.insert(name(*a));
2005                order.push(*a);
2006            }
2007            !ready
2008        });
2009        if remaining.len() == before {
2010            order.extend(remaining.drain(..));
2011        }
2012    }
2013    order
2014}
2015
2016/// One generated C function, its signature apart from its body so the prototype and the definition
2017/// are printed from the same string.
2018struct CFn {
2019    sig: String,
2020    body: String,
2021}
2022
2023/// The dynamic-array family over one element type: `Seq_<key>` with `seq_<key>_new/push/get/set/len`
2024/// (1-based `get`/`set`, doubling growth). `elem` is the element's C type, `key` the name the family
2025/// is spelled with (they differ only for a nested sequence's element type).
2026fn seq_family(elem: &str, key: &str) -> Vec<CFn> {
2027    let sq = format!("Seq_{key}");
2028    let f = |sig: String, body: String| CFn { sig, body };
2029    vec![
2030        f(format!("__attribute__((unused)) static {sq} seq_{key}_new(void)"), format!("{{ return ({sq}){{NULL, 0, 0}}; }}")),
2031        f(
2032            format!("__attribute__((unused)) static void seq_{key}_push({sq} *s, {elem} val)"),
2033            format!("{{ if (s->len == s->cap) {{ s->cap = s->cap ? s->cap * 2 : 8; s->data = ({elem} *)lc_gc_realloc(s->data, s->cap * sizeof({elem})); }} s->data[s->len++] = val; }}"),
2034        ),
2035        f(format!("__attribute__((unused)) static {elem} seq_{key}_get({sq} *s, int64_t idx)"), "{ return s->data[logos_idx0(idx, s->len)]; }".to_string()),
2036        f(format!("__attribute__((unused)) static void seq_{key}_set({sq} *s, int64_t idx, {elem} val)"), "{ s->data[logos_idx0(idx, s->len)] = val; }".to_string()),
2037        f(format!("__attribute__((unused)) static int64_t seq_{key}_len({sq} *s)"), "{ return (int64_t)s->len; }".to_string()),
2038    ]
2039}
2040
2041/// `seq_<key>_to_string` (`[a, b]`, each element rendered by `render`, an expression over
2042/// `s->data[i]` yielding a fresh `char*`) and the printing `show_seq_<key>` beside it.
2043fn seq_show(key: &str, render: &str) -> Vec<CFn> {
2044    let sq = format!("Seq_{key}");
2045    vec![
2046        CFn {
2047            sig: format!("__attribute__((unused)) static char *seq_{key}_to_string({sq} *s)"),
2048            body: format!("{{ char *out = lc_gc_strdup(\"[\"); for (size_t i = 0; i < s->len; i++) {{ if (i > 0) {{ char *c1 = str_concat(out, \", \"); lc_gc_free(out); out = c1; }} char *__e = {render}; char *c2 = str_concat(out, __e); lc_gc_free(out); lc_gc_free(__e); out = c2; }} char *cf = str_concat(out, \"]\"); lc_gc_free(out); return cf; }}"),
2049        },
2050        CFn {
2051            sig: format!("__attribute__((unused)) static void show_seq_{key}({sq} *s)"),
2052            body: format!("{{ char *t = seq_{key}_to_string(s); printf(\"%s\\n\", t); lc_gc_free(t); }}"),
2053        },
2054    ]
2055}
2056
2057/// Whole-tuple Show: `(v0, v1, …)` — PARENS (distinct from a Seq's brackets), each field through
2058/// its own renderer.
2059fn tuple_show(tname: &str, elems: &[CType], interner: &Interner) -> CFn {
2060    use std::fmt::Write;
2061
2062    let fmt: String = (0..elems.len())
2063        .map(|_| "%s")
2064        .collect::<Vec<_>>()
2065        .join(", ");
2066    let mut body = String::from("{\n");
2067    let mut args = Vec::new();
2068    for (i, e) in elems.iter().enumerate() {
2069        let render =
2070            crate::codegen_c::types::c_field_to_string_expr(e, &format!("v.f{i}"), interner);
2071        writeln!(body, "    char *__s{i} = {render};").unwrap();
2072        args.push(format!("__s{i}"));
2073    }
2074    writeln!(
2075        body,
2076        "    char *out = logos_dyn_sprintf(\"({fmt})\", {});",
2077        args.join(", ")
2078    )
2079    .unwrap();
2080    for i in 0..elems.len() {
2081        writeln!(body, "    lc_gc_free(__s{i});").unwrap();
2082    }
2083    writeln!(body, "    return out;").unwrap();
2084    body.push('}');
2085    CFn {
2086        sig: format!("__attribute__((unused)) static char *{tname}_to_string({tname} v)"),
2087        body,
2088    }
2089}
2090
2091/// Phase C for a struct: its full field list, as `struct Name { … };` — matching Phase A's prior
2092/// `typedef struct Name Name;` (a plain tagged struct definition, not a second `typedef`).
2093fn emit_struct_body(
2094    sym: Symbol,
2095    registry: &TypeRegistry,
2096    interner: &Interner,
2097    facts: &exact::FieldFacts,
2098    output: &mut String,
2099) {
2100    use std::fmt::Write;
2101
2102    if let Some(crate::analysis::TypeDef::Struct { fields, .. }) = registry.get(sym) {
2103        let name = escape_c_ident(interner.resolve(sym));
2104        writeln!(output, "struct {name} {{").unwrap();
2105        for field in fields {
2106            let field_name = escape_c_ident(interner.resolve(field.name));
2107            let ctype = exact::field_ctype(sym, field, interner, registry, facts);
2108            let type_str = c_type_str_resolved(&ctype, interner);
2109            writeln!(output, "    {} {};", type_str, field_name).unwrap();
2110        }
2111        writeln!(output, "}};").unwrap();
2112    }
2113}
2114
2115/// Phase D for a struct: the whole-value `Show` — `<Name>_to_string` renders `Name { field: value }`,
2116/// byte-identical to the interpreter oracle (brace-delimited, fields SORTED by name, nested values
2117/// through their own renderers). `None` when a field is not C-renderable; such a struct keeps the
2118/// inline field-show path.
2119fn struct_show(
2120    sym: Symbol,
2121    registry: &TypeRegistry,
2122    interner: &Interner,
2123    display_names: &HashMap<Symbol, Symbol>,
2124    facts: &exact::FieldFacts,
2125) -> Option<CFn> {
2126    use std::fmt::Write;
2127
2128    let Some(crate::analysis::TypeDef::Struct { fields, .. }) = registry.get(sym) else {
2129        return None;
2130    };
2131    if !crate::codegen_c::types::c_struct_showable(sym, registry, interner) {
2132        return None;
2133    }
2134    let name = escape_c_ident(interner.resolve(sym));
2135    let ts = crate::codegen_c::types::struct_to_string_fn(sym, interner);
2136    let disp = crate::codegen_c::types::display_name_of(sym, display_names, interner);
2137    let mut sorted: Vec<&crate::analysis::FieldDef> = fields.iter().collect();
2138    sorted.sort_by(|a, b| interner.resolve(a.name).cmp(interner.resolve(b.name)));
2139    let mut body = String::from("{\n");
2140    if sorted.is_empty() {
2141        writeln!(body, "    return lstrdup(\"{disp}\");").unwrap();
2142    } else {
2143        let mut fmt_fields = Vec::new();
2144        let mut args = Vec::new();
2145        for (i, fd) in sorted.iter().enumerate() {
2146            let field_name = escape_c_ident(interner.resolve(fd.name));
2147            let ct = exact::field_ctype(sym, fd, interner, registry, facts);
2148            let render = crate::codegen_c::types::c_field_to_string_expr(
2149                &ct,
2150                &format!("v.{}", field_name),
2151                interner,
2152            );
2153            writeln!(body, "    char *__s{i} = {render};").unwrap();
2154            fmt_fields.push(format!("{}: %s", interner.resolve(fd.name)));
2155            args.push(format!("__s{i}"));
2156        }
2157        writeln!(
2158            body,
2159            "    char *out = logos_dyn_sprintf(\"{} {{ {} }}\", {});",
2160            disp,
2161            fmt_fields.join(", "),
2162            args.join(", ")
2163        )
2164        .unwrap();
2165        for i in 0..sorted.len() {
2166            writeln!(body, "    lc_gc_free(__s{i});").unwrap();
2167        }
2168        writeln!(body, "    return out;").unwrap();
2169    }
2170    body.push('}');
2171    Some(CFn {
2172        sig: format!("__attribute__((unused)) static char *{ts}({name} v)"),
2173        body,
2174    })
2175}
2176
2177/// Phase D for an enum: `<Name>_to_string`, rendering a value exactly as the interpreter shows it —
2178/// a unit variant as its name, a variant with a payload as `Variant(a, b)` (positional, each field
2179/// through its own renderer, a boxed recursive field dereferenced), and an instance of the core
2180/// `Option` as its payload, or `nothing`. `None` when a field is not renderable.
2181fn enum_show(
2182    sym: Symbol,
2183    registry: &TypeRegistry,
2184    interner: &Interner,
2185    display_names: &HashMap<Symbol, Symbol>,
2186    facts: &exact::FieldFacts,
2187) -> Option<CFn> {
2188    use std::fmt::Write;
2189
2190    let Some(crate::analysis::TypeDef::Enum { variants, .. }) = registry.get(sym) else {
2191        return None;
2192    };
2193    if !crate::codegen_c::types::c_enum_showable(sym, registry, interner) {
2194        return None;
2195    }
2196    let name = escape_c_ident(interner.resolve(sym));
2197    let ts = crate::codegen_c::types::struct_to_string_fn(sym, interner);
2198    let is_option = display_names
2199        .get(&sym)
2200        .is_some_and(|g| interner.resolve(*g) == "Option");
2201    let mut body = String::from("{\n    switch (v.tag) {\n");
2202    for v in variants {
2203        let vname = escape_c_ident(interner.resolve(v.name));
2204        let shown = interner.resolve(v.name);
2205        writeln!(body, "    case {name}_{vname}: {{").unwrap();
2206        let renders: Vec<String> = v
2207            .fields
2208            .iter()
2209            .map(|f| {
2210                let fname = escape_c_ident(interner.resolve(f.name));
2211                let boxed =
2212                    matches!(&f.ty, crate::analysis::FieldType::Named(fsym) if *fsym == sym);
2213                let access = if boxed {
2214                    format!("(*v.data.{vname}.{fname})")
2215                } else {
2216                    format!("v.data.{vname}.{fname}")
2217                };
2218                let ct = exact::field_ctype(v.name, f, interner, registry, facts);
2219                crate::codegen_c::types::c_field_to_string_expr(&ct, &access, interner)
2220            })
2221            .collect();
2222        match (is_option, renders.as_slice()) {
2223            (true, []) => writeln!(body, "        return lstrdup(\"nothing\");").unwrap(),
2224            (true, [payload]) => writeln!(body, "        return {payload};").unwrap(),
2225            (_, []) => writeln!(body, "        return lstrdup(\"{shown}\");").unwrap(),
2226            _ => {
2227                for (i, r) in renders.iter().enumerate() {
2228                    writeln!(body, "        char *__s{i} = {r};").unwrap();
2229                }
2230                let fmt = vec!["%s"; renders.len()].join(", ");
2231                let args: Vec<String> = (0..renders.len()).map(|i| format!("__s{i}")).collect();
2232                writeln!(
2233                    body,
2234                    "        char *out = logos_dyn_sprintf(\"{shown}({fmt})\", {});",
2235                    args.join(", ")
2236                )
2237                .unwrap();
2238                for i in 0..renders.len() {
2239                    writeln!(body, "        lc_gc_free(__s{i});").unwrap();
2240                }
2241                writeln!(body, "        return out;").unwrap();
2242            }
2243        }
2244        writeln!(body, "    }}").unwrap();
2245    }
2246    body.push_str("    }\n    return lstrdup(\"\");\n}");
2247    Some(CFn {
2248        sig: format!("__attribute__((unused)) static char *{ts}({name} v)"),
2249        body,
2250    })
2251}
2252
2253/// Phase C for an enum: the tag enum, then the tagged-union body as `struct Name { … };` —
2254/// matching Phase A's prior forward declaration exactly like a struct's body does. A field
2255/// DIRECTLY naming its own enum (never through a container) still boxes to a pointer, exactly as
2256/// before — that per-field self-reference is a LAYOUT concern this phase split does not change.
2257fn emit_enum_body(
2258    sym: Symbol,
2259    registry: &TypeRegistry,
2260    interner: &Interner,
2261    facts: &exact::FieldFacts,
2262    output: &mut String,
2263) {
2264    use std::fmt::Write;
2265    if let Some(crate::analysis::TypeDef::Enum { variants, .. }) = registry.get(sym) {
2266        let name = escape_c_ident(interner.resolve(sym));
2267
2268        // Tag enum
2269        write!(output, "typedef enum {{ ").unwrap();
2270        for (i, v) in variants.iter().enumerate() {
2271            let vname = escape_c_ident(interner.resolve(v.name));
2272            if i > 0 {
2273                write!(output, ", ").unwrap();
2274            }
2275            write!(output, "{}_{}", name, vname).unwrap();
2276        }
2277        writeln!(output, " }} {}_tag;\n", name).unwrap();
2278
2279        let has_data = variants.iter().any(|v| !v.fields.is_empty());
2280
2281        writeln!(output, "struct {} {{", name).unwrap();
2282        writeln!(output, "    {}_tag tag;", name).unwrap();
2283        if has_data {
2284            writeln!(output, "    union {{").unwrap();
2285            for v in variants {
2286                if v.fields.is_empty() {
2287                    continue;
2288                }
2289                let vname = escape_c_ident(interner.resolve(v.name));
2290                writeln!(output, "        struct {{").unwrap();
2291                for f in &v.fields {
2292                    let fname = escape_c_ident(interner.resolve(f.name));
2293                    let is_self_ref = if let crate::analysis::FieldType::Named(fsym) = &f.ty {
2294                        *fsym == sym
2295                    } else {
2296                        false
2297                    };
2298                    if is_self_ref {
2299                        writeln!(output, "            {} *{};", name, fname).unwrap();
2300                    } else {
2301                        let ctype = exact::field_ctype(v.name, f, interner, registry, facts);
2302                        let type_str = c_type_str_resolved(&ctype, interner);
2303                        writeln!(output, "            {} {};", type_str, fname).unwrap();
2304                    }
2305                }
2306                writeln!(output, "        }} {};", vname).unwrap();
2307            }
2308            writeln!(output, "    }} data;").unwrap();
2309        }
2310        writeln!(output, "}};\n").unwrap();
2311    }
2312}
2313
2314pub fn codegen_program_c(
2315    stmts: &[Stmt],
2316    registry: &TypeRegistry,
2317    interner: &Interner,
2318    policies: &crate::analysis::policy::PolicyRegistry,
2319) -> String {
2320    codegen_monomorphic_program_c(
2321        stmts,
2322        registry,
2323        interner,
2324        policies,
2325        &HashMap::new(),
2326        TaskTier::Coroutines,
2327    )
2328}
2329
2330/// [`codegen_program_c`] for a monomorphized program: `instances` names the generic type each
2331/// instance type applies, so its values show under the generic's name.
2332pub fn codegen_monomorphic_program_c(
2333    stmts: &[Stmt],
2334    _registry: &TypeRegistry,
2335    interner: &Interner,
2336    policies: &crate::analysis::policy::PolicyRegistry,
2337    instances: &HashMap<Symbol, crate::monomorphize::TypeInstance>,
2338    tier: TaskTier,
2339) -> String {
2340    let mut output = String::with_capacity(4096);
2341    let mut ctx = CContext::new(interner, _registry);
2342    // The top-level context is the only one that emits `Check` statements, so it carries the real
2343    // policy registry; the helper/child contexts keep the empty default.
2344    ctx.policies = policies;
2345    ctx.display_names = instances
2346        .iter()
2347        .map(|(inst, of)| (*inst, of.generic))
2348        .collect();
2349    // The exact extension's reach: the bindings, parameters and results it reaches hold `LTower`s.
2350    ctx.tower = tower::reach_of(stmts, _registry, interner);
2351    // Where a stored `nothing` reaches: those bindings, parameters and results hold value-or-nothing.
2352    ctx.absence = absent::of_program(stmts, _registry, interner);
2353
2354    // Does the program use the deterministic concurrency runtime? This single flag gates EVERYTHING
2355    // concurrency-related below (the `ucontext` scheduler prelude, the task-entry wrappers, wrapping
2356    // Main as a task + `logos_sched_bootstrap`). When it is false the output is byte-identical to a
2357    // world without the scheduler — the invariant that keeps the ~1246 non-concurrency C tests fixed.
2358    let uses_concurrency = program_uses_concurrency(stmts);
2359    ctx.uses_concurrency = uses_concurrency;
2360    // Under the stepped tier, the functions that wait run only as step functions, and a call to one from a
2361    // stepped body pushes its frame.
2362    let steps =
2363        (uses_concurrency && tier == TaskTier::Stepped).then(|| stepped::stepped_functions(stmts));
2364    if let Some(s) = &steps {
2365        ctx.stepped_fns = s.waits.clone();
2366    }
2367
2368    // Does the program use a single-replica counter CRDT (`ConvergentCount`/`Tally`)? This gates the
2369    // `logos_crdt` runtime and seeds the `(struct, field)` counter side-set the codegen consults. When
2370    // no struct has a counter field, the runtime is not emitted and the output is byte-identical to a
2371    // world without CRDTs — the invariant that keeps the ~1246 non-CRDT C tests fixed.
2372    let uses_crdt = program_uses_crdt_counter(_registry, interner);
2373    ctx.counter_fields = counter_crdt_fields(_registry, interner);
2374
2375    // The scalar exact higher-order functions: the call-site half is ONE decision shared with the Rust
2376    // backend (`codegen::bigint_promote::exact_hof_fns`: every site passes an INLINE closure literal in every
2377    // `fn`-typed position, since a closure VARIABLE was already emitted `int64_t (*)(int64_t)` at its `Let`,
2378    // and not every site is provably within `i64`); the shape half is `is_exact_hof`. Then every
2379    // exact-integer slot of the program (see `exact`), before any type, signature or body is emitted.
2380    let site_exact_hofs = crate::codegen::bigint_promote::exact_hof_fns(stmts, interner);
2381    ctx.exact_hofs = stmts
2382        .iter()
2383        .filter_map(|stmt| match stmt {
2384            Stmt::FunctionDef {
2385                name,
2386                params,
2387                is_native: false,
2388                ..
2389            } => {
2390                let param_ctypes: Vec<CType> = params
2391                    .iter()
2392                    .map(|(_, pt)| resolve_type_expr_with_registry(pt, interner, Some(_registry)))
2393                    .collect();
2394                // A function lifted out of a closure is a function value the program wrote: exact, as a closure is.
2395                let lifted = crate::optimize::is_lifted_closure(*name);
2396                ((is_exact_hof(&param_ctypes) && site_exact_hofs.contains(name)) || lifted)
2397                    .then_some(*name)
2398            }
2399            _ => None,
2400        })
2401        .collect();
2402    ctx.int_oracle = Some(std::rc::Rc::new(crate::optimize::oracle_analyze_with(
2403        stmts, interner,
2404    )));
2405    ctx.exact = exact::exact_slots(
2406        stmts,
2407        _registry,
2408        interner,
2409        &ctx.exact_hofs,
2410        &ctx.counter_fields,
2411        ctx.int_oracle.as_deref(),
2412    );
2413    ctx.quiet_fns = std::rc::Rc::new(quiet_functions(stmts, interner));
2414
2415    output.push_str(runtime::C_GC_COLLECTOR);
2416    output.push_str(&c_runtime());
2417    output.push_str(CLOSURE_TYPE);
2418    output.push_str(TEXT_BUILDER);
2419    output.push_str(CHECKED_INT);
2420    if ctx.tower.is_some() {
2421        output.push_str(tower::RUNTIME);
2422    }
2423    if uses_concurrency {
2424        if steps.is_some() {
2425            output.push_str(C_STEPPED_HOST);
2426            output.push_str(STEPPED_SCHEDULER);
2427        } else {
2428            output.push_str(C_CONCURRENCY_RUNTIME);
2429        }
2430    }
2431    if uses_crdt {
2432        output.push_str(C_CRDT_RUNTIME);
2433    }
2434    // The offline loopback networking transport — emitted only when the program uses networking, so a
2435    // non-net program stays byte-identical.
2436    if program_uses_net(stmts) {
2437        output.push_str(&c_net_runtime());
2438    }
2439    if program_uses_files(stmts) {
2440        output.push_str(FILE_RUNTIME);
2441    }
2442    ctx.nothing_names = nothing_names(stmts);
2443    let mut holds_nothing = !ctx.nothing_names.is_empty() || !ctx.absence.is_empty();
2444    for_each_node(stmts, |node| {
2445        holds_nothing |= matches!(
2446            node,
2447            Visited::Expr(Expr::ChunkAt { .. }) | Visited::Stmt(Stmt::Pop { into: Some(_), .. })
2448        );
2449    });
2450    if !uses_concurrency && holds_nothing {
2451        output.push_str(OPT_RUNTIME);
2452    }
2453    // A list or a map whose items may be nothing holds each as a value-or-nothing: one family for every payload,
2454    // since a value-or-nothing is one C type; what renders and compares them is the payload's.
2455    if holds_nothing {
2456        output.push_str(OPT_SEQ_FAMILY);
2457        let opt = || Box::new(CType::Opt(Box::new(CType::Int64)));
2458        emit_generic_map_family(&mut output, &CType::MapStrValue(opt()), interner, false);
2459        emit_generic_map_family(&mut output, &CType::MapI64Value(opt()), interner, false);
2460    }
2461
2462    // Value-type `Seq` families — `Seq of Money/Quantity/Modular/Uuid/Complex/decimal` on the C tier.
2463    // The element structs are defined in `C_RUNTIME`; here we synthesize the dynamic-array family +
2464    // a `[a, b]` Show for each. Always emitted (`__attribute__((unused))` → gcc drops the unused ones),
2465    // so a Seq literal of any value type resolves without threading a collection pass. Keyed on the
2466    // element C-type; the per-type `*_to_string` renders each element (the `LDec` one takes a pointer).
2467    for (elem, to_str) in [
2468        ("LMoney", "money_to_string(s->data[i])"),
2469        ("LQuant", "quant_to_string(s->data[i])"),
2470        ("LMod", "mod_to_string(s->data[i])"),
2471        ("LUuid", "uuid_to_string(s->data[i])"),
2472        ("LComplex", "cplx_to_string(s->data[i])"),
2473        ("LDec", "ldec_to_string(&s->data[i])"),
2474    ] {
2475        let sq = format!("Seq_{elem}");
2476        writeln!(
2477            output,
2478            "typedef struct {{ {elem} *data; size_t len; size_t cap; }} {sq};"
2479        )
2480        .unwrap();
2481        writeln!(output, "__attribute__((unused)) static {sq} seq_{elem}_new(void) {{ return ({sq}){{NULL, 0, 0}}; }}").unwrap();
2482        writeln!(output, "__attribute__((unused)) static void seq_{elem}_push({sq} *s, {elem} val) {{ if (s->len == s->cap) {{ s->cap = s->cap ? s->cap * 2 : 8; s->data = ({elem} *)lc_gc_realloc(s->data, s->cap * sizeof({elem})); }} s->data[s->len++] = val; }}").unwrap();
2483        writeln!(output, "__attribute__((unused)) static {elem} seq_{elem}_get({sq} *s, int64_t idx) {{ return s->data[logos_idx0(idx, s->len)]; }}").unwrap();
2484        writeln!(output, "__attribute__((unused)) static void seq_{elem}_set({sq} *s, int64_t idx, {elem} val) {{ s->data[logos_idx0(idx, s->len)] = val; }}").unwrap();
2485        writeln!(output, "__attribute__((unused)) static int64_t seq_{elem}_len({sq} *s) {{ return (int64_t)s->len; }}").unwrap();
2486        writeln!(output, "__attribute__((unused)) static char *seq_{elem}_to_string({sq} *s) {{ char *out = lc_gc_strdup(\"[\"); for (size_t i = 0; i < s->len; i++) {{ if (i > 0) {{ char *c1 = str_concat(out, \", \"); lc_gc_free(out); out = c1; }} char *__e = {to_str}; char *c2 = str_concat(out, __e); lc_gc_free(out); lc_gc_free(__e); out = c2; }} char *cf = str_concat(out, \"]\"); lc_gc_free(out); return cf; }}").unwrap();
2487        writeln!(output, "__attribute__((unused)) static void show_seq_{elem}({sq} *s) {{ char *t = seq_{elem}_to_string(s); printf(\"%s\\n\", t); lc_gc_free(t); }}").unwrap();
2488    }
2489
2490    // Value-type `Map` families — `Map of Text to Money/Quantity/…` → `Map_str_LMoney` etc., an
2491    // open-addressing string-keyed hash map whose VALUE is a value-type struct (mirrors `Map_str_i64`,
2492    // reusing the runtime's `_map_hash_str`). Always emitted, `__attribute__((unused))`. `get` on a
2493    // missing key returns a zeroed value (correct programs never hit it).
2494    for (elem, vstr) in [
2495        ("LMoney", "money_to_string(m->vals[si])"),
2496        ("LQuant", "quant_to_string(m->vals[si])"),
2497        ("LMod", "mod_to_string(m->vals[si])"),
2498        ("LUuid", "uuid_to_string(m->vals[si])"),
2499        ("LComplex", "cplx_to_string(m->vals[si])"),
2500        ("LDec", "ldec_to_string(&m->vals[si])"),
2501    ] {
2502        let mp = format!("Map_str_{elem}");
2503        writeln!(output, "typedef struct {{ char **keys; {elem} *vals; uint8_t *state; size_t cap; size_t len; size_t *order; size_t ord_len; }} {mp};").unwrap();
2504        writeln!(output, "__attribute__((unused)) static {mp} map_str_{elem}_new(void) {{ size_t cap = 16; {mp} m = {{(char **)lc_gc_calloc(cap, sizeof(char *)), ({elem} *)lc_gc_calloc(cap, sizeof({elem})), (uint8_t *)lc_gc_calloc(cap, 1), cap, 0, (size_t *)lc_gc_calloc(cap, sizeof(size_t)), 0}}; return m; }}").unwrap();
2505        writeln!(output, "__attribute__((unused)) static void _map_str_{elem}_resize({mp} *m) {{ char **ok = m->keys; {elem} *ov = m->vals; uint8_t *os = m->state; size_t *oo = m->order; size_t ool = m->ord_len; size_t nc = m->cap * 2; m->keys = (char **)lc_gc_calloc(nc, sizeof(char *)); m->vals = ({elem} *)lc_gc_calloc(nc, sizeof({elem})); m->state = (uint8_t *)lc_gc_calloc(nc, 1); m->order = (size_t *)lc_gc_calloc(nc, sizeof(size_t)); m->cap = nc; m->len = 0; m->ord_len = 0; for (size_t oi = 0; oi < ool; oi++) {{ size_t si = oo[oi]; if (!os[si]) continue; size_t idx = _map_hash_str(ok[si], nc); while (m->state[idx]) idx = (idx + 1) & (nc - 1); m->keys[idx] = ok[si]; m->vals[idx] = ov[si]; m->state[idx] = 1; m->len++; m->order[m->ord_len++] = idx; }} lc_gc_free(ok); lc_gc_free(ov); lc_gc_free(os); lc_gc_free(oo); }}").unwrap();
2506        writeln!(output, "__attribute__((unused)) static void map_str_{elem}_set({mp} *m, const char *key, {elem} val) {{ if (m->ord_len * 4 >= m->cap * 3) _map_str_{elem}_resize(m); size_t idx = _map_hash_str(key, m->cap); while (m->state[idx]) {{ if (strcmp(m->keys[idx], key) == 0) {{ m->vals[idx] = val; return; }} idx = (idx + 1) & (m->cap - 1); }} m->keys[idx] = lc_gc_strdup(key); m->vals[idx] = val; m->state[idx] = 1; m->len++; m->order[m->ord_len++] = idx; }}").unwrap();
2507        writeln!(output, "__attribute__((unused)) static {elem} map_str_{elem}_get({mp} *m, const char *key) {{ size_t idx = _map_hash_str(key, m->cap); while (m->state[idx]) {{ if (strcmp(m->keys[idx], key) == 0) return m->vals[idx]; idx = (idx + 1) & (m->cap - 1); }} {elem} z; memset(&z, 0, sizeof({elem})); return z; }}").unwrap();
2508        writeln!(output, "__attribute__((unused)) static bool map_str_{elem}_contains({mp} *m, const char *key) {{ size_t idx = _map_hash_str(key, m->cap); while (m->state[idx]) {{ if (strcmp(m->keys[idx], key) == 0) return true; idx = (idx + 1) & (m->cap - 1); }} return false; }}").unwrap();
2509        writeln!(output, "__attribute__((unused)) static void map_str_{elem}_remove({mp} *t, const char *key) {{ size_t mask = t->cap - 1, i = _map_hash_str(key, t->cap); while (t->state[i] && strcmp(t->keys[i], key) != 0) i = (i + 1) & mask; if (!t->state[i]) return; _logos_order_drop(t->order, &t->ord_len, i); t->len--; for (size_t j = (i + 1) & mask; t->state[j]; j = (j + 1) & mask) {{ if (_logos_slot_backs(_map_hash_str(t->keys[j], t->cap), i, j, mask)) {{ t->keys[i] = t->keys[j]; t->vals[i] = t->vals[j]; _logos_order_move(t->order, t->ord_len, j, i); i = j; }} }} t->state[i] = 0; }}").unwrap();
2510        writeln!(output, "__attribute__((unused)) static int64_t map_str_{elem}_len({mp} *m) {{ return (int64_t)m->len; }}").unwrap();
2511        writeln!(output, "__attribute__((unused)) static char *map_str_{elem}_to_string({mp} *m) {{ char *out = lc_gc_strdup(\"{{\"); int first = 1; for (size_t oi = 0; oi < m->ord_len; oi++) {{ size_t si = m->order[oi]; if (!m->state[si]) continue; char *__v = {vstr}; char *e = logos_dyn_sprintf(\"%s%s: %s\", first ? \"\" : \", \", m->keys[si], __v); lc_gc_free(__v); char *nw = str_concat(out, e); lc_gc_free(out); lc_gc_free(e); out = nw; first = 0; }} char *nw = str_concat(out, \"}}\"); lc_gc_free(out); return nw; }}").unwrap();
2512        writeln!(output, "__attribute__((unused)) static void show_map_str_{elem}({mp} *m) {{ char *t = map_str_{elem}_to_string(m); printf(\"%s\\n\", t); lc_gc_free(t); }}").unwrap();
2513    }
2514
2515    // Maps whose value no fixed family holds — `Map of Text to Seq of Int` → the generic `Map_str_Seq_i64`
2516    // family, `Map of Int to Hyperreal` → `Map_i64_LTower`. Emitted HERE (before struct defs) so a struct may
2517    // hold such a map; the value's type is already in scope (scalar seqs live in `C_RUNTIME`, value-type seqs
2518    // just above, `LTower` with the extension's runtime). Collected from signatures AND
2519    // statement expressions (`is_c_map_value` deliberately excludes struct/nested-seq values, whose Seq
2520    // families are emitted later).
2521    {
2522        let mut mv_seen = std::collections::HashSet::new();
2523        let mut map_values: Vec<CType> = Vec::new();
2524        for stmt in stmts {
2525            if let Stmt::FunctionDef {
2526                params,
2527                return_type,
2528                ..
2529            } = stmt
2530            {
2531                if let Some(rt) = return_type {
2532                    collect_mapvalue_from_ctype(
2533                        &resolve_type_expr_with_registry(rt, interner, Some(_registry)),
2534                        &mut mv_seen,
2535                        &mut map_values,
2536                        interner,
2537                    );
2538                }
2539                for (_, pt) in params.iter() {
2540                    collect_mapvalue_from_ctype(
2541                        &resolve_type_expr_with_registry(pt, interner, Some(_registry)),
2542                        &mut mv_seen,
2543                        &mut map_values,
2544                        interner,
2545                    );
2546                }
2547            }
2548        }
2549        {
2550            let mut mv_ctx = CContext::new(interner, _registry);
2551            mv_ctx.exact = ctx.exact.clone();
2552            mv_ctx.tower = ctx.tower.clone();
2553            mv_ctx.absence = ctx.absence.clone();
2554            collect_stmt_mapvalue_types(
2555                stmts,
2556                &mut mv_ctx,
2557                &mut mv_seen,
2558                &mut map_values,
2559                interner,
2560            );
2561        }
2562        for map in &map_values {
2563            emit_generic_map_family(&mut output, map, interner, true);
2564        }
2565    }
2566
2567    // Every aggregate: the program's records and enums, plus each tuple and nested sequence its
2568    // signatures, statements and record fields use (deduped, nested-first), emitted as one ordered
2569    // unit (see `codegen_c_aggregates`).
2570    {
2571        let (mut tup_seen, mut tuples) = (
2572            std::collections::HashSet::new(),
2573            Vec::<(String, Vec<CType>)>::new(),
2574        );
2575        let (mut ss_seen, mut seqseqs) = (std::collections::HashSet::new(), Vec::<CType>::new());
2576        let mut collect = |cty: &CType| {
2577            collect_tuple_types(cty, &mut tup_seen, &mut tuples, interner);
2578            collect_seqseq_types(cty, &mut ss_seen, &mut seqseqs, interner);
2579        };
2580        let defined = crate::analysis::callgraph::program_type_defs(stmts, _registry);
2581        for (_, def) in _registry
2582            .iter_types()
2583            .filter(|(sym, _)| defined.contains(*sym))
2584        {
2585            let field_types: Vec<&crate::analysis::FieldType> = match def {
2586                crate::analysis::TypeDef::Struct { fields, .. } => {
2587                    fields.iter().map(|f| &f.ty).collect()
2588                }
2589                crate::analysis::TypeDef::Enum { variants, .. } => variants
2590                    .iter()
2591                    .flat_map(|v| v.fields.iter().map(|f| &f.ty))
2592                    .collect(),
2593                _ => Vec::new(),
2594            };
2595            for ft in field_types {
2596                collect(&field_type_to_ctype(ft, interner, _registry));
2597            }
2598        }
2599        for stmt in stmts {
2600            if let Stmt::FunctionDef {
2601                name,
2602                params,
2603                return_type,
2604                ..
2605            } = stmt
2606            {
2607                if let Some(rt) = return_type {
2608                    collect(&ctx.exact.widened_return(
2609                        *name,
2610                        resolve_type_expr_with_registry(rt, interner, Some(_registry)),
2611                    ));
2612                }
2613                for (_, pt) in params.iter() {
2614                    collect(&resolve_type_expr_with_registry(
2615                        pt,
2616                        interner,
2617                        Some(_registry),
2618                    ));
2619                }
2620            }
2621        }
2622        // Also collect from statement expressions (bare `Show (1, 2)`, `Let g be [[1,2]]`, …).
2623        let mut stmt_ctx = CContext::new(interner, _registry);
2624        stmt_ctx.exact = ctx.exact.clone();
2625        stmt_ctx.tower = ctx.tower.clone();
2626        stmt_ctx.absence = ctx.absence.clone();
2627        collect_stmt_tuple_types(stmts, &mut stmt_ctx, &mut tup_seen, &mut tuples, interner);
2628        let mut stmt_ctx = CContext::new(interner, _registry);
2629        stmt_ctx.exact = ctx.exact.clone();
2630        stmt_ctx.tower = ctx.tower.clone();
2631        stmt_ctx.absence = ctx.absence.clone();
2632        collect_stmt_seqseq_types(stmts, &mut stmt_ctx, &mut ss_seen, &mut seqseqs, interner);
2633        codegen_c_aggregates(
2634            _registry,
2635            interner,
2636            &defined,
2637            &ctx.display_names,
2638            &ctx.field_facts(),
2639            &tuples,
2640            &seqseqs,
2641            &mut output,
2642        );
2643    }
2644
2645    // First pass: register every function's C signature (for forward references): its declared types, with
2646    // each `Int` return and parameter the exact-slot analysis settled on `LInt`, and an exact HOF's integers.
2647    for stmt in stmts {
2648        if let Stmt::FunctionDef {
2649            name,
2650            params,
2651            return_type,
2652            is_native,
2653            ..
2654        } = stmt
2655        {
2656            if *is_native {
2657                let fname = interner.resolve(*name);
2658                let ret_type = match fname {
2659                    "args" => CType::SeqStr,
2660                    "parseInt" => CType::Int64,
2661                    "parseFloat" => CType::Float64,
2662                    _ => {
2663                        if let Some(rt) = return_type {
2664                            resolve_type_expr_with_registry(rt, interner, Some(_registry))
2665                        } else {
2666                            CType::Void
2667                        }
2668                    }
2669                };
2670                ctx.funcs.insert(*name, ret_type);
2671                ctx.native_funcs.insert(*name);
2672                let param_types = params
2673                    .iter()
2674                    .map(|(_, pt)| resolve_type_expr_with_registry(pt, interner, Some(_registry)))
2675                    .collect();
2676                ctx.fn_params.insert(*name, param_types);
2677                ctx.fn_inout.insert(
2678                    *name,
2679                    params.iter().map(|(_, pt)| types::is_inout(pt)).collect(),
2680                );
2681            } else {
2682                let mut ret_type = if let Some(rt) = return_type {
2683                    ctx.exact.widened_return(
2684                        *name,
2685                        resolve_type_expr_with_registry(rt, interner, Some(_registry)),
2686                    )
2687                } else {
2688                    CType::Void
2689                };
2690                if ret_type == CType::Int64 && ctx.exact_hofs.contains(name) {
2691                    ret_type = CType::BigInt;
2692                }
2693                if tower::returns(&ctx, *name) {
2694                    ret_type = CType::Tower;
2695                }
2696                let ret_type = absent::returned(*name, ret_type, &ctx);
2697                ctx.funcs.insert(*name, ret_type);
2698                let param_types = params
2699                    .iter()
2700                    .map(|(pn, pt)| param_ctype(&ctx, *name, *pn, pt))
2701                    .collect();
2702                ctx.fn_params.insert(*name, param_types);
2703                ctx.fn_inout.insert(
2704                    *name,
2705                    params.iter().map(|(_, pt)| types::is_inout(pt)).collect(),
2706                );
2707            }
2708        }
2709    }
2710    ctx.plain_texts = lent_texts(stmts, &ctx);
2711    // A function that declares no return type answers what its `Return`s hand back (a closure lifted to a
2712    // function, a `## To` written without `->`), settled once every function a `Return` may call is.
2713    for _ in 0..=stmts.len() {
2714        let mut settled = true;
2715        for stmt in stmts {
2716            if let Stmt::FunctionDef {
2717                name,
2718                params,
2719                body,
2720                return_type: None,
2721                is_native: false,
2722                ..
2723            } = stmt
2724            {
2725                let answered = absent::returned(*name, undeclared_return(*name, params, body, &ctx), &ctx);
2726                if ctx.funcs.get(name) != Some(&answered) {
2727                    ctx.funcs.insert(*name, answered);
2728                    settled = false;
2729                }
2730            }
2731        }
2732        if settled {
2733            break;
2734        }
2735    }
2736
2737    // A labeled seam between the fixed C runtime/type prelude (above) and the
2738    // program's own code (below). The CUDA AOT tier lifts everything after this
2739    // marker onto the device; nothing before it (the glibc-heavy dynamic runtime)
2740    // is device code. Inert for every other consumer — it is a C comment.
2741    output.push_str(USER_CODE_SENTINEL);
2742    output.push('\n');
2743
2744    // Forward declarations
2745    for stmt in stmts {
2746        if let Stmt::FunctionDef {
2747            name,
2748            params,
2749            return_type,
2750            is_native,
2751            ..
2752        } = stmt
2753        {
2754            if *is_native || steps.as_ref().is_some_and(|s| s.waits.contains(name)) {
2755                continue;
2756            }
2757            let func_name = escape_c_ident(ctx.interner.resolve(*name));
2758            // Use the first-pass return type (which already widened `Int`→`LInt` for a BigInt-returning
2759            // function) so the forward declaration matches the definition.
2760            let ret_type = ctx.funcs.get(name).cloned().unwrap_or_else(|| {
2761                if let Some(rt) = return_type {
2762                    resolve_type_expr_with_registry(rt, interner, Some(_registry))
2763                } else {
2764                    CType::Void
2765                }
2766            });
2767            // The first pass's parameter types, so prototype and definition agree.
2768            let param_strs: Vec<String> = params
2769                .iter()
2770                .map(|(pname, ptype)| {
2771                    let ty = param_ctype(&ctx, *name, *pname, ptype);
2772                    if types::is_inout(ptype) {
2773                        types::c_inout_param_decl(&ty, &ctx.resolve(*pname), interner)
2774                    } else {
2775                        c_param_decl(&ty, &ctx.resolve(*pname), interner)
2776                    }
2777                })
2778                .collect();
2779            writeln!(
2780                output,
2781                "{} {}({});",
2782                c_type_str_resolved(&ret_type, interner),
2783                func_name,
2784                param_strs.join(", ")
2785            )
2786            .unwrap();
2787        }
2788    }
2789    // The spawned functions, each with the arity it is launched at, in a stable (name-sorted) order. Their
2790    // task-entry wrappers are declared here, beside the functions, so a body that launches a task can name
2791    // a wrapper defined after it. Every entry takes its task's arguments as one array of scalars.
2792    let spawned: Vec<(Symbol, usize)> = if uses_concurrency && steps.is_none() {
2793        let mut arities: HashMap<Symbol, usize> = HashMap::new();
2794        collect_spawned_arities(stmts, &mut arities);
2795        let mut spawned: Vec<(Symbol, usize)> = arities.into_iter().collect();
2796        spawned.sort_by(|a, b| interner.resolve(a.0).cmp(interner.resolve(b.0)));
2797        spawned
2798    } else {
2799        Vec::new()
2800    };
2801    for &(func, nargs) in &spawned {
2802        // The callee's own parameter types; an unresolved (parse-only) name takes Ints, so its entry links.
2803        let params = stmts
2804            .iter()
2805            .find_map(|stmt| match stmt {
2806                Stmt::FunctionDef {
2807                    name,
2808                    params,
2809                    is_native: false,
2810                    ..
2811                } if *name == func => Some(
2812                    params
2813                        .iter()
2814                        .map(|(pn, pt)| param_ctype(&ctx, func, *pn, pt))
2815                        .collect(),
2816                ),
2817                _ => None,
2818            })
2819            .unwrap_or_else(|| vec![CType::Int64; nargs]);
2820        ctx.task_params.insert(func, params);
2821        writeln!(
2822            output,
2823            "static long long logos_taskentry_{}(const long long *__targs);",
2824            escape_c_ident(interner.resolve(func))
2825        )
2826        .unwrap();
2827    }
2828    output.push('\n');
2829
2830    // Function definitions + main go into a separate buffer so the lifted lambda functions
2831    // (accumulated in `ctx.lifted` as a SIDE EFFECT of codegen) can be emitted BEFORE the code
2832    // that references them. Lambda bodies may call user functions — the forward declarations above
2833    // cover those — and `main` references the lambda names, so this ordering satisfies both.
2834    // The program's bindings a function reaches become file-scope statics. Main is lowered first then, so each
2835    // static's C type is the one its root `Let` gives it, and every function body is lowered knowing it.
2836    let statics = program_statics(stmts, interner);
2837    for stmt in stmts {
2838        if let Stmt::FunctionDef { body, .. } = stmt {
2839            ctx.changed_statics.extend(
2840                values::mutated_roots(body, &ctx.fn_inout)
2841                    .into_iter()
2842                    .filter(|g| statics.names.contains(g)),
2843            );
2844        }
2845    }
2846    // `## Main` changes a static in place as a function does: a body that copies the static copies it then too.
2847    let main: Vec<Stmt> = stmts
2848        .iter()
2849        .filter(|s| !matches!(s, Stmt::FunctionDef { .. }))
2850        .cloned()
2851        .collect();
2852    ctx.changed_statics.extend(
2853        values::mutated_roots(&main, &ctx.fn_inout)
2854            .into_iter()
2855            .filter(|g| statics.names.contains(g)),
2856    );
2857    // The parameters each plain function changes in place, which its callers copy where they read the argument
2858    // again. A step and a closure copy what they change on entry instead.
2859    let caller_copied: Vec<(Symbol, Vec<Symbol>, &[Stmt])> = stmts
2860        .iter()
2861        .filter_map(|s| match s {
2862            Stmt::FunctionDef {
2863                name,
2864                params,
2865                body,
2866                is_native: false,
2867                ..
2868            } if !steps.as_ref().is_some_and(|st| st.waits.contains(name)) => {
2869                Some((*name, params.iter().map(|(p, _)| *p).collect(), *body))
2870            }
2871            _ => None,
2872        })
2873        .collect();
2874    let call_shapes: values::CallShapes = stmts
2875        .iter()
2876        .filter_map(|s| match s {
2877            Stmt::FunctionDef {
2878                name,
2879                params,
2880                return_type: Some(rt),
2881                ..
2882            } => {
2883                let holds = |t: &TypeExpr| {
2884                    values::holds_buffer(
2885                        &resolve_type_expr_with_registry(t, interner, Some(_registry)),
2886                        _registry,
2887                        interner,
2888                    )
2889                };
2890                let result_holds = holds(rt);
2891                Some((
2892                    *name,
2893                    params
2894                        .iter()
2895                        .map(|(_, pt)| result_holds && holds(pt))
2896                        .collect(),
2897                ))
2898            }
2899            _ => None,
2900        })
2901        .collect();
2902    ctx.call_shapes = std::rc::Rc::new(sharing::narrowed_call_shapes(
2903        &caller_copied,
2904        &call_shapes,
2905        &ctx.fn_inout,
2906    ));
2907    ctx.mutating = std::rc::Rc::new(sharing::mutating_params(
2908        &caller_copied,
2909        &ctx.changed_statics,
2910        &ctx.call_shapes,
2911        &ctx.fn_inout,
2912    ));
2913    let fixed_stack_plan = c_fixed_stack_plan(stmts, &ctx);
2914    let fixed_for = |scope: Option<Symbol>| {
2915        fixed_stack_plan
2916            .iter()
2917            .filter_map(|(&(owner, symbol), &capacity)| {
2918                (owner == scope).then_some((symbol, capacity))
2919            })
2920            .collect::<HashMap<_, _>>()
2921    };
2922    ctx.text_bytes_candidates = c_text_bytes_view_plan(stmts, interner);
2923    ctx.fixed_stack_seqs = fixed_for(None);
2924    for refusal in &statics.refusals {
2925        output.push_str(&format!(
2926            "\n#error \"the C backend does not lower {}\"\n",
2927            refusal.replace('"', "'")
2928        ));
2929    }
2930    let early_main = if statics.names.is_empty() {
2931        None
2932    } else {
2933        ctx.program_statics = statics.names.iter().copied().collect();
2934        let vars_before_main = ctx.vars.clone();
2935        if let Some(s) = &steps {
2936            register_step_params(stmts, s, &mut ctx);
2937        }
2938        let main_code = emit_main(stmts, &mut ctx, uses_concurrency, tier);
2939        ctx.vars = vars_before_main;
2940        for g in &statics.names {
2941            if let Some(ty) = ctx.static_types.get(g).cloned() {
2942                writeln!(
2943                    output,
2944                    "static {};",
2945                    c_param_decl(&ty, &ctx.resolve(*g), interner)
2946                )
2947                .unwrap();
2948                ctx.vars.insert(*g, ty);
2949            }
2950        }
2951        output.push('\n');
2952        Some(main_code)
2953    };
2954
2955    if let Some(s) = &steps {
2956        register_step_params(stmts, s, &mut ctx);
2957    }
2958    let mut body = String::new();
2959    for stmt in stmts {
2960        if let Stmt::FunctionDef {
2961            name,
2962            is_native: false,
2963            ..
2964        } = stmt
2965        {
2966            if !steps.as_ref().is_some_and(|s| s.waits.contains(name)) {
2967                ctx.fixed_stack_seqs = fixed_for(Some(*name));
2968                codegen_function(stmt, &mut ctx, &mut body);
2969            }
2970        }
2971    }
2972    // The step functions, in a stable (name-sorted) order: every frame is typed before any step names it.
2973    let mut frames = String::new();
2974    let mut step_bodies = String::new();
2975    let mut step_names: Vec<String> = Vec::new();
2976    if let Some(s) = &steps {
2977        let mut stepped_defs: Vec<&Stmt> = stmts
2978            .iter()
2979            .filter(|st| matches!(st, Stmt::FunctionDef { name, is_native: false, .. } if s.steps().any(|f| f == name)))
2980            .collect();
2981        stepped_defs.sort_by_key(|st| match st {
2982            Stmt::FunctionDef { name, .. } => interner.resolve(*name).to_string(),
2983            _ => String::new(),
2984        });
2985        for def in stepped_defs {
2986            if let Stmt::FunctionDef { name, .. } = def {
2987                ctx.fixed_stack_seqs = fixed_for(Some(*name));
2988                step_names.push(escape_c_ident(interner.resolve(*name)));
2989            }
2990            let (frame, step) = codegen_step_function(def, &mut ctx);
2991            frames.push_str(&frame);
2992            step_bodies.push_str(&step);
2993        }
2994    }
2995
2996    // Task-entry wrappers — one `long long logos_taskentry_<fn>(const long long *__targs)` per spawned function,
2997    // so the scheduler calls every task body the same way: by pointer, with the task's arguments as one
2998    // array of scalars. Each unpacks its arguments to the callee's real C parameter types (see
2999    // `emit::task_arg_unpack`); a task answers `nothing`, so the callee's own result is dropped. Emitted
3000    // ONLY under concurrency, after the definitions they reference.
3001    for (func, _) in &spawned {
3002        let fname = escape_c_ident(interner.resolve(*func));
3003        let params = ctx.task_params.get(func).cloned().unwrap_or_default();
3004        let call_args: Vec<String> = params
3005            .iter()
3006            .enumerate()
3007            .map(|(i, ty)| emit::task_arg_unpack(ty, &format!("__targs[{i}]"), interner))
3008            .collect();
3009        writeln!(
3010            body,
3011            "static long long logos_taskentry_{}(const long long *__targs) {{",
3012            fname
3013        )
3014        .unwrap();
3015        if params.is_empty() {
3016            writeln!(body, "    (void)__targs;").unwrap();
3017        }
3018        writeln!(body, "    {}({});", fname, call_args.join(", ")).unwrap();
3019        writeln!(body, "    return 0;").unwrap();
3020        writeln!(body, "}}").unwrap();
3021    }
3022
3023    let main_code = match early_main {
3024        Some(main_code) => main_code,
3025        None => {
3026            ctx.fixed_stack_seqs = fixed_for(None);
3027            emit_main(stmts, &mut ctx, uses_concurrency, tier)
3028        }
3029    };
3030
3031    let mut lifted_once = std::collections::HashSet::new();
3032    for lam in ctx.lifted.borrow().iter() {
3033        if lifted_once.insert(lam.clone()) {
3034            output.push_str(lam);
3035        }
3036    }
3037    output.push('\n');
3038    if steps.is_some() {
3039        output.push_str(&frames);
3040        output.push_str(&main_code.frame);
3041        for name in step_names
3042            .iter()
3043            .map(String::as_str)
3044            .chain(std::iter::once(MAIN_STEP))
3045        {
3046            writeln!(output, "static int logos_step_{name}(void *fp);").unwrap();
3047        }
3048        output.push('\n');
3049    }
3050    output.push_str(&body);
3051    output.push_str(&step_bodies);
3052    output.push_str(&main_code.step);
3053    output.push_str(&main_code.entry);
3054    output
3055}
3056
3057/// The C type a function declared without a return type answers: its first `Return`'s value, typed with its
3058/// parameters and the bindings before it in scope; `Void` when no `Return` carries a value.
3059fn undeclared_return(
3060    function: Symbol,
3061    params: &[(Symbol, &TypeExpr)],
3062    body: &[Stmt],
3063    ctx: &CContext,
3064) -> CType {
3065    fn first_answer<'a>(body: &'a [Stmt<'a>], scope: &mut CContext<'a>) -> Option<CType> {
3066        for s in body {
3067            match s {
3068                Stmt::Let { var, value, ty, .. } => {
3069                    let bound = match ty {
3070                        Some(t) => {
3071                            resolve_type_expr_with_registry(t, scope.interner, Some(scope.registry))
3072                        }
3073                        None => crate::codegen_c::types::infer_expr_type(value, scope),
3074                    };
3075                    scope.vars.insert(*var, bound);
3076                }
3077                Stmt::Return { value: Some(v) } => {
3078                    return Some(crate::codegen_c::types::infer_expr_type(v, scope))
3079                }
3080                Stmt::If {
3081                    then_block,
3082                    else_block,
3083                    ..
3084                } => {
3085                    if let Some(t) = first_answer(then_block, scope) {
3086                        return Some(t);
3087                    }
3088                    if let Some(t) = else_block.and_then(|b| first_answer(b, scope)) {
3089                        return Some(t);
3090                    }
3091                }
3092                Stmt::While { body, .. }
3093                | Stmt::Repeat { body, .. }
3094                | Stmt::Zone { body, .. }
3095                | Stmt::Splice { body }
3096                | Stmt::Reversibly { body }
3097                | Stmt::During { body, .. } => {
3098                    if let Some(t) = first_answer(body, scope) {
3099                        return Some(t);
3100                    }
3101                }
3102                Stmt::Inspect { arms, .. } => {
3103                    for arm in arms {
3104                        if let Some(t) = first_answer(arm.body, scope) {
3105                            return Some(t);
3106                        }
3107                    }
3108                }
3109                _ => {}
3110            }
3111        }
3112        None
3113    }
3114    let mut scope = CContext::new(ctx.interner, ctx.registry);
3115    scope.funcs = ctx.funcs.clone();
3116    scope.native_funcs = ctx.native_funcs.clone();
3117    scope.fn_params = ctx.fn_params.clone();
3118    scope.exact = ctx.exact.clone();
3119    scope.exact_hofs = ctx.exact_hofs.clone();
3120    scope.absence = ctx.absence.clone();
3121    for (p, t) in params {
3122        scope.vars.insert(*p, param_ctype(ctx, function, *p, t));
3123    }
3124    first_answer(body, &mut scope).unwrap_or(CType::Void)
3125}
3126
3127/// Record each step function's parameter types, by which a launch or a push packs its arguments.
3128fn register_step_params(stmts: &[Stmt], steps: &stepped::Stepped, ctx: &mut CContext) {
3129    for stmt in stmts {
3130        if let Stmt::FunctionDef {
3131            name,
3132            params,
3133            is_native: false,
3134            ..
3135        } = stmt
3136        {
3137            if steps.steps().any(|f| f == name) {
3138                let types = params
3139                    .iter()
3140                    .map(|(pn, pt)| param_ctype(ctx, *name, *pn, pt))
3141                    .collect();
3142                ctx.task_params.insert(*name, types);
3143            }
3144        }
3145    }
3146}
3147
3148/// A function that waits or is launched, as its frame and step (see `stepped`), with the per-function
3149/// pre-passes an ordinary function's body receives.
3150fn codegen_step_function(stmt: &Stmt, ctx: &mut CContext) -> (String, String) {
3151    let Stmt::FunctionDef {
3152        name,
3153        params,
3154        body,
3155        return_type,
3156        ..
3157    } = stmt
3158    else {
3159        return (String::new(), String::new());
3160    };
3161    let param_types: Vec<(Symbol, CType)> = params
3162        .iter()
3163        .map(|(pn, pt)| (*pn, param_ctype(ctx, *name, *pn, pt)))
3164        .collect();
3165    let bigint_vars = body_exact_locals(ctx, *name, body, &param_types);
3166    let returns = ctx.funcs.get(name).cloned().unwrap_or_else(|| {
3167        return_type.map_or(CType::Void, |rt| {
3168            resolve_type_expr_with_registry(rt, ctx.interner, Some(ctx.registry))
3169        })
3170    });
3171    let saved_big = std::mem::replace(&mut ctx.bigint_vars, bigint_vars);
3172    let saved_vars = ctx.vars.clone();
3173    for (pn, pt) in &param_types {
3174        ctx.vars.insert(*pn, pt.clone());
3175    }
3176    let numbers = numbers::number_locals(body, ctx);
3177    ctx.vars = saved_vars;
3178    let saved_numbers = std::mem::replace(&mut ctx.number_locals, numbers);
3179    let saved_returns = std::mem::replace(&mut ctx.current_fn_returns, returns.clone());
3180    let saved_nonnegative = std::mem::replace(
3181        &mut ctx.nonnegative_vars,
3182        crate::codegen::expr::collect_always_nonneg(body),
3183    );
3184    let cname = escape_c_ident(ctx.interner.resolve(*name));
3185    let out = ctx.in_body(false, |ctx| {
3186        stepped::emit_step(&cname, &param_types, returns, body, ctx)
3187    });
3188    ctx.bigint_vars = saved_big;
3189    ctx.number_locals = saved_numbers;
3190    ctx.current_fn_returns = saved_returns;
3191    ctx.nonnegative_vars = saved_nonnegative;
3192    out
3193}