Skip to main content

logicaffeine_compile/
compile.rs

1//! LOGOS Compilation Pipeline
2//!
3//! This module provides the end-to-end compilation pipeline that transforms
4//! LOGOS source code into executable Rust programs.
5//!
6//! # Pipeline Overview
7//!
8//! ```text
9//! LOGOS Source (.md)
10//!       │
11//!       ▼
12//! ┌───────────────────┐
13//! │  1. Lexer         │ Tokenize source
14//! └─────────┬─────────┘
15//!           ▼
16//! ┌───────────────────┐
17//! │  2. Discovery     │ Type & policy definitions
18//! └─────────┬─────────┘
19//!           ▼
20//! ┌───────────────────┐
21//! │  3. Parser        │ Build AST
22//! └─────────┬─────────┘
23//!           ▼
24//! ┌───────────────────┐
25//! │  4. Analysis      │ Escape, ownership, verification
26//! └─────────┬─────────┘
27//!           ▼
28//! ┌───────────────────┐
29//! │  5. CodeGen       │ Emit Rust source
30//! └─────────┬─────────┘
31//!           ▼
32//!     Rust Source
33//! ```
34//!
35//! # Compilation Functions
36//!
37//! | Function | Analysis | Use Case |
38//! |----------|----------|----------|
39//! | [`compile_to_rust`] | Escape only | Basic compilation |
40//! | [`compile_to_rust_checked`] | Escape + Ownership | Use with `--check` flag |
41//! | `compile_to_rust_verified` | All + Z3 | Formal verification (requires `verification` feature) |
42//! | [`compile_project`] | Multi-file | Projects with imports |
43//! | [`compile_and_run`] | Full + Execute | Development workflow |
44//!
45//! Escape and ownership analysis judge the program as written — the freshly-parsed statements,
46//! before observation elision, division resolution or the optimizer rewrite them — so a verdict
47//! never depends on what the optimizer folded, and matches the editor's.
48//!
49//! # Examples
50//!
51//! ## Basic Compilation
52//!
53//! ```
54//! # use logicaffeine_compile::compile::compile_to_rust;
55//! # use logicaffeine_compile::ParseError;
56//! # fn main() -> Result<(), ParseError> {
57//! let source = "## Main\nLet x be 5.\nShow x.";
58//! let rust_code = compile_to_rust(source)?;
59//! // rust_code contains:
60//! // fn main() {
61//! //     let x = 5;
62//! //     println!("{}", x);
63//! // }
64//! # Ok(())
65//! # }
66//! ```
67//!
68//! ## With Ownership Checking
69//!
70//! ```
71//! # use logicaffeine_compile::compile::compile_to_rust_checked;
72//! let source = "## Main\nLet x be 5.\nGive x to y.\nShow x.";
73//! let result = compile_to_rust_checked(source);
74//! // Returns Err: "x has already been given away"
75//! ```
76
77use std::collections::{HashMap, HashSet};
78use std::fs;
79use std::io::Write;
80use std::path::Path;
81use std::process::Command;
82
83// Runtime crates paths (relative to workspace root)
84const CRATES_DATA_PATH: &str = "crates/logicaffeine_data";
85const CRATES_SYSTEM_PATH: &str = "crates/logicaffeine_system";
86
87use std::fmt::Write as FmtWrite;
88
89use crate::analysis::{DiscoveryPass, EscapeChecker, OwnershipChecker, PolicyRegistry};
90use crate::arena::Arena;
91use crate::arena_ctx::AstContext;
92use crate::ast::stmt::{
93    BinaryOpKind, ClosureBody, Literal, Pattern, ReadSource, SelectBranch, StringPart,
94};
95use crate::ast::{Expr, MatchArm, Stmt, TypeExpr};
96use crate::codegen::{
97    codegen_program, generate_c_header, generate_python_bindings, generate_typescript_bindings,
98};
99use crate::diagnostic::{parse_rustc_json, translate_diagnostics, LogosError};
100use crate::drs::WorldState;
101use crate::error::ParseError;
102use crate::intern::Interner;
103use crate::lexer::Lexer;
104use crate::parser::Parser;
105use crate::semantics::collections::with_reference_semantics;
106use crate::sourcemap::SourceMap;
107
108/// A declared external crate dependency from a `## Requires` block.
109#[derive(Debug, Clone)]
110pub struct CrateDependency {
111    pub name: String,
112    pub version: String,
113    pub features: Vec<String>,
114}
115
116/// Full compilation output including generated Rust code and extracted dependencies.
117#[derive(Debug)]
118pub struct CompileOutput {
119    pub rust_code: String,
120    pub dependencies: Vec<CrateDependency>,
121    /// Generated C header content (populated when C exports exist).
122    pub c_header: Option<String>,
123    /// Generated Python ctypes bindings (populated when C exports exist).
124    pub python_bindings: Option<String>,
125    /// Generated TypeScript type declarations (.d.ts content, populated when C exports exist).
126    pub typescript_types: Option<String>,
127    /// Generated TypeScript FFI bindings (.js content, populated when C exports exist).
128    pub typescript_bindings: Option<String>,
129}
130
131/// Interpret LOGOS source and return output as a string.
132///
133/// Runs the full pipeline (lex → discovery → parse → interpret) without
134/// generating Rust code. Useful for sub-second feedback during development.
135///
136/// # Arguments
137///
138/// * `source` - LOGOS source code as a string
139///
140/// # Returns
141///
142/// The collected output from `Show` statements, joined by newlines.
143///
144/// # Errors
145///
146/// Returns [`ParseError`] if parsing fails or the interpreter encounters
147/// a runtime error.
148pub fn interpret_program(source: &str) -> Result<String, ParseError> {
149    let result = crate::ui_bridge::interpret_for_ui_sync(source);
150    if let Some(err) = result.error {
151        Err(ParseError {
152            kind: crate::error::ParseErrorKind::Custom(err),
153            span: crate::token::Span::default(),
154        })
155    } else {
156        Ok(result.lines.join("\n"))
157    }
158}
159
160/// [`interpret_program`] for one of the compiler's own LOGOS programs — the partial evaluator, its
161/// dialects, the self-interpreter, a compiler a projection produced — inside the bootstrap scope
162/// ([`with_reference_semantics`]): those programs thread their state through `mutable` parameters and
163/// are written for the in-place writes of reference semantics. A user program never runs here.
164pub fn interpret_bootstrap(source: &str) -> Result<String, ParseError> {
165    with_reference_semantics(|| interpret_program(source))
166}
167
168/// Parse LOGOS source and execute it on the register bytecode VM, returning the
169/// captured output. Uses the SAME front-end as the tree-walker
170/// ([`crate::ui_bridge::with_parsed_program`]: lex → MWE → discovery → parse),
171/// so differential tests compare two engines on one program, never two
172/// programs. Returns `Err` for programs outside the VM's supported subset (the
173/// compiler reports `vm: unsupported …`).
174pub fn vm_run_source(source: &str) -> Result<String, String> {
175    crate::ui_bridge::with_parsed_program(source, |parsed, interner| match parsed {
176        Ok((stmts, types, policies)) => {
177            let (output, error) =
178                crate::vm::run_to_outcome(stmts, interner, Some(types), Some(&policies));
179            match error {
180                None => Ok(output),
181                Some(e) => Err(e),
182            }
183        }
184        Err(advice) => Err(advice),
185    })
186}
187
188/// What a program run produced: every output line emitted before completion or
189/// failure, plus the error if it failed. The differential contract is
190/// `vm_outcome(src) == tw_outcome(src)` — output AND error.
191#[derive(Debug, Clone, PartialEq, Eq)]
192pub struct RunOutcome {
193    pub output: String,
194    pub error: Option<String>,
195}
196
197/// The CANONICAL set of value kinds that must be FIRST-CLASS as a function parameter AND return value on
198/// EVERY execution tier — the single source of truth SHARED across crates so the coverage locks cannot
199/// drift apart. The tests crate's `param_return_tier_coverage_lock` asserts its PROBES name EXACTLY this
200/// set (executed on TW/VM/AOT-C/AOT-Rust, lowered on WASM), and this crate's
201/// `wasm_aot_lock::first_class_param_return_round_trips_on_wasm` asserts it has an EXECUTABLE WASM program
202/// for every kind here. Adding a kind here makes BOTH locks RED until each covers it — anti-drift by
203/// construction, compiler-enforced (both crates reference this one `const`). Keep alphabetically grouped
204/// scalars → sequences → collections → aggregates for readability; order is not significant (compared as
205/// a set).
206pub const FIRST_CLASS_VALUE_KINDS: &[&str] = &[
207    "int",
208    "real",
209    "bool",
210    "text",
211    "seq_int",
212    "seq_text",
213    "seq_seq",
214    "set_int",
215    "struct",
216    "tuple_anon",
217    "multi_return",
218    "record_named",
219    "destructure",
220    "seq_tuple",
221];
222
223/// Run `source` on the TREE-WALKER (the oracle), capturing partial output and
224/// the error, if any. This entry point always uses the tree-walker — the
225/// dispatching `interpret_for_ui_sync` now runs the VM for the sync path, and
226/// the differential suites need the oracle by itself.
227pub fn tw_outcome(source: &str) -> RunOutcome {
228    let result = tw_lines(source);
229    RunOutcome {
230        output: result.lines.join("\n"),
231        error: result.error,
232    }
233}
234
235/// [`tw_outcome`] with the shown lines kept apart. The exact bytes a run writes to standard output are
236/// every line followed by a newline, which is what a compiled binary writes; the joined `output` of a
237/// [`RunOutcome`] cannot tell no output from one empty line, so a byte-exact comparison starts here.
238pub fn tw_lines(source: &str) -> crate::interpreter::InterpreterResult {
239    tw_lines_with_args(source, &[])
240}
241
242/// [`tw_lines`] with the program argument vector for the `args()` system native (full argv; index 0 is the
243/// program name).
244pub fn tw_lines_with_args(
245    source: &str,
246    program_args: &[String],
247) -> crate::interpreter::InterpreterResult {
248    // Deterministic oracle: no relay transport, so `Connect` runs as a single-node local no-op (the
249    // networking analogue of the fixed clock). Only affects a `Connect` program; inert otherwise.
250    crate::concurrency::net_inbox::set_net_offline(true);
251    crate::ui_bridge::with_parsed_program(source, |parsed, interner| match parsed {
252        Ok((stmts, types, policies)) => {
253            let force_async = crate::interpreter::needs_async(stmts, interner);
254            crate::ui_bridge::run_treewalker(
255                stmts,
256                types,
257                policies,
258                interner,
259                force_async,
260                program_args,
261            )
262        }
263        Err(advice) => crate::interpreter::InterpreterResult {
264            lines: Vec::new(),
265            error: Some(advice),
266        },
267    })
268}
269
270/// Whether `stmt` merely DEFINES something — a component, a type, a route, a theorem — rather
271/// than doing anything when the program runs. The allowlist behind [`main_drives_a_page`]: an
272/// unlisted statement kind at the boundary means the gate declines rather than guesses, so a
273/// shape this function has not considered can only narrow the gate, never widen it onto ground it
274/// has not been checked against.
275///
276/// Everything BEFORE the split compiles and runs exactly as the straight-through path always has
277/// — an ordinary program prefix, whatever it does; only the TRAILING run has to be pure driving
278/// statements, since that is the part `page_host::drive_main` carries out itself instead of
279/// letting the compiler inline it into `main`. The split is the START of the longest such trailing
280/// run, so a real program's own imports and top-level setup (which `page_host`'s driving
281/// vocabulary was never meant to classify) never have to look like anything in particular.
282fn main_drives_a_page(stmts: &[Stmt], interner: &Interner) -> Option<usize> {
283    let is_drive = |s: &Stmt| {
284        matches!(
285            crate::page_host::classify(s, interner),
286            crate::page_host::Classified::Drive(_)
287        )
288    };
289    let mut split = stmts.len();
290    while split > 0 && is_drive(&stmts[split - 1]) {
291        split -= 1;
292    }
293    if split == stmts.len() {
294        // No trailing driving statement at all — provably inert for this program.
295        return None;
296    }
297    let mounts = stmts[split..].iter().any(|s| {
298        matches!(
299            crate::page_host::classify(s, interner),
300            crate::page_host::Classified::Drive(crate::page_host::Drive::Mount { .. })
301        )
302    });
303    mounts.then_some(split)
304}
305
306/// Run `source` on the bytecode VM, capturing partial output and the error,
307/// if any. Same front-end as [`tw_outcome`].
308///
309/// A `## Main` that ENDS by driving a page (its trailing statements are nothing but driving
310/// verbs mounting at least one component — `main_drives_a_page`) runs that trailing script
311/// through `page_host::drive_main` instead of letting the compiler inline it into `main`: the same
312/// guarded, settling driver a `## Test` candidate tier uses, so a trapping turn recovers and a
313/// typed fetch completes here exactly as it does there. Every other program — anything with no
314/// trailing driving statement at all — is untouched; the gate never fires for one.
315///
316/// A run is a fresh process, as on every tier: it starts with nothing stored
317/// ([`crate::semantics::storage::reset`]).
318pub fn vm_outcome(source: &str) -> RunOutcome {
319    crate::semantics::storage::reset();
320    crate::ui_bridge::with_parsed_program(source, |parsed, interner| match parsed {
321        Ok((stmts, types, policies)) => {
322            if let Some(split) = main_drives_a_page(stmts, interner) {
323                return match crate::page_host::drive_main(
324                    &stmts[..split],
325                    &stmts[split..],
326                    interner,
327                    types,
328                    &policies,
329                ) {
330                    Ok(output) => RunOutcome {
331                        output,
332                        error: None,
333                    },
334                    Err(e) => RunOutcome {
335                        output: String::new(),
336                        error: Some(e),
337                    },
338                };
339            }
340            let (output, error) =
341                crate::vm::run_to_outcome(stmts, interner, Some(types), Some(&policies));
342            RunOutcome { output, error }
343        }
344        Err(advice) => RunOutcome {
345            output: String::new(),
346            error: Some(advice),
347        },
348    })
349}
350
351/// A runtime failure's message, prefixed with WHERE it happened when a `Stmt::Site` marker was in
352/// force (`site`, from [`crate::interpreter::Interpreter::current_site`]/[`crate::vm::Vm::
353/// failing_site`]) — Wave 3: "runtime failures carry a location". `None` — a failure in `##
354/// Main`/`## Test`'s own top-level statements, which carry no marker — returns `message` unchanged.
355///
356/// `source` is re-parsed once for [`crate::ui_bridge::failure_sites_of`]'s table — a SECOND,
357/// deterministic parse of the identical text through the identical front-end as whichever parse
358/// produced `interner`/`site`. Their `Symbol`s align because [`Interner::intern`] assigns ids in
359/// first-encounter order and both parses see the identical token stream (same source, same lexer,
360/// same prelude splice) — `interner` here is the CALLER's own interner from that SAME source, not
361/// the (discarded) one `failure_sites_of` used internally; it is what [`FailureSite::render`]
362/// (`logicaffeine_language::ast::stmt::FailureSite`) needs to resolve the component/action symbols
363/// this table's spans came with. The catalogue lock (`runtime_failure_location_lock`) is what holds
364/// this alignment to account, on every failure kind, on both tiers.
365fn locate_runtime_failure(
366    source: &str,
367    interner: &Interner,
368    site: Option<u32>,
369    message: &str,
370) -> String {
371    let Some(id) = site else {
372        return message.to_string();
373    };
374    let sites = crate::ui_bridge::failure_sites_of(source);
375    let Some(site) = sites.get(id as usize) else {
376        return message.to_string();
377    };
378    let (line, col) = logicaffeine_language::diagnostic::line_col(source, site.span.start);
379    format!("{line}:{col} — {}", site.render(interner, message))
380}
381
382/// [`tw_outcome`], with a failed run's error LOCATED (see `locate_runtime_failure`) — same front-
383/// end, same interpreter, same error TEXT; this only decides what goes in FRONT of it. A concurrent
384/// program (many `Interpreter` instances, one per task) has no single "the current site" to show, so
385/// it falls back to [`tw_outcome`]'s own unlocated shape rather than guessing which task's site to
386/// name.
387pub fn tw_outcome_located(source: &str) -> RunOutcome {
388    crate::concurrency::net_inbox::set_net_offline(true);
389    crate::ui_bridge::with_parsed_program(source, |parsed, interner| match parsed {
390        Ok((stmts, types, policies)) => {
391            if crate::concurrency::uses_scheduler(stmts) {
392                let force_async = crate::interpreter::needs_async(stmts, interner);
393                let result = crate::ui_bridge::run_treewalker(
394                    stmts,
395                    types,
396                    policies,
397                    interner,
398                    force_async,
399                    &[],
400                );
401                return RunOutcome {
402                    output: result.lines.join("\n"),
403                    error: result.error,
404                };
405            }
406            let force_async = crate::interpreter::needs_async(stmts, interner);
407            let mut interp = crate::interpreter::Interpreter::new(interner)
408                .with_type_registry(types)
409                .with_policies(policies)
410                .with_vfs(std::sync::Arc::new(logicaffeine_system::fs::MemVfs::new()));
411            let run_result = if force_async {
412                futures::executor::block_on(interp.run(stmts))
413            } else {
414                interp.run_sync(stmts)
415            };
416            let site = interp.page_failure_site().or(interp.current_site);
417            let unhandled = interp.take_page_failure();
418            let (error, site) = match run_result {
419                Err(e) => (Some(e), interp.current_site),
420                Ok(()) => (unhandled, site),
421            };
422            let error = error.map(|msg| locate_runtime_failure(source, interner, site, &msg));
423            RunOutcome {
424                output: interp.output.join("\n"),
425                error,
426            }
427        }
428        Err(advice) => RunOutcome {
429            output: String::new(),
430            error: Some(advice),
431        },
432    })
433}
434
435/// [`vm_outcome`], with a failed run's error LOCATED (see `locate_runtime_failure`). Uses the
436/// plain `Compiler::compile_with_oracle` → `Vm::run` path directly (not `page_host::drive_main`'s
437/// page-driving split) — every failure-site fixture this lane's tests drive is a single-turn action
438/// failure, which that plain path already covers exactly as `vm_failure_site_lock.rs` proves. A
439/// run is a fresh process: it starts with nothing stored.
440pub fn vm_outcome_located(source: &str) -> RunOutcome {
441    crate::semantics::storage::reset();
442    crate::ui_bridge::with_parsed_program(source, |parsed, interner| match parsed {
443        Ok((stmts, types, policies)) => {
444            let (output, error, site) =
445                crate::vm::run_to_outcome_located(stmts, interner, Some(types), Some(&policies));
446            let error = error.map(|msg| locate_runtime_failure(source, interner, site, &msg));
447            RunOutcome { output, error }
448        }
449        Err(advice) => RunOutcome {
450            output: String::new(),
451            error: Some(advice),
452        },
453    })
454}
455
456/// Which engine actually executed a strict run — the identity a caller can
457/// trust, because the strict entries never substitute one engine for another.
458#[derive(Debug, Clone, Copy, PartialEq, Eq)]
459pub enum EngineId {
460    /// The tree-walking interpreter (the reference oracle).
461    TreeWalker,
462    /// The register bytecode VM.
463    Vm,
464}
465
466impl EngineId {
467    /// The stable machine-readable label (`"tree-walker"` / `"vm"`).
468    pub fn label(self) -> &'static str {
469        match self {
470            EngineId::TreeWalker => "tree-walker",
471            EngineId::Vm => "vm",
472        }
473    }
474}
475
476/// The outcome of a STRICT engine run. `engine_ran` is the honest identity:
477/// `Some(engine)` means that engine — and only that engine — executed the
478/// program; `None` means NOTHING ran (a parse failure, or the typed refusal of
479/// an engine that cannot run the program) and `error` says why. A strict run
480/// never silently substitutes the tree-walker for the VM.
481#[derive(Debug, Clone, PartialEq, Eq)]
482pub struct EngineOutcome {
483    /// The engine that executed the program, or `None` when nothing ran.
484    pub engine_ran: Option<EngineId>,
485    /// Every output line, newline-joined (both engines share this convention,
486    /// so cross-engine outcomes compare byte-for-byte).
487    pub output: String,
488    /// The runtime error, the parse story, or the refusal reason.
489    pub error: Option<String>,
490}
491
492impl EngineOutcome {
493    /// True when nothing ran and `error` carries the reason — the typed
494    /// refusal (or a parse failure, which refuses BOTH engines).
495    pub fn refused(&self) -> bool {
496        self.engine_ran.is_none()
497    }
498}
499
500/// Engine-identity trace shared with the dispatching paths: with
501/// `LOGOS_ENGINE_TRACE` set, say which engine a strict run used (stderr).
502fn strict_trace(engine: &str) {
503    if std::env::var_os("LOGOS_ENGINE_TRACE").is_some() {
504        eprintln!("logos-engine: {engine}");
505    }
506}
507
508/// Run `source` STRICTLY on the tree-walker. Identical pipeline to
509/// [`tw_outcome`] (same front-end, same oracle engine — concurrency runs on
510/// the tree-walker's deterministic scheduler), plus the honest engine
511/// identity: `engine_ran` is `Some(TreeWalker)` whenever the program executed,
512/// `None` for a parse failure (nothing ran on any engine).
513pub fn run_strict_tw(source: &str) -> EngineOutcome {
514    run_strict_tw_with_args(source, &[])
515}
516
517/// [`run_strict_tw`] with the program argument vector for the `args()` system
518/// native (full argv; index 0 is the program name).
519pub fn run_strict_tw_with_args(source: &str, program_args: &[String]) -> EngineOutcome {
520    // Deterministic oracle: offline single node, matching `tw_outcome`.
521    crate::concurrency::net_inbox::set_net_offline(true);
522    crate::ui_bridge::with_parsed_program(source, |parsed, interner| match parsed {
523        Ok((stmts, types, policies)) => {
524            let force_async = crate::interpreter::needs_async(stmts, interner);
525            strict_trace("strict treewalker");
526            let result = crate::ui_bridge::run_treewalker(
527                stmts,
528                types,
529                policies,
530                interner,
531                force_async,
532                program_args,
533            );
534            EngineOutcome {
535                engine_ran: Some(EngineId::TreeWalker),
536                output: result.lines.join("\n"),
537                error: result.error,
538            }
539        }
540        Err(advice) => EngineOutcome {
541            engine_ran: None,
542            output: String::new(),
543            error: Some(advice),
544        },
545    })
546}
547
548/// Run `source` STRICTLY on the bytecode VM. Identical pipeline to
549/// [`vm_outcome`] (same front-end, same oracle-range compile), with the
550/// strict contract: a program the VM cannot run — one that needs the async
551/// runtime, one that needs the scheduler driver, or one its compiler rejects —
552/// is a TYPED REFUSAL (`engine_ran: None`, `error` says why). The tree-walker
553/// is NEVER silently substituted.
554pub fn run_strict_vm(source: &str) -> EngineOutcome {
555    run_strict_vm_with_args(source, &[])
556}
557
558/// [`run_strict_vm`] with the program argument vector for the `args()` system
559/// native. Honors the thread's armed fuel (the MCP `step_budget`) exactly as
560/// the live sync path does.
561pub fn run_strict_vm_with_args(source: &str, program_args: &[String]) -> EngineOutcome {
562    let refusal = |why: String| {
563        strict_trace("strict vm (refused)");
564        EngineOutcome {
565            engine_ran: None,
566            output: String::new(),
567            error: Some(why),
568        }
569    };
570    crate::ui_bridge::with_parsed_program(source, |parsed, interner| match parsed {
571        Ok((stmts, types, policies)) => {
572            // The strict twins of the dispatcher's tree-walker fallbacks: where
573            // the live path would silently substitute the tree-walker, strict
574            // mode refuses BEFORE anything runs.
575            if crate::interpreter::needs_async(stmts, interner) {
576                return refusal(
577                    "strict vm: refused — this program needs the async runtime (file I/O, \
578                     sleep, serve, or networking); the bytecode VM is sync-only and the \
579                     tree-walker is never silently substituted"
580                        .to_string(),
581                );
582            }
583            if crate::concurrency::uses_scheduler(stmts) {
584                return refusal(
585                    "strict vm: refused — this program uses tasks/channels, which need the \
586                     scheduler driver; the plain bytecode VM cannot run it and the \
587                     tree-walker is never silently substituted"
588                        .to_string(),
589                );
590            }
591            let oracle = crate::optimize::oracle_analyze_with(stmts, interner);
592            let program = match crate::vm::Compiler::compile_with_oracle(
593                stmts,
594                interner,
595                Some(types),
596                Some(oracle),
597            ) {
598                Ok(p) => p,
599                Err(e) => {
600                    return refusal(format!(
601                        "strict vm: refused — the VM compiler cannot compile this program: {e}"
602                    ))
603                }
604            };
605            strict_trace("strict vm");
606            let mut vm = crate::vm::Vm::new(&program)
607                .with_policy_ctx(&policies, interner)
608                .with_program_args(program_args.to_vec());
609            // Same tier rule as the live path: JIT-tiered native code executes
610            // outside the STEPPED accounting, so a budgeted run stays on the
611            // VM dispatch loop.
612            if crate::interpreter::active_fuel().is_none() {
613                if let Some(tier) = crate::vm::installed_native_tier() {
614                    vm = vm.with_native_tier(tier);
615                }
616            }
617            let error = crate::vm::drive_vm(&mut vm);
618            EngineOutcome {
619                engine_ran: Some(EngineId::Vm),
620                output: vm.into_lines().join("\n"),
621                error,
622            }
623        }
624        Err(advice) => EngineOutcome {
625            engine_ran: None,
626            output: String::new(),
627            error: Some(advice),
628        },
629    })
630}
631
632/// Run `source` on the bytecode VM in the OBSERVED profile (Wave 13): the VM
633/// emits the same observation events (`Note`/`Warn`/`Record`/`During`) the
634/// tree-walker does, into the `observe` channel — program output is byte-
635/// identical to [`vm_outcome`]. Pair with `observe::install()`/`drain()` to
636/// capture the emitted event stream.
637pub fn vm_outcome_observed(source: &str) -> RunOutcome {
638    crate::ui_bridge::with_parsed_program(source, |parsed, interner| match parsed {
639        Ok((stmts, types, policies)) => {
640            let (output, error) =
641                crate::vm::run_to_outcome_observed(stmts, interner, Some(types), Some(&policies));
642            RunOutcome { output, error }
643        }
644        Err(advice) => RunOutcome {
645            output: String::new(),
646            error: Some(advice),
647        },
648    })
649}
650
651/// The verdict of a cross-tier differential run (Wave 13, footgun F18). Program
652/// output must be byte-identical across every execution tier; a divergence is
653/// ALWAYS a compiler bug — the framework's liability, never the user's mistake —
654/// and carries a filed-ready reproduction bundle.
655#[derive(Clone, Debug, PartialEq, Eq)]
656pub enum TierVerdict {
657    /// Every tier agreed. The single shared outcome (the tree-walker oracle's).
658    Agree {
659        output: String,
660        error: Option<String>,
661    },
662    /// Two tiers disagreed. `compiler_bug` is invariably `true` — that a tier
663    /// divergence is the compiler's fault (never the user's) is the whole point
664    /// of the classification. `bundle` is a ready-to-file reproduction.
665    Divergence { compiler_bug: bool, bundle: String },
666}
667
668/// Run `source` on every always-available execution tier — the tree-walker
669/// oracle and the register VM — and classify the result (Wave 13; the engine
670/// behind `largo test --tiers all` and the F18 "works-on-my-tier" guard).
671///
672/// Output is compared modulo the one benign, documented tier convention (the VM
673/// terminates output with a newline the tree-walker omits — `trim_end`); error
674/// text is compared exactly. For sequential programs, as the differential
675/// harness is; a concurrency program (which the plain VM entry declines) is out
676/// of scope and simply reports `Agree` from the oracle.
677pub fn tier_differential(source: &str) -> TierVerdict {
678    let tw = tw_outcome(source);
679    let vm = vm_outcome(source);
680
681    // The VM declines scheduler ops ("requires the scheduler driver"); that is a
682    // capability boundary, not a divergence — defer to the oracle (concurrency
683    // has its own seeded differential).
684    let vm_declined = vm
685        .error
686        .as_deref()
687        .map(|e| e.contains("scheduler driver"))
688        .unwrap_or(false);
689    if vm_declined {
690        return TierVerdict::Agree {
691            output: tw.output,
692            error: tw.error,
693        };
694    }
695
696    let outputs_agree = tw.output.trim_end() == vm.output.trim_end();
697    let errors_agree = tw.error == vm.error;
698    if outputs_agree && errors_agree {
699        TierVerdict::Agree {
700            output: tw.output,
701            error: tw.error,
702        }
703    } else {
704        let bundle = format!(
705            "TIER DIVERGENCE — a compiler bug (the framework's liability, never your program's).\n\
706             This is footgun F18: a 5-tier language must guarantee every tier agrees.\n\
707             --- source ---\n{source}\n\
708             --- tree-walker (oracle) ---\noutput={:?}\nerror={:?}\n\
709             --- register VM ---\noutput={:?}\nerror={:?}\n",
710            tw.output, tw.error, vm.output, vm.error
711        );
712        TierVerdict::Divergence {
713            compiler_bug: true,
714            bundle,
715        }
716    }
717}
718
719/// The VM outcome for a CONCURRENT program — drives the bytecode VM on the cooperative scheduler
720/// (`VmTask` on `run_with_seed`, seed 0) exactly as the browser/playground does, so a `Pipe`/task/
721/// `Select` program runs on the VM byte-identical to the tree-walker's async path. The plain
722/// [`vm_outcome`] errors on any concurrency op (`requires the scheduler driver`); this is the oracle
723/// the AOT concurrency lock compares against so tw == VM == AOT is verifiable for the concurrent set.
724#[cfg(not(target_arch = "wasm32"))]
725pub fn vm_outcome_concurrent(source: &str) -> RunOutcome {
726    let r = crate::ui_bridge::run_vm_concurrent(source);
727    RunOutcome {
728        output: r.lines.join("\n"),
729        error: r.error,
730    }
731}
732
733/// The VM outcome for a peer-NETWORKING program — drives the resumable bytecode VM and services each
734/// `VmBlock::Net*` through the shared LOCAL `NetInbox` (the same inbox the tree-walker's offline
735/// mode uses), so `Listen`/`Send`/`Sync`/`PeerAgent` run on the VM byte-identical to the tree-walker.
736/// The AOT networking lock compares against this so tw == VM == AOT holds for the local-mode net set.
737#[cfg(not(target_arch = "wasm32"))]
738pub fn vm_outcome_net(source: &str) -> RunOutcome {
739    let r = vm_lines_net(source);
740    RunOutcome {
741        output: r.lines.join("\n"),
742        error: r.error,
743    }
744}
745
746/// [`vm_outcome_net`] with the shown lines kept apart (see [`tw_lines`]).
747#[cfg(not(target_arch = "wasm32"))]
748pub fn vm_lines_net(source: &str) -> crate::interpreter::InterpreterResult {
749    // Deterministic oracle: offline single node, so `Connect` is a local no-op (matches `tw_outcome`).
750    crate::concurrency::net_inbox::set_net_offline(true);
751    futures::executor::block_on(crate::ui_bridge::run_vm_net_async(source))
752}
753
754/// Run an ALREADY-COMPILED (possibly HAND-AUTHORED) program through the reversible cooperative scheduler
755/// (`RevCoop`) and return its main output. The scheduler-only ops that no LOGOS source emits — `ChanClose`,
756/// `TaskAwait`, `SpawnHandle` — BLOCK on the plain VM (`requires the scheduler driver`), so their fabric
757/// tile is proven by hand-building a raw `CompiledProgram` and differencing the fabric tape against THIS
758/// oracle (the same seam `codegen_sva/rtl.rs`'s soft-core differential uses for those ops).
759#[cfg(not(target_arch = "wasm32"))]
760pub fn program_outcome_scheduled(program: &crate::vm::CompiledProgram) -> RunOutcome {
761    match crate::vm::RevCoop::record(crate::vm::Vm::new(program)) {
762        Ok(coop) => RunOutcome {
763            output: coop.main_output(),
764            error: None,
765        },
766        Err(e) => RunOutcome {
767            output: String::new(),
768            error: Some(e),
769        },
770    }
771}
772
773/// Run an ALREADY-COMPILED (possibly HAND-AUTHORED) program through the FULL cooperative scheduler (the same
774/// `VmTask`/`run_with_seed` driver `run_vm_concurrent` uses, seed 0), returning its output. Unlike the
775/// reversible `program_outcome_scheduled`, this services ops the reverse machinery does not yet cover
776/// (`TaskAbort`) — so it is the oracle for the fabric's `TaskAbort` tile.
777#[cfg(not(target_arch = "wasm32"))]
778pub fn program_outcome_concurrent(program: &crate::vm::CompiledProgram) -> RunOutcome {
779    let r = program_lines_concurrent(program);
780    RunOutcome {
781        output: r.lines.join("\n"),
782        error: r.error,
783    }
784}
785
786/// [`program_outcome_concurrent`] with the shown lines kept apart (see [`tw_lines`]).
787#[cfg(not(target_arch = "wasm32"))]
788pub fn program_lines_concurrent(
789    program: &crate::vm::CompiledProgram,
790) -> crate::interpreter::InterpreterResult {
791    use crate::concurrency::vm_driver::VmTask;
792    use logicaffeine_runtime::{
793        run_with_seed, RunOutcome as RtOutcome, SchedSeed, SchedulerConfig,
794    };
795    use std::cell::RefCell;
796    use std::rc::Rc;
797
798    let output: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
799    let err_sink: crate::concurrency::driver::ErrSink = Rc::new(RefCell::new(None));
800    let main_task = VmTask::new(
801        crate::vm::Vm::new(program),
802        output.clone(),
803        Some(err_sink.clone()),
804    );
805    let (outcome, _trace) = run_with_seed(SchedulerConfig::default(), SchedSeed(0), move |sched| {
806        sched.spawn_main(Box::new(main_task));
807    });
808    let mut error = err_sink.borrow().clone();
809    if error.is_none() {
810        if let RtOutcome::Deadlock = outcome {
811            error = Some("deadlock: every task is blocked waiting".to_string());
812        }
813    }
814    let lines = output.borrow().clone();
815    crate::interpreter::InterpreterResult { lines, error }
816}
817
818/// Run an ALREADY-COMPILED `CompiledProgram` straight-line on the VM and return its outcome — the plain-
819/// sequential counterpart to [`program_outcome_scheduled`]/[`program_outcome_concurrent`]. This is the
820/// missing primitive that lets the source-of-truth invariants be expressed against the SAME bytecode IR every
821/// backend lowers: `VM(opt P)` is `program_outcome(&optimized_program)`, so a backend's output can be
822/// differenced against the exact IR it consumed. Partial output on error is preserved (matching the VM).
823#[cfg(not(target_arch = "wasm32"))]
824pub fn program_outcome(program: &crate::vm::CompiledProgram) -> RunOutcome {
825    let mut vm = crate::vm::Vm::new(program);
826    match vm.run() {
827        Ok(()) => RunOutcome {
828            output: vm.output(),
829            error: None,
830        },
831        Err(e) => RunOutcome {
832            output: vm.output(),
833            error: Some(e),
834        },
835    }
836}
837
838/// [`tw_outcome`] with the program argument vector for the `args()` system
839/// native (full argv; index 0 is the program name) — the seam the benchmark
840/// corpus differential uses to run `main.lg` programs that read their size
841/// from argv.
842pub fn tw_outcome_with_args(source: &str, program_args: &[String]) -> RunOutcome {
843    let result = tw_lines_with_args(source, program_args);
844    RunOutcome {
845        output: result.lines.join("\n"),
846        error: result.error,
847    }
848}
849
850/// [`vm_outcome`] with the program argument vector and an optional private
851/// native tier (so a differential test can observe THAT program's JIT compile
852/// counters in isolation — the process-wide tier's counters are shared by
853/// every test in the binary).
854pub fn vm_outcome_with_args(
855    source: &str,
856    program_args: &[String],
857    tier: Option<&dyn crate::vm::NativeTier>,
858) -> RunOutcome {
859    crate::ui_bridge::with_parsed_program(source, |parsed, interner| match parsed {
860        Ok((stmts, types, policies)) => {
861            let (output, error) = crate::vm::run_to_outcome_with_args(
862                stmts,
863                interner,
864                Some(types),
865                Some(&policies),
866                program_args,
867                tier,
868            );
869            RunOutcome { output, error }
870        }
871        Err(advice) => RunOutcome {
872            output: String::new(),
873            error: Some(advice),
874        },
875    })
876}
877
878/// [`vm_outcome_with_args`], but the statements pass through the run-path optimizer
879/// at an explicit hotness `tier` (HOTSWAP §4) before reaching the VM — the seam the
880/// `tier_invariance` gate drives at every tier T0..T3 to assert byte-identical
881/// output. `tier = Tier::T3` reproduces today's optimized run path.
882pub fn vm_outcome_tiered(
883    source: &str,
884    program_args: &[String],
885    tier: crate::optimization::Tier,
886    native_tier: Option<&dyn crate::vm::NativeTier>,
887) -> RunOutcome {
888    crate::ui_bridge::with_optimized_program_tiered(source, tier, |parsed, interner| match parsed {
889        Ok((stmts, types, policies)) => {
890            // `with_optimized_program_tiered` above owns the shared optimizer
891            // stage. Bytecode selection and any native-tier work happen only
892            // after that program reaches the VM, so keep their `mark_fired`
893            // evidence in backend lowering. Without this boundary a JIT trace
894            // falsely reports VM choices such as `unbox` and `fastdiv` as
895            // extra shared optimizer passes.
896            let (output, error) = crate::optimize::with_backend_lowering(|| {
897                crate::vm::run_to_outcome_with_args(
898                    stmts,
899                    interner,
900                    Some(types),
901                    Some(&policies),
902                    program_args,
903                    native_tier,
904                )
905            });
906            RunOutcome { output, error }
907        }
908        Err(advice) => RunOutcome {
909            output: String::new(),
910            error: Some(advice),
911        },
912    })
913}
914
915/// [`vm_outcome_with_args`] driven through the BACKGROUND native compiler (HOTSWAP §6):
916/// hot functions compile on a worker thread off the interpreter's path. Requires a
917/// process-installed tier (the P8 gate installs one first). The compiled chain is
918/// identical to the synchronous one — only WHEN it is produced differs — so output
919/// must match the synchronous/tree-walker engines exactly.
920#[cfg(not(target_arch = "wasm32"))]
921pub fn vm_outcome_bg(source: &str, program_args: &[String]) -> RunOutcome {
922    crate::ui_bridge::with_parsed_program(source, |parsed, interner| match parsed {
923        Ok((stmts, types, policies)) => {
924            let (output, error) = crate::vm::run_to_outcome_bg(
925                stmts,
926                interner,
927                Some(types),
928                Some(&policies),
929                program_args,
930            );
931            RunOutcome { output, error }
932        }
933        Err(advice) => RunOutcome {
934            output: String::new(),
935            error: Some(advice),
936        },
937    })
938}
939
940/// Refuse a program that touches a BROWSER surface on a tier that has none.
941///
942/// The DOM, the signal store and WebRTC arrive as ordinary builtin CALLS rather than opcodes of
943/// their own, so a backend that never inspects builtins simply emits them and returns an
944/// artifact. AOT-Rust produced 380 bytes for a page, AOT-C produced 121KB, and neither has a
945/// document — `largo build --target c` on a `## Page` looked like a successful build and could
946/// only ever render nothing, with the mistake surfacing far from the `--target` flag that caused
947/// it. Fail closed instead, and NAME the DOM so the reader knows the tier is wrong for the
948/// program rather than the program being wrong.
949fn refuse_browser_surface(source: &str, tier: &str) -> Result<(), ParseError> {
950    let Ok(program) = compile_to_program(source) else {
951        return Ok(());
952    };
953    // REACHABLE, not merely present: the prelude loads standard-library functions this program
954    // never calls, and `web.lg` holds the browser fetch wrappers beside the pure-text helpers.
955    if crate::aot_unsupported::first_reachable(&program)
956        == Some(crate::aot_unsupported::Offload::Dom)
957    {
958        return Err(ParseError {
959            kind: crate::error::ParseErrorKind::Custom(format!(
960                "{tier} cannot build a page: this program touches the DOM (a browser surface), \
961                 and {tier} has no document to build. A `## Page` or a `## Component` runs on the \
962                 tree-walker and in the browser through WebAssembly — build it for one of those, \
963                 or move the part that is not about the page into a program of its own."
964            )),
965            span: crate::token::Span::default(),
966        });
967    }
968    Ok(())
969}
970
971/// `stmts` with the root bindings its functions reach lifted into one lent record
972/// ([`crate::program_bindings`]) — for a tier that compiles `## Main` into a function of its own —
973/// and the registry that record is registered in. Unchanged when no function reaches one.
974fn lift_program_bindings<'a>(
975    stmts: Vec<Stmt<'a>>,
976    registry: crate::analysis::TypeRegistry,
977    interner: &mut Interner,
978    arenas: crate::ast_map::Arenas<'a>,
979) -> Result<(Vec<Stmt<'a>>, crate::analysis::TypeRegistry), ParseError> {
980    match crate::program_bindings::lift_program_bindings(&stmts, &registry, interner, arenas) {
981        Ok(Some(lifted)) => Ok((lifted.stmts, lifted.registry)),
982        Ok(None) => Ok((stmts, registry)),
983        Err(why) => Err(ParseError {
984            kind: crate::error::ParseErrorKind::Custom(why),
985            span: crate::token::Span::default(),
986        }),
987    }
988}
989
990/// Compile LOGOS source to Rust source code.
991///
992/// This is the basic compilation function that runs lexing, parsing, and
993/// escape analysis before generating Rust code.
994///
995/// # Arguments
996///
997/// * `source` - LOGOS source code as a string
998///
999/// # Returns
1000///
1001/// Generated Rust source code on success.
1002///
1003/// # Errors
1004///
1005/// Returns [`ParseError`] if:
1006/// - Lexical analysis fails (invalid tokens)
1007/// - Parsing fails (syntax errors)
1008/// - Escape analysis fails (zone-local values escaping)
1009/// - The program reaches a browser surface (the DOM, the signal store, WebRTC), which the AOT-Rust tier
1010///   does not have
1011///
1012/// # Example
1013///
1014/// ```
1015/// # use logicaffeine_compile::compile::compile_to_rust;
1016/// # use logicaffeine_compile::ParseError;
1017/// # fn main() -> Result<(), ParseError> {
1018/// let source = "## Main\nLet x be 5.\nShow x.";
1019/// let rust_code = compile_to_rust(source)?;
1020/// assert!(rust_code.contains("fn main()"));
1021/// assert!(!rust_code.contains("compile_error!"));
1022/// # Ok(())
1023/// # }
1024/// ```
1025pub fn compile_to_rust(source: &str) -> Result<String, ParseError> {
1026    refuse_browser_surface(source, "the AOT-Rust backend")?;
1027    compile_program_full(source).map(|o| o.rust_code)
1028}
1029
1030/// Compile for **deterministic replay**: identical to [`compile_to_rust`] for a program
1031/// that never touches the scheduler; a program that does runs its tasks, pipes, timers and selects on
1032/// `logicaffeine_system::replay`, the interpreter's scheduler ported, so a binary run under
1033/// `LOGOS_SEED=…` prints what the interpreter prints at that seed. Used by the seeded differential
1034/// harness.
1035pub fn compile_to_rust_deterministic(source: &str) -> Result<String, ParseError> {
1036    crate::codegen::with_deterministic_replay(|| compile_to_rust(source))
1037}
1038
1039/// Compile to Rust in the **OBSERVED profile** (Wave 13): the emitted program
1040/// EMITS observation events — `logicaffeine_system::obs::record`/`span_enter`/
1041/// `span_exit` calls for `Note`/`Warn`/`Record`/`During` — instead of eliding
1042/// them. The default [`compile_to_rust`] stays the elided (release) profile,
1043/// byte-identical to the observation-free program (§0.7).
1044pub fn compile_to_rust_observed(source: &str) -> Result<String, ParseError> {
1045    crate::codegen::with_observed_codegen(|| compile_to_rust(source))
1046}
1047
1048/// Compile imperative LOGOS to Rust with an extracted math/logic module bundled in.
1049/// `proven` is a main-less Rust module body (the Forge's extraction); it is emitted
1050/// as `pub mod proven { … } use proven::*;` so the imperative program can call its
1051/// functions / `check_*` predicates by name. See [`compile_program_full_with_proven`].
1052pub fn compile_to_rust_with_proven(source: &str, proven: &str) -> Result<String, ParseError> {
1053    compile_program_full_with_proven(source, Some(proven)).map(|o| o.rust_code)
1054}
1055
1056/// Which optimizations actually FIRE for `source`: an optimization is "used" when
1057/// disabling it (via a file-level `## No <X>` decorator) changes the generated
1058/// Rust. Lets the benchmarks UI show, per program, which optimizations it USES vs
1059/// the full set it CAN use. O(number of optimizations) compiles — intended for
1060/// per-benchmark, not hot-path, use. Returns the decorator keywords of the firing
1061/// optimizations (in registry order).
1062pub fn optimizations_used(source: &str) -> Vec<&'static str> {
1063    let base = match compile_to_rust(source) {
1064        Ok(r) => r,
1065        Err(_) => return Vec::new(),
1066    };
1067    crate::optimization::REGISTRY
1068        .iter()
1069        .filter(|m| {
1070            let decorated = crate::optimization::decorate_source(source, &[m.keyword]);
1071            compile_to_rust(&decorated)
1072                .map(|r| r != base)
1073                .unwrap_or(false)
1074        })
1075        .map(|m| m.keyword)
1076        .collect()
1077}
1078
1079/// Compile `source` while recording which optimizations actually FIRED — the
1080/// honest, single-compile alternative to [`optimizations_used`]'s O(N) diff. An
1081/// optimization is "fired" when it actually changed the program or emitted its
1082/// optimized form for this compile, under the effective (normalized) config.
1083/// Reusable: any caller can compile a program and learn what fired, for tracing
1084/// and tooling.
1085pub fn compile_program_traced(
1086    source: &str,
1087) -> Result<(CompileOutput, crate::optimization::FiredOptimizations), ParseError> {
1088    crate::optimize::begin_fired_trace();
1089    let result = compile_program_full(source);
1090    // Always end the trace (even on a parse error) so the thread-local never
1091    // leaks into a later compile on this thread.
1092    let fired = crate::optimize::end_fired_trace().unwrap_or_default();
1093    result.map(|o| (o, fired))
1094}
1095
1096/// Compile the Rust AOT backend with stage-separated optimization evidence.
1097/// The ordinary compile path is unchanged; tracing only observes existing
1098/// `mark_fired` sites and classifies them as shared optimizer vs Rust lowering.
1099pub fn compile_program_backend_traced(
1100    source: &str,
1101) -> Result<(CompileOutput, crate::optimization::BackendOptimizationTrace), ParseError> {
1102    crate::optimize::begin_backend_trace(crate::optimization::OptimizationBackend::RustAot);
1103    let result = compile_program_full(source);
1104    let trace = crate::optimize::end_backend_trace().expect("backend trace was just started");
1105    result.map(|o| (o, trace))
1106}
1107
1108/// The decorator keywords of the optimizations that fired for `source` (registry
1109/// order), under the default/effective config. One compile, exact.
1110pub fn optimizations_fired(source: &str) -> Vec<&'static str> {
1111    compile_program_traced(source)
1112        .map(|(_, fired)| fired.keywords())
1113        .unwrap_or_default()
1114}
1115
1116/// The optimizations that fired for `source` under an explicit config — re-traces
1117/// an arbitrary toggle state (turning some off can make others fire). Realised by
1118/// disabling that config's off-keywords on the source, then tracing.
1119pub fn optimizations_fired_with(
1120    source: &str,
1121    cfg: &crate::optimization::OptimizationConfig,
1122) -> Vec<&'static str> {
1123    let disabled: Vec<&'static str> = cfg.disabled_keywords().collect();
1124    let decorated = crate::optimization::decorate_source(source, &disabled);
1125    optimizations_fired(&decorated)
1126}
1127
1128/// One compile returning the generated Rust, the fired-optimization keywords, AND
1129/// the `(winner, loser)` precedence decisions made — what an interactive viewer
1130/// calls per toggle state to show the firing opts and the conflicts that occurred.
1131pub fn compile_to_rust_traced(
1132    source: &str,
1133) -> Result<(String, Vec<&'static str>, Vec<(&'static str, &'static str)>), ParseError> {
1134    crate::optimize::begin_fired_trace();
1135    let result = compile_program_full(source);
1136    let fired = crate::optimize::end_fired_trace()
1137        .unwrap_or_default()
1138        .keywords();
1139    let preempted = preempted_keywords();
1140    result.map(|o| (o.rust_code, fired, preempted))
1141}
1142
1143/// The `(winner, loser)` precedence decisions the compiler made for `source` — the
1144/// conflicts traced at their source (`mark_preempted`), under the effective config.
1145pub fn optimization_preemptions(source: &str) -> Vec<(&'static str, &'static str)> {
1146    crate::optimize::begin_fired_trace();
1147    let _ = compile_program_full(source);
1148    let _ = crate::optimize::end_fired_trace();
1149    preempted_keywords()
1150}
1151
1152/// Convert the trace's `(Opt, Opt)` preemption edges to `(keyword, keyword)`.
1153fn preempted_keywords() -> Vec<(&'static str, &'static str)> {
1154    crate::optimize::end_preempted_trace()
1155        .into_iter()
1156        .map(|(w, l)| (w.meta().keyword, l.meta().keyword))
1157        .collect()
1158}
1159
1160/// The per-program DEPENDENCY edges for `source`, discovered by evaluating with
1161/// all optimizations on and probing: disabling a fired optimization `dep` that
1162/// makes another fired optimization `dependent` STOP firing means `dependent`
1163/// depended on `dep` for this program. Stops already explained by a declared
1164/// `requires`-cascade (`normalize` would disable the dependent anyway) are
1165/// excluded — those are captured by the static registry graph. What remains are
1166/// the EMERGENT, program-specific dependencies (e.g. dead-code elimination only
1167/// had work because scalarization produced the dead code): returned as
1168/// `(dependent, dep)` keyword pairs, sorted and deduped (deterministic).
1169///
1170/// This is offline analysis (one compile per fired optimization) — it is baked
1171/// into the benchmark data, never run in the hot path.
1172pub fn optimization_dependencies(source: &str) -> Vec<(&'static str, &'static str)> {
1173    use crate::optimization::{by_keyword, decorate_source, OptimizationConfig};
1174    use std::collections::BTreeSet;
1175
1176    let base: Vec<&'static str> = optimizations_fired(source);
1177    let base_set: BTreeSet<&'static str> = base.iter().copied().collect();
1178    let mut out: Vec<(&'static str, &'static str)> = Vec::new();
1179    for &dep in &base {
1180        let dep_opt = match by_keyword(dep) {
1181            Some(o) => o,
1182            None => continue,
1183        };
1184        // What the declared `requires`-cascade disables when `dep` is off.
1185        let mut cfg = OptimizationConfig::all_on();
1186        cfg.set(dep_opt, false);
1187        cfg.normalize();
1188        let off: BTreeSet<&'static str> = optimizations_fired(&decorate_source(source, &[dep]))
1189            .into_iter()
1190            .collect();
1191        for &dependent in &base_set {
1192            if dependent == dep || off.contains(dependent) {
1193                continue;
1194            }
1195            let dependent_opt = match by_keyword(dependent) {
1196                Some(o) => o,
1197                None => continue,
1198            };
1199            // Skip stops the static graph already explains (normalize disabled it).
1200            if cfg.is_on(dependent_opt) {
1201                out.push((dependent, dep));
1202            }
1203        }
1204    }
1205    out.sort();
1206    out.dedup();
1207    out
1208}
1209
1210/// The complete per-program optimization graph from one all-on evaluation: the
1211/// optimizations that `fired`, the `blockers` (`(winner, loser)` preemptions that
1212/// occurred), and the emergent `dependencies` (`(dependent, dep)` — see
1213/// [`optimization_dependencies`]). Everything the menu-tree needs, baked once per
1214/// benchmark so the UI never probes in the hot path. All on the AOT codegen path
1215/// (the one that produces the shown Rust), so the three views agree.
1216pub fn optimization_graph(
1217    source: &str,
1218) -> (
1219    Vec<&'static str>,
1220    Vec<(&'static str, &'static str)>,
1221    Vec<(&'static str, &'static str)>,
1222) {
1223    (
1224        optimizations_fired(source),
1225        optimization_preemptions(source),
1226        optimization_dependencies(source),
1227    )
1228}
1229
1230/// The optimizations that fired on the RUN path — the VM/interpreter optimizer
1231/// (`optimize_for_run`) — for `source`. The run-path analogue of
1232/// [`optimizations_fired`] (which traces the AOT codegen path); it surfaces the
1233/// run-path-only passes — inlining, loop-carried CSE, float strength reduction —
1234/// the AOT trace cannot see. Respects file-level `## No <opt>` decorators.
1235pub fn optimization_trace_run(source: &str) -> crate::optimization::BackendOptimizationTrace {
1236    crate::optimize::begin_backend_trace(crate::optimization::OptimizationBackend::TreeWalker);
1237    crate::ui_bridge::with_optimized_program(source, |_parsed, _interner| {});
1238    crate::optimize::end_backend_trace().expect("backend trace was just started")
1239}
1240
1241pub fn optimizations_fired_run(source: &str) -> Vec<&'static str> {
1242    optimization_trace_run(source).all_fired().keywords()
1243}
1244
1245/// The optimizations that fired while compiling `source` to VM bytecode — the
1246/// third path, after AOT codegen and the run-path optimizer. Surfaces the
1247/// VM-compile-time opts (constant-divisor magic division, VM `i32` narrowing)
1248/// the other two traces cannot see. Compiles only (no execution), so it is fast
1249/// and needs no program arguments.
1250pub fn optimization_trace_vm(source: &str) -> crate::optimization::BackendOptimizationTrace {
1251    crate::optimize::begin_backend_trace(crate::optimization::OptimizationBackend::Vm);
1252    crate::ui_bridge::with_optimized_program(source, |parsed, interner| {
1253        if let Ok((stmts, types, _policies)) = parsed {
1254            let _ = crate::optimize::with_backend_lowering(|| {
1255                // The oracle is consumed by VM bytecode selection after the shared
1256                // run-path optimizer has finished.  Keep facts it discovers in the
1257                // backend-lowering stage; otherwise an analysis-only `mark_fired`
1258                // looks like a VM-only optimizer transform and trips the parity
1259                // ratchet against the tree-walker/run path.
1260                let oracle = crate::optimize::oracle_analyze_with(stmts, interner);
1261                let program = crate::vm::Compiler::compile_with_oracle(
1262                    stmts,
1263                    interner,
1264                    Some(types),
1265                    Some(oracle),
1266                );
1267                // This entry point traces the VM as the final backend, so
1268                // selecting an unchecked opcode is VM lowering evidence.  Do
1269                // the census here instead of in `Compiler::emit`: bytecode-C
1270                // uses the same compiler as an intermediate producer and must
1271                // earn its own `Unchecked` bit only when its C walker actually
1272                // consumes the opcode.  That separation is what lets the
1273                // cross-backend ratchet detect a silently reintroduced check.
1274                if let Ok(program) = &program {
1275                    if program.code.iter().any(|op| {
1276                        matches!(
1277                            op,
1278                            crate::vm::Op::IndexUnchecked { .. }
1279                                | crate::vm::Op::SetIndexUnchecked { .. }
1280                        )
1281                    }) {
1282                        crate::optimize::mark_fired(crate::optimization::Opt::Unchecked);
1283                    }
1284                }
1285                program
1286            });
1287        }
1288    });
1289    crate::optimize::end_backend_trace().expect("backend trace was just started")
1290}
1291
1292pub fn optimizations_fired_vm(source: &str) -> Vec<&'static str> {
1293    optimization_trace_vm(source).all_fired().keywords()
1294}
1295
1296/// Compile LOGOS source to C code.
1297///
1298/// Produces a self-contained C file with embedded runtime that can be
1299/// compiled with `gcc -O2 -o program output.c`.
1300pub fn compile_to_c(source: &str) -> Result<String, ParseError> {
1301    // A program the VM refuses before it runs is one whose every run fails, before any output, in the VM's
1302    // own words: the C is that program.
1303    if let Some(refusal) = vm_refusal(source) {
1304        return Ok(crate::codegen_c::refused_program(&refusal));
1305    }
1306    compile_to_c_tiered(source, crate::codegen_c::TaskTier::Coroutines)
1307}
1308
1309/// Direct AST→C compilation with stage-separated optimization evidence.
1310/// The refusal probe runs before tracing so VM-only probe work cannot be
1311/// misreported as a C optimization.
1312pub fn compile_to_c_traced(
1313    source: &str,
1314) -> Result<(String, crate::optimization::BackendOptimizationTrace), ParseError> {
1315    let refusal = vm_refusal(source);
1316    crate::optimize::begin_backend_trace(crate::optimization::OptimizationBackend::CAst);
1317    let result = match refusal {
1318        Some(refusal) => Ok(crate::codegen_c::refused_program(&refusal)),
1319        None => compile_to_c_tiered(source, crate::codegen_c::TaskTier::Coroutines),
1320    };
1321    let trace = crate::optimize::end_backend_trace().expect("backend trace was just started");
1322    result.map(|c| (c, trace))
1323}
1324
1325/// Why the VM refuses `source` before running any of it — its front end rejects the text, or its compiler the
1326/// program — in the words [`vm_outcome`] reports; `None` for a program it runs.
1327fn vm_refusal(source: &str) -> Option<String> {
1328    crate::ui_bridge::with_parsed_program(source, |parsed, interner| match parsed {
1329        Err(advice) => Some(advice),
1330        Ok((stmts, _, _)) if main_drives_a_page(stmts, interner).is_some() => None,
1331        Ok((stmts, types, _)) => {
1332            let oracle = crate::optimize::oracle_analyze_with(stmts, interner);
1333            crate::vm::Compiler::compile_with_oracle(stmts, interner, Some(types), Some(oracle))
1334                .err()
1335        }
1336    })
1337}
1338
1339/// [`compile_to_c`] with the program's tasks as step functions over heap frames — the stepped tier, the one
1340/// a GPU thread can run and the host walker runs — instead of coroutines on stacks of their own.
1341pub fn compile_to_c_stepped(source: &str) -> Result<String, ParseError> {
1342    compile_to_c_tiered(source, crate::codegen_c::TaskTier::Stepped)
1343}
1344
1345/// [`compile_to_c_stepped`] under an explicit [`SchedulerKnobs`](crate::codegen_c::concurrency::SchedulerKnobs):
1346/// the scheduler's policy, workers, seed and default pipe capacity, as `#define`s its scheduler reads.
1347#[cfg(not(target_arch = "wasm32"))]
1348pub fn compile_to_c_stepped_with_knobs(
1349    source: &str,
1350    knobs: &crate::codegen_c::concurrency::SchedulerKnobs,
1351) -> Result<String, ParseError> {
1352    Ok(format!(
1353        "{}{}",
1354        knobs.emit_defines(),
1355        compile_to_c_stepped(source)?
1356    ))
1357}
1358
1359fn compile_to_c_tiered(
1360    source: &str,
1361    tier: crate::codegen_c::TaskTier,
1362) -> Result<String, ParseError> {
1363    refuse_browser_surface(source, "the AOT-C backend")?;
1364    // Auto-prepend the stdlib modules the program references, exactly as the Rust path does
1365    // (see `compile_program_full_with_proven`). Without this the C backend lexes the bare user
1366    // source, so a call to an auto-imported stdlib function (`gcd`, `binomial`, …) emits the call
1367    // but never its body — the generated C fails to link ("undefined reference"). No-op when the
1368    // program uses no stdlib vocabulary, so hand-written C corpora stay byte-identical.
1369    let prelude_src = crate::loader::apply_prelude(source);
1370    // Tree-shake unreachable functions before C codegen: the flat C namespace can't emit an
1371    // unused stdlib function that collides with a libc name or hits a C-codegen gap it is never
1372    // reached through. (C-only; the Rust backend tolerates dead functions, so it keeps the full
1373    // splice.)
1374    let pruned = crate::loader::keep_reachable_functions(source, prelude_src.as_ref());
1375    let source = pruned.as_str();
1376    let library = crate::loader::LibraryProvenance::of(source);
1377
1378    let mut interner = Interner::new();
1379    let mut lexer = Lexer::new(source, &mut interner);
1380    let tokens = lexer.tokenize();
1381
1382    let (type_registry, policy_registry) = {
1383        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
1384        let result = discovery.run_full();
1385        (result.types, result.policies)
1386    };
1387
1388    let mut world_state = WorldState::new();
1389    let expr_arena = Arena::new();
1390    let term_arena = Arena::new();
1391    let np_arena = Arena::new();
1392    let sym_arena = Arena::new();
1393    let role_arena = Arena::new();
1394    let pp_arena = Arena::new();
1395    let stmt_arena: Arena<Stmt> = Arena::new();
1396    let _compile_facts = crate::optimize::facts::scope();
1397    let imperative_expr_arena: Arena<Expr> = Arena::new();
1398    let type_expr_arena: Arena<TypeExpr> = Arena::new();
1399
1400    let ast_ctx = AstContext::with_types(
1401        &expr_arena,
1402        &term_arena,
1403        &np_arena,
1404        &sym_arena,
1405        &role_arena,
1406        &pp_arena,
1407        &stmt_arena,
1408        &imperative_expr_arena,
1409        &type_expr_arena,
1410    );
1411
1412    let mut parser = Parser::new(
1413        tokens,
1414        &mut world_state,
1415        &mut interner,
1416        ast_ctx,
1417        type_registry,
1418    );
1419    let stmts = parser.parse_program()?;
1420    // Honor file-level `## No`/`## Require` decorators on the C backend (`largo emit c`) via the
1421    // shared gate: merge `## No` into the active config and fail an unfired `## Require`. Captured
1422    // here (the last use of `parser`) so its `&mut interner` borrow ends before reuse.
1423    let (opt_config, gate) = crate::optimize::install_decorators(
1424        crate::optimization::OptimizationConfig::from_env(),
1425        &parser.program_opt_flags(),
1426        parser.required_optimizations(),
1427    );
1428    let codegen_registry = parser.into_type_registry();
1429    // Unreachable functions were tree-shaken above, so a native-kernel declaration that survives is
1430    // one the program calls — and C cannot link the Rust kernels.
1431    if let Some(kernel) = stmts.iter().find_map(|s| match s {
1432        Stmt::FunctionDef {
1433            name,
1434            is_native: true,
1435            ..
1436        } => crate::semantics::native_kernels::NativeKernel::from_name(interner.resolve(*name)),
1437        _ => None,
1438    }) {
1439        return Err(ParseError {
1440            kind: crate::error::ParseErrorKind::Custom(kernel.refusal("C")),
1441            span: crate::token::Span::default(),
1442        });
1443    }
1444    if let Some(kind) = codegen_registry
1445        .iter_types()
1446        .find_map(|(_, def)| match def {
1447            crate::analysis::TypeDef::Struct { fields, .. } => fields.iter().find_map(|f| {
1448                crate::semantics::crdt::CrdtKind::of_type_name(field_type_base_name(
1449                    &f.ty, &interner,
1450                ))
1451                .filter(|k| !k.lowered_by(Backend::CFromAst))
1452            }),
1453            _ => None,
1454        })
1455    {
1456        return Err(ParseError {
1457            kind: crate::error::ParseErrorKind::Custom(kind.refusal("C")),
1458            span: crate::token::Span::default(),
1459        });
1460    }
1461    // A pipe parameter declared by its element (`ch: Real`, as the interpreter accepts) becomes
1462    // `Pipe of Real`, so every site that types a parameter by its declaration sees a pipe.
1463    let stmts = crate::analysis::pipes::declare_pipe_params(
1464        &stmts,
1465        crate::ast_map::Arenas {
1466            exprs: &imperative_expr_arena,
1467            stmts: &stmt_arena,
1468            types: &type_expr_arena,
1469        },
1470        &mut interner,
1471    );
1472    // Preserve source-level purity and recursion shape while inserting an explicit cache. The shared
1473    // optimizer and versioner must still see this source-shaped program, just as the Rust backend does;
1474    // C-only monomorphization runs after their final proof-bearing rewrite.
1475    let stmts = crate::optimize::memoize_for_explicit_lowering(
1476        stmts,
1477        &imperative_expr_arena,
1478        &stmt_arena,
1479        &mut interner,
1480        &opt_config,
1481    );
1482    // Type-directed division: rewrite `Divide → ExactDivide` in every Rational context (the integer
1483    // default stays floor), so `Let x: Rational be 7 / 2` compiles exact (`7/2`) instead of flooring to
1484    // `3` — matching the tree-walker/VM and the AOT-Rust path. The optimizer treats `ExactDivide` as
1485    // opaque (never floor-folds it, and never leaks an integer point-range from it), so this is the
1486    // single pass that keeps the exact numeric tower away from the integer-only folds. Purely additive.
1487    let resolved = crate::resolve_program::resolve_program(
1488        &stmts,
1489        crate::ast_map::Arenas {
1490            exprs: &imperative_expr_arena,
1491            stmts: &stmt_arena,
1492            types: &type_expr_arena,
1493        },
1494        &mut interner,
1495        opt_config.is_on(crate::optimization::Opt::Comptime),
1496        library.functions(),
1497    );
1498    let stmts: Vec<Stmt> = match resolved {
1499        Some(rw) => rw.to_vec(),
1500        None => stmts,
1501    };
1502    let stmts = crate::optimize::optimize_program(
1503        stmts,
1504        &imperative_expr_arena,
1505        &stmt_arena,
1506        &mut interner,
1507        &opt_config,
1508    );
1509    // C fixes no order among an operator's operands; LOGOS evaluates them left to right. A lent element or field
1510    // becomes a binding the call points at, stored back after it.
1511    let effects = crate::codegen_c::call_effects(&stmts);
1512    let stmts = crate::optimize::sequence::sequence_operands(
1513        stmts,
1514        crate::ast_map::Arenas {
1515            exprs: &imperative_expr_arena,
1516            stmts: &stmt_arena,
1517            types: &type_expr_arena,
1518        },
1519        &mut interner,
1520        effects,
1521    );
1522    // Consume the same guarded-region versioning pass Rust runs immediately before emission. It is
1523    // the last shared AST rewrite: the C-only monomorphizer below specializes this tree while
1524    // preserving the proof facts on the equivalent expressions it creates.
1525    let type_env = crate::analysis::check_program_located(&stmts, &interner, &codegen_registry)
1526        .map_err(|e| ParseError {
1527            kind: e.to_parse_error_kind(&interner, &stmts),
1528            span: crate::token::Span::default(),
1529        })?;
1530    let stmts = crate::optimize::version::version_stmts(
1531        stmts,
1532        crate::ast_map::Arenas {
1533            exprs: &imperative_expr_arena,
1534            stmts: &stmt_arena,
1535            types: &type_expr_arena,
1536        },
1537        &type_env,
1538        &interner,
1539        &opt_config,
1540    );
1541    // C has no generics and no built-in `Option`: the proof-bearing program becomes the concrete one
1542    // it stands for — one function per (generic function, type arguments) it calls, one registered
1543    // type per applied generic, and `some`/`none` as instances of the core `Option` enum.
1544    let mono = crate::monomorphize::monomorphize(
1545        &stmts,
1546        &codegen_registry,
1547        &mut interner,
1548        crate::ast_map::Arenas {
1549            exprs: &imperative_expr_arena,
1550            stmts: &stmt_arena,
1551            types: &type_expr_arena,
1552        },
1553        crate::monomorphize::Options { lower_option: true },
1554    )
1555    .map_err(|m| ParseError {
1556        kind: crate::error::ParseErrorKind::Custom(format!(
1557            "the C backend cannot compile this program: {m}"
1558        )),
1559        span: crate::token::Span::default(),
1560    })?;
1561    let (stmts, codegen_registry, instances) = (mono.stmts, mono.registry, mono.instances);
1562    if std::env::var_os("LOGOS_DEBUG_C_TILE").is_some() {
1563        use logicaffeine_language::ast_depth::{for_each_node, Visited};
1564        let mut tile_facts = 0usize;
1565        for_each_node(&stmts, |node| {
1566            if let Visited::Expr(expr) = node {
1567                tile_facts += usize::from(crate::optimize::facts::holds_expr(
1568                    crate::optimize::facts::Fact::TileLegal,
1569                    expr,
1570                ));
1571            }
1572        });
1573        eprintln!("C TileLegal expressions before emission: {tile_facts}");
1574    }
1575    let c_code = crate::optimize::with_backend_lowering(|| {
1576        crate::codegen_c::codegen_monomorphic_program_c(
1577            &stmts,
1578            &codegen_registry,
1579            &interner,
1580            &policy_registry,
1581            &instances,
1582            tier,
1583        )
1584    });
1585    gate.verify().map_err(|m| ParseError {
1586        kind: crate::error::ParseErrorKind::Custom(m),
1587        span: crate::token::Span::default(),
1588    })?;
1589    Ok(c_code)
1590}
1591
1592/// Compile LOGOS source DIRECTLY to a self-contained WebAssembly module — no rustc, no cargo,
1593/// no wasm-bindgen, no toolchain. Uses the SAME front-end as [`vm_outcome`]
1594/// ([`crate::ui_bridge::with_parsed_program`] → [`crate::vm::Compiler::compile_with_types`]),
1595/// so the emitted module runs the IDENTICAL bytecode the VM does; the AOT WebAssembly backend
1596/// then lowers the whole program to `.wasm`.
1597///
1598/// Returns the bytes of a `.wasm` file. A program outside the backend's supported fragment
1599/// yields a [`ParseError`] carrying the backend's `unsupported …` reason — the corpus lock
1600/// turns that into a tracked, shrinking gap rather than a silent skip.
1601/// Compile `source` to LOGOS Silicon ISA assembly (Tier 5, `--emit isa`) — the register-VM opcode set
1602/// AS the native chip ISA, every instruction annotated with its reversibility contract (see
1603/// [`crate::vm::isa`]). Uses the SAME Oracle-optimized bytecode the other tiers run, so the emitted
1604/// ISA is the exact program the interpreter/VM/JIT/AOT execute, now as silicon.
1605pub fn compile_to_isa(source: &str) -> Result<String, ParseError> {
1606    fn custom(msg: String) -> ParseError {
1607        ParseError {
1608            kind: crate::error::ParseErrorKind::Custom(msg),
1609            span: crate::token::Span::default(),
1610        }
1611    }
1612    refuse_exact(source, "Silicon ISA", "the LOGOS chip")?;
1613    crate::ui_bridge::with_parsed_program_checked(source, |parsed, interner| {
1614        let (stmts, types, _policies) = parsed?;
1615        let oracle = crate::optimize::oracle_analyze_with(stmts, interner);
1616        let program = crate::vm::Compiler::compile_with_oracle_located(
1617            stmts,
1618            interner,
1619            Some(types),
1620            Some(oracle),
1621        )?;
1622        Ok(crate::vm::isa::emit_isa(&program))
1623    })
1624}
1625
1626/// The sentence the `tier`, which holds no value of the exact extension, refuses `source` with when the extension
1627/// reaches it: the extension's values live in the value runtime a compiled program links beside it, which `holder`
1628/// cannot call. `None` for a program the extension never reaches, and for one that does not compile here: the
1629/// tier's own compile reports that, located, and checks the program's `## Require` against what fires in it.
1630pub(crate) fn exact_refusal(source: &str, tier: &str, holder: &str) -> Option<String> {
1631    let reaches = crate::ui_bridge::with_parsed_program(source, |parsed, interner| {
1632        let Ok((stmts, types, _policies)) = parsed else {
1633            return false;
1634        };
1635        crate::vm::Compiler::compile_with_oracle_located(stmts, interner, Some(types), None)
1636            .is_ok_and(|program| crate::vm::tower::reaches(&program))
1637    });
1638    reaches.then(|| {
1639        format!("the {tier} does not run the exact extension: its values live in a runtime {holder} cannot call")
1640    })
1641}
1642
1643/// [`exact_refusal`] as the error a compile entry stops with.
1644pub(crate) fn refuse_exact(source: &str, tier: &str, holder: &str) -> Result<(), ParseError> {
1645    match exact_refusal(source, tier, holder) {
1646        None => Ok(()),
1647        Some(sentence) => Err(ParseError {
1648            kind: crate::error::ParseErrorKind::Custom(sentence),
1649            span: crate::token::Span::default(),
1650        }),
1651    }
1652}
1653
1654/// ★ THE CANONICAL `source → CompiledProgram` PATH ★ — the single bytecode-IR entry every backend and every
1655/// invariant lock reuses (no drift). This is the RAW-AST lowering (Oracle-analyzed, but WITHOUT the AOT
1656/// `optimize_program` lattice) — identical to what `vm_outcome`/`compile_to_riscv`/`compile_to_wasm` compile
1657/// today, so `program_outcome(compile_to_program(src)) == vm_outcome(src)` by construction. The optimized
1658/// variant (`optimize_program` applied → the finalized source-of-truth IR every backend will lower) is added
1659/// with the optimizer-soundness lock; see the refactor plan.
1660// ★ NOT HOST-ONLY, AND THE GATE HERE BROKE THE WEB BUILD. This was `#[cfg(not(target_arch = "wasm32"))]`,
1661// but nothing in the body needs a host: `ui_bridge` → `optimize` → `vm::Compiler` is pure computation, and
1662// all three modules build for wasm32 (the `vm` module IS the browser's engine). Meanwhile
1663// `refuse_browser_surface` — which is NOT gated, and must not be, because `compile_to_rust` and
1664// `compile_to_c` are what the web app's roadmap page and benchmarks call — invokes this function. So on
1665// wasm32 the crate referenced a function that did not exist and `apps/logicaffeine_web` could not build.
1666//
1667// Gating the CALLERS instead would compile, and would be wrong: it deletes `compile_to_rust` from the web
1668// build (the site uses it) and silently drops the DOM refusal in the browser, so the guard would hold on
1669// the host and vanish exactly where a `## Page` program is most likely to be compiled.
1670pub fn compile_to_program(source: &str) -> Result<crate::vm::CompiledProgram, ParseError> {
1671    fn custom(msg: String) -> ParseError {
1672        ParseError {
1673            kind: crate::error::ParseErrorKind::Custom(msg),
1674            span: crate::token::Span::default(),
1675        }
1676    }
1677    crate::ui_bridge::with_parsed_program_checked(source, |parsed, interner| {
1678        let (stmts, types, _policies) = parsed?;
1679        let oracle = crate::optimize::oracle_analyze_with(stmts, interner);
1680        Ok(crate::vm::Compiler::compile_with_oracle_located(
1681            stmts,
1682            interner,
1683            Some(types),
1684            Some(oracle),
1685        )?)
1686    })
1687}
1688
1689/// ★ Phase 1 — compile to C by lowering the bytecode `CompiledProgram` directly (the `codegen_c::from_program`
1690/// Op-walker), the bytecode-IR-as-source-of-truth path that REPLACES the AST-based `compile_to_c`. It lowers
1691/// the OPTIMIZED IR (`compile_to_program_optimized`) — the SAME `optimize_program` the AST `compile_to_c` runs,
1692/// honoring the LOGOS source's `## No`/`## Require` opt decorators — so the whole AOT optimizer lattice
1693/// (constant-fold, SCCP, egraph, LICM, deforest, supercompile, closed-form, bound_version) reaches the C. One
1694/// pristine, optimal pipeline: source → (opt flags honored) optimized bytecode → Op-walker → C. Grown op-by-op
1695/// behind `c_bytecode_lock`; returns a typed `Err` on any op not yet lowered (callers fall back to the AST
1696/// emitter until the Op-walker covers the corpus).
1697#[cfg(not(target_arch = "wasm32"))]
1698pub fn compile_to_c_via_bytecode(source: &str) -> Result<String, ParseError> {
1699    compile_to_c_via_bytecode_with_knobs(
1700        source,
1701        &crate::codegen_c::concurrency::SchedulerKnobs::default(),
1702    )
1703}
1704
1705/// Optimized-bytecode→C compilation with stage-separated optimization
1706/// evidence. Fallbacks to the syntax-tree C tiers are recorded explicitly.
1707#[cfg(not(target_arch = "wasm32"))]
1708pub fn compile_to_c_via_bytecode_traced(
1709    source: &str,
1710) -> Result<(String, crate::optimization::BackendOptimizationTrace), ParseError> {
1711    crate::optimize::begin_backend_trace(crate::optimization::OptimizationBackend::CBytecode);
1712    let result = compile_to_c_via_bytecode(source);
1713    let trace = crate::optimize::end_backend_trace().expect("backend trace was just started");
1714    result.map(|c| (c, trace))
1715}
1716
1717/// The bytecode→C walker with an explicit [`SchedulerKnobs`](crate::codegen_c::concurrency::SchedulerKnobs) for the concurrency path — the tunable
1718/// deterministic scheduler (ready-queue `policy`, `workers`, `clock`, channel capacity, `seed`). A
1719/// non-concurrency program ignores the knobs (its sequential C is knob-independent). The default-knob
1720/// wrapper is [`compile_to_c_via_bytecode`]; a determinism lock drives this with each policy to prove the
1721/// knob is a real, output-preserving tunable on the determinate corpus.
1722///
1723/// [`SchedulerKnobs`]: crate::codegen_c::concurrency::SchedulerKnobs
1724#[cfg(not(target_arch = "wasm32"))]
1725pub fn compile_to_c_via_bytecode_with_knobs(
1726    source: &str,
1727    knobs: &crate::codegen_c::concurrency::SchedulerKnobs,
1728) -> Result<String, ParseError> {
1729    compile_to_c_via_bytecode_offloaded_with_knobs(source, knobs, |_, _| Vec::new()).map(|o| o.c)
1730}
1731
1732/// The bytecode→C walker with an offload table: `offloads` chooses, from the optimized program and the interner that
1733/// names its functions, the functions a device may answer
1734/// ([`crate::codegen_c::from_program::compile_program_to_c_offloaded`]). An empty table is
1735/// [`compile_to_c_via_bytecode`].
1736#[cfg(not(target_arch = "wasm32"))]
1737pub fn compile_to_c_via_bytecode_offloaded(
1738    source: &str,
1739    offloads: impl FnOnce(
1740        &crate::vm::CompiledProgram,
1741        &Interner,
1742    ) -> Vec<crate::codegen_c::from_program::Offload>,
1743) -> Result<crate::codegen_c::from_program::OffloadedC, ParseError> {
1744    compile_to_c_via_bytecode_offloaded_with_knobs(
1745        source,
1746        &crate::codegen_c::concurrency::SchedulerKnobs::default(),
1747        offloads,
1748    )
1749}
1750
1751#[cfg(not(target_arch = "wasm32"))]
1752fn compile_to_c_via_bytecode_offloaded_with_knobs(
1753    source: &str,
1754    knobs: &crate::codegen_c::concurrency::SchedulerKnobs,
1755    offloads: impl FnOnce(
1756        &crate::vm::CompiledProgram,
1757        &Interner,
1758    ) -> Vec<crate::codegen_c::from_program::Offload>,
1759) -> Result<crate::codegen_c::from_program::OffloadedC, ParseError> {
1760    use crate::codegen_c::from_program::OffloadedC;
1761    fn custom(msg: String) -> ParseError {
1762        ParseError {
1763            kind: crate::error::ParseErrorKind::Custom(msg),
1764            span: crate::token::Span::default(),
1765        }
1766    }
1767    with_optimized_program(source, true, |stmts, interner, program, policies| {
1768        refuse_unlinkable(program, interner, Backend::C).map_err(custom)?;
1769        let table = offloads(program, interner);
1770        let on_the_host = |why: &str| {
1771            table
1772                .iter()
1773                .map(|o| (o.func, why.to_string()))
1774                .collect::<Vec<_>>()
1775        };
1776        // The Op-walker now lowers EVERY reachable bytecode op natively — the offline `Net*`/`Crdt*` ops,
1777        // runtime authorization (`CheckPolicy`), AND the last holdout, the real-socket TCP client (`Tcp`, over
1778        // the `C_TCP_RUNTIME` POSIX socket runtime). So this delegation gate is EMPTY: `program_needs_astc_
1779        // delegation` always returns `false` today. The guard is kept as the honest self-documenting seam — a
1780        // future op that genuinely cannot be lowered would re-open it (and the census locks would force it).
1781        if crate::codegen_c::program_needs_astc_delegation(program) {
1782            crate::optimize::mark_backend_fallback(
1783                crate::optimization::OptimizationBackend::CAst,
1784                "bytecode op outside the C Op-walker",
1785            );
1786            return Ok(OffloadedC {
1787                c: compile_to_c(source)?,
1788                kept: on_the_host("the program is lowered from its syntax tree"),
1789            });
1790        }
1791        // A concurrency program (channels / tasks / `Await the first of` / virtual-time `Sleep`) needs a
1792        // task to SUSPEND at a blocking op and RESUME later — which the flat Op-walker cannot express. So
1793        // it is lowered by the stepped tier (each task a step function over a heap frame, the scheduler core
1794        // the CUDA tier runs), tuned by `SchedulerKnobs` (default = the oracle's `Fifo` / `workers=1` /
1795        // `Logical`). The sequential surface stays on the bytecode walker.
1796        if crate::codegen_c::program_uses_concurrency(stmts) {
1797            crate::optimize::mark_backend_fallback(
1798                crate::optimization::OptimizationBackend::CAst,
1799                "concurrency requires the stepped syntax-tree C tier",
1800            );
1801            Ok(OffloadedC {
1802                c: compile_to_c_stepped_with_knobs(source, knobs)?,
1803                kept: on_the_host("a concurrent program runs on the stepped tier"),
1804            })
1805        } else {
1806            // The Op-walker lowers the whole sequential surface + the offline Net/CRDT ops + `CheckPolicy`
1807            // (the policy registry supplies each `Check`'s condition, as the VM's `policy_ctx` does).
1808            crate::optimize::with_backend_lowering(|| {
1809                crate::codegen_c::from_program::compile_program_to_c_offloaded(
1810                    program,
1811                    Some((interner, policies)),
1812                    &table,
1813                )
1814            })
1815            .map_err(custom)
1816        }
1817    })
1818}
1819
1820/// ★ THE FINALIZED, OPTIMIZED SOURCE-OF-TRUTH IR ★ — `compile( optimize_program( resolve_divisions(AST) ) )`.
1821/// This is the exact front-end `compile_to_c`/`compile_to_rust` run (prelude + `## No`/`## Require` decorators
1822/// + division resolution + the full AOT optimizer lattice) — but it STOPS at the `CompiledProgram` instead of
1823/// emitting a target. It is the one IR every backend will lower in the source-of-truth architecture, and the
1824/// object the invariants pin: `VM(opt P) = program_outcome(compile_to_program_optimized(P))`. Today the bytecode
1825/// backends (riscv/wasm/fabric) compile the RAW AST and miss this whole lattice — so this is also the primitive
1826/// that lets them GAIN it. Mirrors `compile_to_c` (`src/compile.rs`) up to the codegen step.
1827#[cfg(not(target_arch = "wasm32"))]
1828pub fn compile_to_program_optimized(
1829    source: &str,
1830) -> Result<crate::vm::CompiledProgram, ParseError> {
1831    with_optimized_program(source, false, |_stmts, _interner, program, _policies| {
1832        Ok(program.clone())
1833    })
1834}
1835
1836/// [`compile_to_program_optimized`] with each function's name, in function order: what a consumer that
1837/// reports on functions by name (the accelerator region discovery) reads beside the program.
1838#[cfg(not(target_arch = "wasm32"))]
1839pub fn compile_to_program_optimized_named(
1840    source: &str,
1841) -> Result<(crate::vm::CompiledProgram, Vec<String>), ParseError> {
1842    with_optimized_program(source, false, |_stmts, interner, program, _policies| {
1843        let names = program
1844            .functions
1845            .iter()
1846            .map(|f| interner.resolve(f.name).to_string())
1847            .collect();
1848        Ok((program.clone(), names))
1849    })
1850}
1851
1852/// Run the full front-end (prelude + decorators + division resolution + the AOT optimizer lattice) to the
1853/// finalized `CompiledProgram`, then hand `finish` the OPTIMIZED `stmts`, the `interner`, and the `program`
1854/// — all borrowed while the front-end's arenas are still live. The one seam a backend needs when it lowers
1855/// from the bytecode IR yet still wants the optimized AST (e.g. the walker's concurrency branch, which asks it
1856/// whether the program has tasks). `compile_to_program_optimized` is the trivial `finish` that
1857/// just clones out the program.
1858#[cfg(not(target_arch = "wasm32"))]
1859fn with_optimized_program<T>(
1860    source: &str,
1861    require_static_types: bool,
1862    finish: impl FnOnce(
1863        &[Stmt],
1864        &Interner,
1865        &crate::vm::CompiledProgram,
1866        &crate::analysis::PolicyRegistry,
1867    ) -> Result<T, ParseError>,
1868) -> Result<T, ParseError> {
1869    fn custom(msg: String) -> ParseError {
1870        ParseError {
1871            kind: crate::error::ParseErrorKind::Custom(msg),
1872            span: crate::token::Span::default(),
1873        }
1874    }
1875    let prelude_src = crate::loader::apply_prelude(source);
1876    let pruned = crate::loader::keep_reachable_functions(source, prelude_src.as_ref());
1877    let source = pruned.as_str();
1878    let library = crate::loader::LibraryProvenance::of(source);
1879
1880    let mut interner = Interner::new();
1881    let mut lexer = Lexer::new(source, &mut interner);
1882    let tokens = lexer.tokenize();
1883
1884    let (type_registry, policy_registry) = {
1885        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
1886        let result = discovery.run_full();
1887        (result.types, result.policies)
1888    };
1889
1890    let mut world_state = WorldState::new();
1891    let expr_arena = Arena::new();
1892    let term_arena = Arena::new();
1893    let np_arena = Arena::new();
1894    let sym_arena = Arena::new();
1895    let role_arena = Arena::new();
1896    let pp_arena = Arena::new();
1897    let stmt_arena: Arena<Stmt> = Arena::new();
1898    let _compile_facts = crate::optimize::facts::scope();
1899    let imperative_expr_arena: Arena<Expr> = Arena::new();
1900    let type_expr_arena: Arena<TypeExpr> = Arena::new();
1901
1902    let ast_ctx = AstContext::with_types(
1903        &expr_arena,
1904        &term_arena,
1905        &np_arena,
1906        &sym_arena,
1907        &role_arena,
1908        &pp_arena,
1909        &stmt_arena,
1910        &imperative_expr_arena,
1911        &type_expr_arena,
1912    );
1913
1914    let mut parser = Parser::new(
1915        tokens,
1916        &mut world_state,
1917        &mut interner,
1918        ast_ctx,
1919        type_registry,
1920    );
1921    let stmts = parser.parse_program()?;
1922    let (opt_config, gate) = crate::optimize::install_decorators(
1923        crate::optimization::OptimizationConfig::from_env(),
1924        &parser.program_opt_flags(),
1925        parser.required_optimizations(),
1926    );
1927    let codegen_registry = parser.into_type_registry();
1928    // Memoization is an AST rewrite, so it must run before the shared
1929    // optimizer.  Optimizer facts are keyed to the exact arena nodes they
1930    // prove; rewriting the tree after optimization silently discarded
1931    // `InBounds`, `RawIntOp`, and `TileLegal` before bytecode/JIT lowering.
1932    // Direct C already uses this ordering.  Keeping the optimizer last makes
1933    // its proof-bearing output the source consumed by every bytecode tier.
1934    let stmts = crate::optimize::memoize_for_explicit_lowering(
1935        stmts,
1936        &imperative_expr_arena,
1937        &stmt_arena,
1938        &mut interner,
1939        &opt_config,
1940    );
1941    let resolved = crate::resolve_program::resolve_program(
1942        &stmts,
1943        crate::ast_map::Arenas {
1944            exprs: &imperative_expr_arena,
1945            stmts: &stmt_arena,
1946            types: &type_expr_arena,
1947        },
1948        &mut interner,
1949        opt_config.is_on(crate::optimization::Opt::Comptime),
1950        library.functions(),
1951    );
1952    let stmts: Vec<Stmt> = match resolved {
1953        Some(rw) => rw.to_vec(),
1954        None => stmts,
1955    };
1956    let stmts = crate::optimize::optimize_program(
1957        stmts,
1958        &imperative_expr_arena,
1959        &stmt_arena,
1960        &mut interner,
1961        &opt_config,
1962    );
1963    // Rust runs the shared guarded-region versioner immediately before its
1964    // emitter.  Bytecode-derived backends must run the same proof pass before
1965    // compiling their final IR; otherwise TileLegal/InBounds reach Rust alone
1966    // and C-bytecode/JIT silently keep exact counters and bounds checks.
1967    // The VM retains its dynamic value semantics. A type environment is a
1968    // prerequisite for this proof-driven optimization, not for executing
1969    // bytecode. Typed backends still require the same static validation.
1970    let type_env = match crate::analysis::check_program_located(&stmts, &interner, &codegen_registry) {
1971        Ok(env) => Some(env),
1972        Err(e) if require_static_types => {
1973            return Err(ParseError {
1974                kind: e.to_parse_error_kind(&interner, &stmts),
1975                span: crate::token::Span::default(),
1976            });
1977        }
1978        Err(_) => None,
1979    };
1980    let stmts = if let Some(type_env) = type_env {
1981        crate::optimize::version::version_stmts(
1982            stmts,
1983            crate::ast_map::Arenas {
1984                exprs: &imperative_expr_arena,
1985                stmts: &stmt_arena,
1986                types: &type_expr_arena,
1987            },
1988            &type_env,
1989            &interner,
1990            &opt_config,
1991        )
1992    } else {
1993        stmts
1994    };
1995    // The optimized AST → the finalized bytecode IR. The `CompiledProgram` owns its op stream (no arena refs),
1996    // so it outlives this function's arenas.
1997    let oracle = crate::optimize::oracle_analyze_with(&stmts, &interner);
1998    let program = crate::optimize::with_backend_lowering(|| {
1999        crate::vm::Compiler::compile_with_oracle_located(
2000            &stmts,
2001            &interner,
2002            Some(&codegen_registry),
2003            Some(oracle),
2004        )
2005    })?;
2006    gate.verify().map_err(|m| ParseError {
2007        kind: crate::error::ParseErrorKind::Custom(m),
2008        span: crate::token::Span::default(),
2009    })?;
2010    finish(&stmts, &interner, &program, &policy_registry)
2011}
2012
2013/// Compile to **RV64GC assembly text** — the LOGOS → RISC-V AOT tier. Lowers from the SAME
2014/// Oracle-optimized bytecode the VM/WASM tiers use (so DivPow2 / bounds-elim forms match), then
2015/// [`crate::codegen_riscv::codegen_program_riscv`] emits the assembly. A RISC-V GCC assembles+links it;
2016/// `qemu-user` runs it byte-for-byte identical to the VM. Returns a `Custom` `ParseError` when the
2017/// program uses an op/shape outside the currently-lowered fragment (a sound refusal, never wrong code).
2018pub fn compile_to_riscv(source: &str) -> Result<String, ParseError> {
2019    fn custom(msg: String) -> ParseError {
2020        ParseError {
2021            kind: crate::error::ParseErrorKind::Custom(msg),
2022            span: crate::token::Span::default(),
2023        }
2024    }
2025    crate::ui_bridge::with_parsed_program_checked(source, |parsed, interner| {
2026        let (stmts, types, policies) = parsed?;
2027        let oracle = crate::optimize::oracle_analyze_with(stmts, interner);
2028        let mut program = crate::vm::Compiler::compile_with_oracle_located(
2029            stmts,
2030            interner,
2031            Some(types),
2032            Some(oracle),
2033        )?;
2034        // Coalesce the VM compiler's register-move cascades before lowering. RISC-V asm has no
2035        // downstream optimizing assembler (unlike the C tier, whose gcc does this), so without the
2036        // peephole it ships the `Set a to b. Set b to t.` five-move idiom verbatim every iteration.
2037        // Semantics-preserving IR→IR (peephole_soundness_lock proves `== VM`).
2038        crate::vm::peephole::peephole(&mut program);
2039        refuse_unlinkable(&program, interner, Backend::RiscV).map_err(custom)?;
2040        crate::codegen_riscv::codegen_program_riscv(&program, &policies, interner)
2041            .map_err(|e| custom(e.to_string()))
2042    })
2043}
2044
2045/// Compile to a **single-Tensix-core TT-Metalium program** — the LOGOS → Tenstorrent
2046/// AOT tier. The compute body is the C translation ([`compile_to_c`], byte-for-byte ≡
2047/// the VM), wrapped by [`crate::codegen_tt`] as a data-movement kernel on one baby
2048/// RISC-V core (`RISCV_0`) plus a host orchestrator. Uses the SAME Oracle-optimized
2049/// bytecode to scan for ops outside the single-baby-core fragment — CONCURRENCY
2050/// (channels/tasks/select need a `ucontext` scheduler; the mesh tier lowers those) —
2051/// returning a `Custom` `ParseError`, a sound refusal, never wrong code. OFFLINE
2052/// networking rides the newlib-clean C net runtime on-core. Returns the emitted
2053/// [`crate::codegen_tt::TtArtifact`].
2054#[cfg(feature = "codegen")]
2055pub fn compile_to_tenstorrent(source: &str) -> Result<crate::codegen_tt::TtArtifact, ParseError> {
2056    fn custom(msg: String) -> ParseError {
2057        ParseError {
2058            kind: crate::error::ParseErrorKind::Custom(msg),
2059            span: crate::token::Span::default(),
2060        }
2061    }
2062    refuse_exact(source, "Tenstorrent tier", "a Tensix core")?;
2063    // Scan the Oracle-optimized bytecode for ops outside the single-baby-core fragment FIRST, so a
2064    // concurrency program gets the backend's specific refusal rather than the C tier's generic error
2065    // — a sound refusal, never wrong code. (Offline networking is served on-core, not refused.)
2066    let refusal = crate::ui_bridge::with_parsed_program_checked(source, |parsed, interner| {
2067        let (stmts, types, _policies) = parsed?;
2068        let oracle = crate::optimize::oracle_analyze_with(stmts, interner);
2069        let program = crate::vm::Compiler::compile_with_oracle_located(
2070            stmts,
2071            interner,
2072            Some(types),
2073            Some(oracle),
2074        )?;
2075        Ok(crate::codegen_tt::unsupported_reason(&program))
2076    })?;
2077    if let Some(reason) = refusal {
2078        return Err(custom(format!(
2079            "tenstorrent AOT backend: unsupported {reason}"
2080        )));
2081    }
2082    // The C oracle is the proven ≡VM compute body the kernel runs.
2083    let oracle_c = compile_to_c(source)?;
2084    Ok(crate::codegen_tt::wrap_as_tt(&oracle_c))
2085}
2086
2087/// Compile to a **mixed-signal analog artifact** — the LOGOS → analog spatial fabric tier
2088/// ([`crate::codegen_ana`]). Scans the Oracle-optimized bytecode through the fail-closed
2089/// [`crate::codegen_ana::analog_refusal`] gate FIRST: concurrency/networking, a program with no
2090/// float dataflow, or float inputs without declared ranges each get a NAMED `analog backend:`
2091/// refusal — a correct artifact or a typed refusal, never a silently-wrong circuit.
2092#[cfg(feature = "codegen")]
2093pub fn compile_to_analog(source: &str) -> Result<crate::codegen_ana::AnalogArtifact, ParseError> {
2094    fn custom(msg: String) -> ParseError {
2095        ParseError {
2096            kind: crate::error::ParseErrorKind::Custom(msg),
2097            span: crate::token::Span::default(),
2098        }
2099    }
2100    refuse_exact(source, "analog tier", "an analog fabric")?;
2101    let gate = crate::ui_bridge::with_parsed_program_checked(source, |parsed, interner| {
2102        let (stmts, types, _policies) = parsed?;
2103        let ranges = crate::codegen_ana::assumed_ranges_in(stmts, interner);
2104        let oracle = crate::optimize::oracle_analyze_with(stmts, interner);
2105        let program = crate::vm::Compiler::compile_with_oracle_located(
2106            stmts,
2107            interner,
2108            Some(types),
2109            Some(oracle),
2110        )?;
2111        let refusal = crate::codegen_ana::analog_refusal(&program, &ranges);
2112        // The region unit is the FIRST function — its params are the DAC inputs.
2113        let region = stmts.iter().find_map(|s| match s {
2114            logicaffeine_language::ast::stmt::Stmt::FunctionDef { name, .. } => {
2115                Some(interner.resolve(*name).to_string())
2116            }
2117            _ => None,
2118        });
2119        Ok((refusal, region))
2120    })?;
2121    let target = crate::codegen_ana::AnalogTarget::sky130_fpaa();
2122    match gate {
2123        // Concurrency/networking (and float-without-ranges) refuse coarse; a NoAnalogRegion
2124        // verdict with a region function present falls through to the lane dispatcher, which
2125        // decides float vs certified-exact integer (panic-safe, typed refusals).
2126        (Some(crate::codegen_ana::AnaLowerError::NoAnalogRegion), Some(fn_name))
2127        | (None, Some(fn_name)) => crate::codegen_ana::try_region(source, &fn_name, &target)
2128            .map(|(_lane, art)| art)
2129            .map_err(|e| custom(format!("analog backend: {e}"))),
2130        (Some(e), _) => Err(custom(format!("analog backend: {e}"))),
2131        (None, None) => Err(custom(
2132            "analog backend: no region function found (the analog region unit is a float function)"
2133                .to_string(),
2134        )),
2135    }
2136}
2137
2138/// Compile to the **Plasticine** target — the open RDU (Prabhakar et al., ISCA 2017), the LOGOS → Plasticine
2139/// lane. The region unit is the FIRST function, which must be a counted range loop (Spatial `Foreach` over
2140/// `lo..=hi`): it is lowered through the certified [`crate::codegen_sva::fabric_rtl::LoopFabric`], modeled as
2141/// one metapipeline stage under Spatial's II definition, placed on the ISCA'17 checkerboard, anchored to the
2142/// VM at sample inputs, SAT-certified when its body is ALU-only, and emitted as Spatial source. Any other
2143/// shape gets a NAMED `plasticine backend:` refusal — an artifact or a typed refusal, never a wrong model.
2144#[cfg(feature = "codegen")]
2145pub fn compile_to_plasticine(
2146    source: &str,
2147) -> Result<crate::codegen_sva::plasticine_report::PlasticineArtifact, ParseError> {
2148    fn custom(msg: String) -> ParseError {
2149        ParseError {
2150            kind: crate::error::ParseErrorKind::Custom(msg),
2151            span: crate::token::Span::default(),
2152        }
2153    }
2154    refuse_exact(source, "Plasticine tier", "a dataflow fabric")?;
2155    let region = crate::ui_bridge::with_parsed_program_checked(source, |parsed, interner| {
2156        let (stmts, _types, _policies) = parsed?;
2157        Ok(stmts.iter().find_map(|s| match s {
2158            Stmt::FunctionDef { name, params, .. } => {
2159                Some((interner.resolve(*name).to_string(), params.len()))
2160            }
2161            _ => None,
2162        }))
2163    })?;
2164    let Some((fn_name, arity)) = region else {
2165        return Err(custom("plasticine backend: no region function found (the Plasticine region unit is a counted-loop function)".to_string()));
2166    };
2167    // The VM anchor's sample inputs: small, distinct, positive.
2168    let params: Vec<i64> = (0..arity).map(|i| 8 + i as i64).collect();
2169    let target = crate::codegen_sva::plasticine::PlasticineTarget::isca17();
2170    crate::codegen_sva::plasticine_report::lower_counted_loop(source, &fn_name, &params, &target)
2171        .map_err(|e| custom(format!("plasticine backend: {e}")))
2172}
2173
2174/// Which RDU lane an artifact came through — chosen by program shape ([`crate::spatial::lower::rdu_lanes::lane_of`]),
2175/// printed by name.
2176#[cfg(feature = "codegen")]
2177pub use crate::spatial::lower::rdu_lanes::RduLane;
2178
2179/// What `largo emit rdu` writes: the `logos.spatial.neutral` v2 envelope, the placement text, the
2180/// certificate (rechecked against the program, carrying the envelope's digest), the MODELED report naming
2181/// the lane, and — when the lane produced one — the Spatial source.
2182#[cfg(feature = "codegen")]
2183#[derive(Clone, Debug)]
2184pub struct RduArtifact {
2185    pub chip: &'static str,
2186    pub lane: RduLane,
2187    pub neutral_json: String,
2188    pub placement_txt: String,
2189    pub certificate_json: String,
2190    pub report_json: String,
2191    pub spatial_source: Option<String>,
2192    /// The SDK-gated artifact itself, for a bridge to ingest (`None` for a lane whose envelope carries no
2193    /// spatial program).
2194    pub neutral: Option<crate::spatial::lower::NeutralArtifact>,
2195    /// What a lane could not do, by name (the Spatial emitter's refusal, …).
2196    pub notes: Vec<String>,
2197}
2198
2199pub const RDU_EMIT_REPORT_SCHEMA: &str = "logos.rdu.emit_report";
2200
2201/// A streamed model bundle's manifest, the model constants it binds from files no checkpoint holds — each at the
2202/// path the manifest binds it at, relative to the bundle — which are written with it, and the LOGOS text of the whole
2203/// cut of the model's one program the bundle deploys (`program.lg`), which the manifest's `program` line identifies.
2204pub struct RduBundle {
2205    pub manifest: String,
2206    pub constants: Vec<(String, Vec<u8>)>,
2207    pub program: String,
2208}
2209
2210/// One lowered program of a streamed model bundle, rendered to the files a bundle directory holds.
2211pub struct RduProgramFiles {
2212    pub dir: String,
2213    pub neutral_json: String,
2214    pub placement_txt: String,
2215    pub certificate_json: String,
2216}
2217
2218pub const RDU_STREAMED_MANIFEST_SCHEMA: &str = "logos.rdu.streamed_manifest";
2219
2220/// A step deployment's shape: a KV cache of `ctx` positions per sequence, `batch` sequences per step, over `tp`
2221/// chips of tensor parallelism — and, with `prefill: Some(chunk)`, a step that PREFILLS `chunk` tokens of one sequence
2222/// (their hidden states stacked, the sequence's state taken row by row: the model's prefill cut) instead of decoding one
2223/// token per sequence.
2224#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2225pub struct StepShape {
2226    pub ctx: usize,
2227    pub batch: usize,
2228    pub tp: usize,
2229    pub prefill: Option<usize>,
2230}
2231
2232/// A model the RDU bundle is compiled from: its spec, the name the manifest gives it, which of the weights the author
2233/// declares Q8_0 its checkpoint stores Q8_0, and the per-frequency factors of a rotation that reads them
2234/// (`rope_freqs.weight`).
2235pub struct RduModel<'a> {
2236    pub spec: crate::model::spec::ModelSpec,
2237    pub name: String,
2238    pub storage: crate::spatial::streamed::Storage<'a>,
2239    pub rope_factors: Option<Vec<f64>>,
2240}
2241
2242impl<'a> RduModel<'a> {
2243    /// A built-in configuration of Qwen3.8, whose checkpoint stores every projection Q8_0.
2244    pub fn qwen38(cfg: &crate::codegen_cuda::qwen38::Qwen38Cfg) -> RduModel<'static> {
2245        RduModel { spec: cfg.spec(), name: "Qwen3.8".to_string(), storage: crate::spatial::streamed::Storage::AllQ8, rope_factors: None }
2246    }
2247
2248    /// The model a checkpoint holds, named `name`: its spec, each weight read as the checkpoint stores it, and the
2249    /// frequency factors its rotations read (`rope_freqs.weight`) when it carries them.
2250    pub fn from_checkpoint(name: &str, checkpoint: &'a mut dyn crate::model::Checkpoint) -> Result<RduModel<'a>, String> {
2251        use crate::model::bind::{values, Binding, View};
2252        use crate::model::reference::WeightSource;
2253        let spec = crate::model::spec::ModelSpec::from_source(&*checkpoint).map_err(|e| match e {
2254            crate::model::spec::SpecError::UnknownArchitecture(_) => format!("{name}: {}", crate::model::triage::refusal(&*checkpoint)),
2255            e => format!("{name}: {e:?}"),
2256        })?;
2257        let rope_factors = if WeightSource::has(&*checkpoint, "rope_freqs.weight") {
2258            let b = Binding { tensor: "rope_freqs.weight".to_string(), view: View::Same };
2259            Some(values(&b, &mut *checkpoint).map_err(|e| format!("{name}: rope_freqs.weight: {e}"))?)
2260        } else {
2261            None
2262        };
2263        let source: &'a dyn WeightSource = checkpoint;
2264        Ok(RduModel { spec, name: name.to_string(), storage: crate::spatial::streamed::Storage::Checkpoint(source), rope_factors })
2265    }
2266}
2267
2268/// Lower a model to the RDU as the chip would run it: ONE program per layer kind plus the head, each lowered,
2269/// certified and handed to `sink` in turn, and a manifest binding every layer to its kind. Returns the
2270/// manifest JSON and the model constants the bundle ships: a decode deployment's rotary caches
2271/// (`{weights_dir}/Rcos.f`, `{weights_dir}/Rsin.f`, one pair per rotation the layers turn by —
2272/// [`rope_tables`](crate::model::bind::rope_tables) at `ctx` positions, little-endian f32), which every step reads at
2273/// its positions so the host hands in only tokens and positions.
2274///
2275/// Layers with equal specs lower to one dataflow (`spatial::streamed::layer_kinds`), so the whole forward —
2276/// however deep — is a program per kind and the head. Programs are rendered and sunk one at a time, so the caller
2277/// never holds more than one program's JSON. The weights stay outside the programs: the manifest names, for
2278/// every layer, which file each of its kind's tensors is read from, and each tensor's role.
2279///
2280/// `decode: Some(StepShape { ctx, batch, tp })` lowers the DECODE deployment instead of the authored forward: an
2281/// embedding program, layer kinds whose attention appends to and reads a KV cache of `ctx` positions, and a head that
2282/// emits the next token (see `streamed::lower_decode_streamed`) — for `batch` sequences per step, every
2283/// weight read once for all of them, when `batch > 1` (`streamed::lower_batched_decode_streamed`); over
2284/// `tp` chips, each layer kind one program with every chip its own heads and a slice of every weight, when `tp > 1`
2285/// (`streamed::lower_tp_decode_streamed`, the manifest naming each chip tensor's slice).
2286pub fn compile_model_to_rdu_streamed(
2287    rdu: &RduModel,
2288    chip: crate::spatial::rdu_chip::RduChip,
2289    weights_dir: &str,
2290    decode: Option<StepShape>,
2291    mut sink: impl FnMut(RduProgramFiles) -> std::io::Result<()>,
2292) -> Result<RduBundle, String> {
2293    use crate::model::program::{written_in, written_split, Cut};
2294    use crate::spatial::lower::rdu::{certificate_summary, RduSpatialBackend};
2295    use crate::spatial::lower::{SpatialArtifact, SpatialBackend};
2296    use crate::spatial::streamed::rebind;
2297    use crate::spatial::streamed::{
2298        lower_batched_decode_streamed, lower_batched_tp_decode_streamed, lower_decode_streamed,
2299        lower_forward_streamed, lower_prefill_streamed, lower_tp_decode_streamed, StreamedReject,
2300    };
2301    let (spec, storage) = (&rdu.spec, rdu.storage);
2302    crate::model::author::check(spec).map_err(|e| format!("{}: {e}", rdu.name))?;
2303
2304    let facts = chip.facts();
2305    let target = facts.spatial_target();
2306    let model = match decode {
2307        None => lower_forward_streamed(spec, storage, &target, |s| s.to_string()),
2308        Some(StepShape { ctx, batch: 1, tp: 1, prefill: Some(chunk) }) => lower_prefill_streamed(spec, storage, ctx, chunk, &target, |s| s.to_string()),
2309        Some(StepShape { batch, tp, prefill: Some(chunk), .. }) => Err(StreamedReject {
2310            program: "bundle".into(),
2311            why: format!("a prefill chunk ({chunk} tokens) is one sequence on one chip — not {batch} sequences over {tp} chips"),
2312        }),
2313        Some(StepShape { ctx, batch: 1, tp: 1, prefill: None }) => lower_decode_streamed(spec, storage, ctx, &target, |s| s.to_string()),
2314        Some(StepShape { ctx, batch, tp: 1, prefill: None }) => lower_batched_decode_streamed(spec, storage, ctx, batch, &target, |s| s.to_string()),
2315        Some(StepShape { ctx, batch: 1, tp, prefill: None }) => lower_tp_decode_streamed(spec, storage, ctx, tp, &target, |s| s.to_string()),
2316        Some(StepShape { ctx, batch, tp, prefill: None }) => lower_batched_tp_decode_streamed(spec, storage, ctx, batch, tp, &target, |s| s.to_string()),
2317    }
2318    .map_err(|e| format!("rdu backend: {}: {e}", rdu.name))?;
2319    // The weight files: the tensors the model declares with one. Carried state (the KV caches, the Gated-DeltaNet
2320    // memories and conv rings) and the compiler's own tensors have none; a chip's slice is read from its full
2321    // tensor's file.
2322    let ((_, f32w, q8w), _) = match decode {
2323        None => written_in(spec, Cut::Forward, weights_dir),
2324        Some(StepShape { ctx, batch: 1, .. }) => written_in(spec, Cut::Decode { ctx }, weights_dir),
2325        Some(StepShape { ctx, batch, .. }) => written_in(spec, Cut::Batch { rows: batch, ctx }, weights_dir),
2326    };
2327    // The whole cut of the model's one program the bundle deploys, the program its embedding, layers and head are
2328    // cuts of: the identity a CUDA lane or an engine program compiled from the same cut records too.
2329    let (whole_text, whole) = match decode {
2330        None => {
2331            let ((text, _, _), id) = written_in(spec, Cut::Forward, weights_dir);
2332            (text, id)
2333        }
2334        Some(StepShape { ctx, batch: 1, tp: 1, prefill: Some(rows) }) => {
2335            let ((text, _, _), id) = written_in(spec, Cut::Prefill { rows, ctx }, weights_dir);
2336            (text, id)
2337        }
2338        Some(StepShape { ctx, batch: 1, tp: 1, prefill: None }) => {
2339            let ((text, _, _), id) = written_in(spec, Cut::Decode { ctx }, weights_dir);
2340            (text, id)
2341        }
2342        Some(StepShape { ctx, batch, tp: 1, .. }) => {
2343            let ((text, _, _), id) = written_in(spec, Cut::Batch { rows: batch, ctx }, weights_dir);
2344            (text, id)
2345        }
2346        Some(StepShape { ctx, batch, tp, .. }) => {
2347            let cut = if batch == 1 { Cut::Decode { ctx } } else { Cut::Batch { rows: batch, ctx } };
2348            let ((text, _, _, _), id) =
2349                written_split(spec, cut, weights_dir, tp).map_err(|e| format!("rdu backend: {} over {tp} chips: {e}", rdu.name))?;
2350            (text, id)
2351        }
2352    };
2353    let file_of = |var: &str| -> Option<String> {
2354        f32w.get(var)
2355            .map(|(path, _)| path.clone())
2356            .or_else(|| q8w.get(var).cloned())
2357    };
2358    // A tensor a section updates in place is `state` only when a step carries it to the next — what a deployment
2359    // allocates once for the session; a table the step assembles whole is one of the step's activations.
2360    let role_of = |t: &crate::spatial::ir::TensorDecl,
2361                   carried: &std::collections::BTreeSet<String>| match t.role {
2362        crate::spatial::ir::TensorRole::State if !carried.contains(&t.name) => {
2363            "activation".to_string()
2364        }
2365        r => format!("{r:?}").to_lowercase(),
2366    };
2367    let none = std::collections::BTreeSet::new();
2368    // A chip's tensor names its chip and, when it is a slice of a checkpoint or carried-state tensor, the full tensor,
2369    // its file, and the rows or columns of it the chip loads.
2370    let bindings = |program: &crate::spatial::ir::SpatialProgram,
2371                    rename: &dyn Fn(&str) -> String,
2372                    tp: Option<&crate::spatial::tensor_parallel::TpManifest>,
2373                    carried: &std::collections::BTreeSet<String>|
2374     -> Vec<serde_json::Value> {
2375        program
2376            .tensors
2377            .iter()
2378            .map(|t| {
2379                let to = rename(&t.name);
2380                // A weight read as it is stored Q8_0 is two tensors of its checkpoint file: the int8 values (`K × N`) and one
2381                // fp32 scale per 32 rows of each column (`K/32 × N`), which the host repacks from the file's blocks.
2382                let (stored, repack) = match crate::spatial::passes::from_q8::stored_part(&to) {
2383                    Some((w, part)) => (w.to_string(), Some(part.repack())),
2384                    None => (to.clone(), None),
2385                };
2386                let mut entry = serde_json::json!({ "program": t.name, "layer": to, "file": file_of(&stored), "role": role_of(t, carried) });
2387                if let Some(r) = repack {
2388                    entry["repack"] = serde_json::json!(r);
2389                }
2390                if let Some(chip) = t.chip {
2391                    entry["chip"] = serde_json::json!(chip.0);
2392                }
2393                if let Some(s) = tp.and_then(|m| m.slices.get(&t.name)) {
2394                    let of = rename(&s.of);
2395                    entry["slice"] = serde_json::json!({ "of": of, "file": file_of(&of), "axis": s.axis, "ranges": s.ranges, "of_shape": s.of_shape });
2396                }
2397                // A chip's Q8_0 plane is the same rows or columns of the FULL weight's plane: the values at the weight's
2398                // own coordinates, the scales at one row per 32 of them (a row slice folds only in whole Q8_0 blocks).
2399                let plane = crate::spatial::passes::from_q8::stored_part(&t.name).and_then(|(w, part)| tp.and_then(|m| m.slices.get(w)).map(|s| (s, part)));
2400                if let Some((s, part)) = plane {
2401                    use crate::spatial::passes::from_q8::{stored_name, Q8Part, Q8_BLOCK};
2402                    use crate::spatial::tensor_parallel::SliceAxis;
2403                    let of = rename(&s.of);
2404                    let (ranges, of_shape): (Vec<(usize, usize)>, (usize, usize)) = match (part, s.axis) {
2405                        (Q8Part::Values, _) => (s.ranges.clone(), s.of_shape),
2406                        (Q8Part::Scales, SliceAxis::Rows) => (s.ranges.iter().map(|(a, n)| (a / Q8_BLOCK, n / Q8_BLOCK)).collect(), (s.of_shape.0 / Q8_BLOCK, s.of_shape.1)),
2407                        (Q8Part::Scales, SliceAxis::Cols) => (s.ranges.clone(), (s.of_shape.0 / Q8_BLOCK, s.of_shape.1)),
2408                    };
2409                    entry["slice"] = serde_json::json!({ "of": stored_name(&of, part), "file": file_of(&of), "repack": part.repack(), "axis": s.axis, "ranges": ranges, "of_shape": of_shape });
2410                }
2411                entry
2412            })
2413            .collect()
2414    };
2415
2416    let mut render = |dir: &str,
2417                      program: &crate::spatial::ir::SpatialProgram|
2418     -> Result<(u64, bool), String> {
2419        let artifact = match RduSpatialBackend::with_facts(facts.clone()).lower(program) {
2420            Ok(SpatialArtifact::SdkGated(a)) => a,
2421            other => {
2422                return Err(format!(
2423                "rdu backend: {dir}: the backend did not produce an SDK-gated artifact: {other:?}"
2424            ))
2425            }
2426        };
2427        // The backend proved the certificate by rechecking the one the program carries, or derived it; a derived one is
2428        // rechecked here, so every certificate a bundle ships has been rechecked against its program.
2429        let rechecked = artifact.rechecked || artifact.certificate.recheck(program);
2430        let mut cert = certificate_summary(&artifact.certificate);
2431        cert["digest_hex"] =
2432            serde_json::json!(format!("{:016x}", artifact.certificate.schedule_digest));
2433        cert["rechecked"] = serde_json::json!(rechecked);
2434        let digest = artifact.certificate.schedule_digest;
2435        sink(RduProgramFiles {
2436            dir: dir.to_string(),
2437            neutral_json: artifact.json,
2438            placement_txt: artifact.pretty,
2439            certificate_json: format!("{}\n", serde_json::to_string_pretty(&cert).expect("JSON")),
2440        })
2441        .map_err(|e| format!("rdu backend: writing {dir}: {e}"))?;
2442        Ok((digest, rechecked))
2443    };
2444
2445    let embed = match &model.embed {
2446        Some(p) => {
2447            let (digest, rechecked) = render("embed", p)?;
2448            let program = model.embed_identity.map(|id| id.line());
2449            Some(
2450                serde_json::json!({ "dir": "embed", "program": program, "schedule_digest": format!("{digest:016x}"), "rechecked": rechecked, "tensors": bindings(p, &|n| n.to_string(), None, &none) }),
2451            )
2452        }
2453        None => None,
2454    };
2455    let mut kinds = Vec::new();
2456    for k in &model.kinds {
2457        let dir = k.name.replace(' ', "_");
2458        let (digest, rechecked) = render(&dir, &k.program)?;
2459        kinds.push(serde_json::json!({
2460            "name": k.name, "dir": dir, "representative_layer": k.representative, "program": k.identity.line(),
2461            "schedule_digest": format!("{digest:016x}"), "rechecked": rechecked,
2462            "sections": k.program.sections.len(), "stages": k.program.stages.len(),
2463        }));
2464    }
2465    let (head_digest, head_rechecked) = render("head", &model.head)?;
2466    let layers: Vec<serde_json::Value> = model
2467        .layers
2468        .iter()
2469        .map(|b| {
2470            let kind = &model.kinds[b.kind];
2471            let mut map: HashMap<&str, &str> = HashMap::with_capacity(b.tensors.len());
2472            for (from, to) in &b.tensors {
2473                map.entry(from.as_str()).or_insert(to.as_str());
2474            }
2475            let (rep, layer) = (kind.representative, b.layer);
2476            let rename = |n: &str| {
2477                map.get(n)
2478                    .map(|to| to.to_string())
2479                    .unwrap_or_else(|| rebind(n, rep, layer))
2480            };
2481            let tensors = bindings(&kind.program, &rename, kind.tp.as_ref(), &kind.carried);
2482            serde_json::json!({ "layer": b.layer, "kind": b.kind, "program": b.identity.line(), "tensors": tensors })
2483        })
2484        .collect();
2485    let mut manifest = serde_json::json!({
2486        "schema": RDU_STREAMED_MANIFEST_SCHEMA,
2487        "version": 1,
2488        "chip": chip.as_str(),
2489        "target": target.name,
2490        "model": { "name": rdu.name, "arch": spec.arch, "layers": spec.layers.len(), "d": spec.d, "vocab": spec.vocab },
2491        "form": if decode.is_some() { "decode" } else { "forward" },
2492        "program": whole.line(),
2493        "provenance": crate::spatial::fit::PROVENANCE_MODELED,
2494        "no_speed_claim": true,
2495        "kinds": kinds,
2496        "head": { "dir": "head", "program": model.head_identity.line(), "schedule_digest": format!("{head_digest:016x}"), "rechecked": head_rechecked, "tensors": bindings(&model.head, &|n| n.to_string(), None, &none) },
2497        "layers": layers,
2498    });
2499    // Where the host allocates each carried state: the SRAM each chip keeps for it beside the largest program's own
2500    // footprint, or HBM/DDR — per state tensor of each program, once for every layer that runs the program.
2501    let r = &model.residency;
2502    let tier_name = |t: &crate::spatial::ir::TensorSpace| match t {
2503        crate::spatial::ir::TensorSpace::Sram => "sram",
2504        crate::spatial::ir::TensorSpace::Hbm => "hbm",
2505        crate::spatial::ir::TensorSpace::Dram => "ddr",
2506    };
2507    let program_of = |name: &str| -> Option<&crate::spatial::ir::SpatialProgram> {
2508        match name {
2509            "embed" => model.embed.as_ref(),
2510            "head" => Some(&model.head),
2511            kind => model
2512                .kinds
2513                .iter()
2514                .find(|k| k.name == kind)
2515                .map(|k| &k.program),
2516        }
2517    };
2518    let role_name = |c: &crate::spatial::residency::StateClass| {
2519        let t = program_of(&c.program).and_then(|p| p.tensors.iter().find(|t| t.name == c.tensor));
2520        match t.map(|t| {
2521            (
2522                t.role,
2523                file_of(&c.tensor).is_some()
2524                    || crate::spatial::passes::from_q8::stored_part(&c.tensor).is_some(),
2525            )
2526        }) {
2527            Some((
2528                crate::spatial::ir::TensorRole::Param | crate::spatial::ir::TensorRole::Input,
2529                true,
2530            )) => "weight",
2531            Some((r, _)) => match r {
2532                crate::spatial::ir::TensorRole::Input => "input",
2533                crate::spatial::ir::TensorRole::Output => "output",
2534                crate::spatial::ir::TensorRole::Param => "constant",
2535                crate::spatial::ir::TensorRole::Activation => "activation",
2536                crate::spatial::ir::TensorRole::State => "table",
2537            },
2538            None => "tensor",
2539        }
2540    };
2541    manifest["residency"] = serde_json::json!({
2542        "provenance": crate::spatial::fit::PROVENANCE_MODELED,
2543        "sram_bytes_per_chip": r.sram_bytes,
2544        "hbm_bytes_per_chip": r.hbm_bytes,
2545        "reserve_bytes": r.reserve.iter().map(|(c, b)| (c.to_string(), *b)).collect::<std::collections::BTreeMap<_, _>>(),
2546        "states": r.placed.iter().map(|(c, tier)| serde_json::json!({
2547            "program": c.program, "tensor": c.tensor, "chip": c.chip, "instances": c.instances,
2548            "bytes": c.bytes, "moved_per_step": c.moved, "tier": tier_name(tier),
2549        })).collect::<Vec<_>>(),
2550        "off_chip": r.off_chip.iter().map(|(c, tier)| serde_json::json!({
2551            "program": c.program, "tensor": c.tensor, "role": role_name(c), "chip": c.chip, "instances": c.instances,
2552            "bytes": c.bytes, "moved_per_step": c.moved, "tier": tier_name(tier),
2553        })).collect::<Vec<_>>(),
2554    });
2555    // A decode bundle serves every step: the host supplies each sequence's token and position, and allocates the
2556    // carried state (every `state` tensor, one set per sequence) once, zeroed, for the session.
2557    if let (
2558        Some(StepShape {
2559            ctx,
2560            batch,
2561            tp,
2562            prefill,
2563        }),
2564        Some(embed),
2565    ) = (decode, embed)
2566    {
2567        manifest["ctx"] = serde_json::json!(ctx);
2568        manifest["batch"] = serde_json::json!(batch);
2569        manifest["tensor_parallel"] = serde_json::json!(tp);
2570        // What a host hands this bundle, or takes from it, when another chip prefills or decodes the sequence.
2571        manifest["handoff"] = crate::spatial::handoff::contract(spec, ctx).map_err(|e| e.to_string())?.to_json();
2572        // A prefill bundle fills one sequence's state — the decode bundle's, by name — from a chunk of its prompt.
2573        if let Some(chunk) = prefill {
2574            manifest["form"] = serde_json::json!("prefill");
2575            manifest["chunk"] = serde_json::json!(chunk);
2576        }
2577        // The plan the chips and the model imply at this context, beside the shape this bundle was compiled at.
2578        manifest["serving_plan"] = match crate::codegen_cuda::qwen38::Qwen38Cfg::from_spec(spec) {
2579            Ok(cfg) => match crate::spatial::fit::qwen38_serving_plan(&cfg, &facts, ctx) {
2580                Ok(p) => serde_json::to_value(p).expect("JSON"),
2581                Err(why) => serde_json::json!({ "refused": why }),
2582            },
2583            Err(_) => serde_json::json!({ "refused": format!("the serving plan sizes the Qwen3.5/3.8 hybrid, not {} (CHIP-5)", spec.arch) }),
2584        };
2585        // A stacked step's token ids are one vector; a batch's sequences each bring a position, a chunk's rows the first.
2586        manifest["runtime_inputs"] = match (prefill, batch) {
2587            (None, 1) => serde_json::json!(["tok", "pos"]),
2588            (Some(_), _) => serde_json::json!(["toks", "pos_s0"]),
2589            (None, rows) => serde_json::json!(std::iter::once("toks".to_string())
2590                .chain((0..rows).map(|b| format!("pos_s{b}")))
2591                .collect::<Vec<_>>()),
2592        };
2593        manifest["embed"] = embed;
2594    }
2595    let constants = match decode {
2596        None => Vec::new(),
2597        Some(StepShape { ctx, .. }) => {
2598            use crate::model::bind::{rope_tables, rotations, RotaryTable};
2599            use crate::model::spec::RopeScaling;
2600            let le = |v: Vec<f64>| v.into_iter().flat_map(|x| (x as f32).to_le_bytes()).collect::<Vec<u8>>();
2601            let mut constants = Vec::new();
2602            for (rotation, rope) in rotations(spec).into_iter().enumerate() {
2603                let factors = match rope.scaling {
2604                    RopeScaling::Factors => Some(rdu.rope_factors.as_deref().ok_or_else(|| {
2605                        format!("rdu backend: {}: rotation {rotation} reads the checkpoint's frequency factors, and none were given", rdu.name)
2606                    })?),
2607                    _ => None,
2608                };
2609                let (cos, sin) = rope_tables(rope, ctx, factors);
2610                for (is_cos, values) in [(true, cos), (false, sin)] {
2611                    let name = RotaryTable { rotation, cached: true, cos: is_cos }.name();
2612                    constants.push((format!("{weights_dir}/{name}.f"), le(values)));
2613                }
2614            }
2615            // The other tables the host computes: a weightless norm's ones, the attention temperature's rotation.
2616            for table in crate::model::bind::computed_tables(spec) {
2617                let values = crate::model::bind::computed_values(spec, table, ctx).expect("a table the spec gives");
2618                constants.push((format!("{weights_dir}/{}.f", table.name()), le(values)));
2619            }
2620            constants
2621        }
2622    };
2623    Ok(RduBundle {
2624        manifest: format!(
2625            "{}\n",
2626            serde_json::to_string_pretty(&manifest).expect("JSON")
2627        ),
2628        constants,
2629        program: whole_text,
2630    })
2631}
2632
2633/// Compile to the **SambaNova RDU** — ONE front door, three lanes chosen by program shape: the **tensor lane**
2634/// (a tensor program lifted through the spatial IR, placed on the chip's descriptor and certified), the
2635/// **loop lane** (a counted-range-loop function through the Plasticine metapipeline model on the RDU mesh
2636/// descriptor), and the **whole-program lane** (any construct the fabric's decision datapath covers, as
2637/// `Scalar` stages). Every lane ends in the same certified neutral envelope, honestly SDK-gated for the
2638/// vendor config bytes. A tensor program the chip cannot host is refused BY NAME on the tensor lane, never
2639/// handed on; a program no lane hosts gets a `rdu backend:` refusal naming every lane's verdict.
2640#[cfg(feature = "codegen")]
2641pub fn compile_to_rdu(
2642    source: &str,
2643    chip: crate::spatial::rdu_chip::RduChip,
2644) -> Result<RduArtifact, ParseError> {
2645    use crate::codegen_sva::plasticine_report::counted_loop_fabric;
2646    use crate::spatial::lower::rdu_lanes::{
2647        first_function, lane_of, lower_loop_lane, lower_whole_program_lane,
2648    };
2649    use crate::spatial::passes::SpatialReject;
2650    use crate::spatial::pipeline::compile_program_to_spatial;
2651    fn custom(msg: String) -> ParseError {
2652        ParseError {
2653            kind: crate::error::ParseErrorKind::Custom(msg),
2654            span: crate::token::Span::default(),
2655        }
2656    }
2657    refuse_exact(source, "RDU tier", "a dataflow fabric")?;
2658    let facts = chip.facts();
2659    let target = facts.spatial_target();
2660    match lane_of(source) {
2661        // ★ THE WHOLE TENSOR PROGRAM, OR A REFUSAL THAT NAMES THE FRACTION.
2662        //
2663        // This arm used to call `template_from_source`, which lifts the FIRST recognized op and lowers
2664        // THAT — so a 183-statement transformer forward came back exit-0 with a four-file bundle whose
2665        // program was `matmul_1x4x8`, one q-projection, with nothing saying so. A partial lowering
2666        // reported as a whole one is the single failure this campaign cannot ship: the people reading
2667        // these bundles design the chip, and they will ask what it covers.
2668        RduLane::Tensor => match compile_program_to_spatial(source, &target) {
2669            Ok(lowering) => match lowering.program.as_ref() {
2670                Some(program) => {
2671                    let coverage = serde_json::json!({
2672                        "whole_program": true,
2673                        "statements_total": lowering.statements,
2674                        "statements_lowered": lowering.lowered,
2675                        "sections": lowering.sections,
2676                        "state_tensors": lowering.state,
2677                    });
2678                    lower_rdu_spatial(program, chip, &facts, RduLane::Tensor, Some(coverage)).map_err(custom)
2679                }
2680                None => {
2681                    let first: Vec<String> = lowering
2682                        .missing
2683                        .iter()
2684                        .take(3)
2685                        .map(|m| format!("stmt {} `{}` [{}]: {}", m.stmt_index, m.binder, m.kind, m.why))
2686                        .collect();
2687                    Err(custom(format!(
2688                        "rdu backend: tensor lane: the {} cannot host {} of this program's {} tensor statements — REFUSING rather than reporting a fraction as the whole program ({} lowered into {} section(s)). Missing: {}",
2689                        target.name,
2690                        lowering.missing.len(),
2691                        lowering.statements,
2692                        lowering.lowered,
2693                        lowering.sections,
2694                        if first.is_empty() { "(none listed)".to_string() } else { first.join(" | ") },
2695                    )))
2696                }
2697            },
2698            Err(SpatialReject::Parse(e)) => Err(custom(format!("rdu backend: tensor lane: the program does not parse: {e}"))),
2699            Err(SpatialReject::Unrecognized { matmul, elementwise, reduction }) => Err(custom(format!(
2700                "rdu backend: tensor lane: the program declares tensors but no recognizer of the whole-program walk lifts an op from it (matmul: {matmul:?}; elementwise: {elementwise:?}; reduction: {reduction:?})",
2701            ))),
2702            Err(other) => Err(custom(format!("rdu backend: tensor lane: the {} cannot host this tensor program: {other:?}", target.name))),
2703        },
2704        RduLane::Loop => {
2705            let art = lower_loop_lane(source, chip).map_err(|e| custom(format!("rdu backend: loop lane: {e}")))?;
2706            Ok(loop_lane_artifact(art, chip, &facts))
2707        }
2708        RduLane::WholeProgram => match lower_whole_program_lane(source, chip) {
2709            Ok(program) => lower_rdu_spatial(&program, chip, &facts, RduLane::WholeProgram, None).map_err(custom),
2710            Err(reject) => {
2711                let loop_verdict = match first_function(source) {
2712                    Some((name, _)) => match counted_loop_fabric(source, &name) {
2713                        Ok(_) => "a counted loop (would have taken the loop lane)".to_string(),
2714                        Err(why) => format!("`{name}` is not a counted range loop ({why})"),
2715                    },
2716                    None => "no function to take (the loop lane's unit is a counted-loop function)".to_string(),
2717                };
2718                Err(custom(format!(
2719                    "rdu backend: no lane hosts this program on the {} — lane by shape: whole-program; tensor lane: no tensor declared and no tensor op recognized; loop lane: {loop_verdict}; whole-program lane: {reject:?}",
2720                    target.name
2721                )))
2722            }
2723        },
2724    }
2725}
2726
2727/// The loop lane's pieces as the four files: the placement text is the lane's one-screen summary, the
2728/// certificate is the SAT certificate summary bound by digest, the report wraps the modeled Plasticine row,
2729/// and the envelope carries the placement, the row, the Spatial source and the certificate under
2730/// `lane: "loop"` in the v2 shape (the target block from the same facts as every other envelope).
2731#[cfg(feature = "codegen")]
2732fn loop_lane_artifact(
2733    art: crate::spatial::lower::rdu_lanes::LoopLaneArtifact,
2734    chip: crate::spatial::rdu_chip::RduChip,
2735    facts: &crate::spatial::rdu_chip::RduChipFacts,
2736) -> RduArtifact {
2737    use crate::spatial::fit::{ChipBlock, HONESTY, PROVENANCE_MODELED};
2738    use crate::spatial::lower::rdu::{
2739        NeutralTarget, GATED_REASON, NEUTRAL_SCHEMA, NEUTRAL_VERSION,
2740    };
2741    let target = facts.spatial_target();
2742    let parse =
2743        |s: &str| serde_json::from_str::<serde_json::Value>(s).expect("the loop lane renders JSON");
2744    let pretty =
2745        |v: &serde_json::Value| format!("{}\n", serde_json::to_string_pretty(v).expect("JSON"));
2746    let (placement, row, certificate) = (
2747        parse(&art.placement_json),
2748        parse(&art.report_json),
2749        parse(&art.certificate_json),
2750    );
2751    let envelope = serde_json::json!({
2752        "schema": NEUTRAL_SCHEMA,
2753        "version": NEUTRAL_VERSION,
2754        "lane": RduLane::Loop,
2755        "target": NeutralTarget::of(&target, facts),
2756        "sections": [],
2757        "state": [],
2758        "gathers": [],
2759        "ii_report": {},
2760        "loop": {
2761            "function": art.plasticine.fn_name,
2762            "plasticine_target": art.plasticine.target,
2763            "placement": placement,
2764            "row": row,
2765            "spatial_source": art.spatial_source,
2766        },
2767        "certificate": certificate,
2768    });
2769    let report = serde_json::json!({
2770        "schema": RDU_EMIT_REPORT_SCHEMA,
2771        "version": 1,
2772        "provenance": PROVENANCE_MODELED,
2773        "no_speed_claim": true,
2774        "honesty": HONESTY,
2775        "lane": RduLane::Loop,
2776        "chip": chip.as_str(),
2777        "target": target.name,
2778        "gated": GATED_REASON,
2779        "program": { "name": art.plasticine.fn_name, "kind": "counted_loop", "plasticine_target": art.plasticine.target },
2780        "certificate": certificate,
2781        "plasticine_row": row,
2782        "spatial_source": true,
2783        "notes": [],
2784        "chip_facts": ChipBlock::of(facts),
2785    });
2786    RduArtifact {
2787        chip: chip.as_str(),
2788        lane: RduLane::Loop,
2789        neutral_json: serde_json::to_string(&envelope).expect("the loop envelope serializes"),
2790        placement_txt: art.pretty,
2791        certificate_json: art.certificate_json,
2792        report_json: pretty(&report),
2793        spatial_source: Some(art.spatial_source),
2794        neutral: None,
2795        notes: Vec::new(),
2796    }
2797}
2798
2799/// A verified spatial program through the RDU lane: the envelope, the placement text, the rechecked
2800/// certificate, the report with the II view, and the Spatial source when the emitter spells the program.
2801#[cfg(feature = "codegen")]
2802fn lower_rdu_spatial(
2803    program: &crate::spatial::ir::SpatialProgram,
2804    chip: crate::spatial::rdu_chip::RduChip,
2805    facts: &crate::spatial::rdu_chip::RduChipFacts,
2806    lane: RduLane,
2807    coverage: Option<serde_json::Value>,
2808) -> Result<RduArtifact, String> {
2809    use crate::spatial::fit::{
2810        CertificateSummary, ChipBlock, IiBlock, ProgramSummary, HONESTY, PROVENANCE_MODELED,
2811    };
2812    use crate::spatial::lower::rdu::RduSpatialBackend;
2813    use crate::spatial::lower::spatial_lang::emit_spatial_program;
2814    use crate::spatial::lower::{SpatialArtifact, SpatialBackend};
2815    use crate::spatial::rdu_chip::rdu_ii_report;
2816    let target = facts.spatial_target();
2817    let artifact = match RduSpatialBackend::with_facts(facts.clone()).lower(program) {
2818        Ok(SpatialArtifact::SdkGated(a)) => a,
2819        Ok(other) => {
2820            return Err(format!(
2821                "rdu backend: {} lane: the {} lane is SDK-gated, got {other:?}",
2822                lane.as_str(),
2823                target.name
2824            ))
2825        }
2826        Err(e) => {
2827            return Err(format!(
2828                "rdu backend: {} lane: the {} refused the verified program {}: {e:?}",
2829                lane.as_str(),
2830                target.name,
2831                program.name
2832            ))
2833        }
2834    };
2835    // ★ READ THE CERTIFICATE FROM THE CERTIFICATE, NOT FROM ITS OWN SERIALIZATION. The envelope's
2836    // `certificate` block is `certificate_summary(&artifact.certificate)` — built from the value this
2837    // artifact already carries. Recovering it by parsing the whole envelope back into a
2838    // `serde_json::Value` cost 67.7 GB on ONE real-width Qwen3.8 layer (a 2.1 GB neutral string becomes
2839    // a tree ~30x its size), and was the entire reason `largo emit rdu` died at two layers while the
2840    // lowering underneath it handled eight. Measured per phase: lowering 11.6 GB, backend 17.0 GB,
2841    // reparse 84.7 GB. The block is byte-identical either way; only the detour is gone.
2842    let summary = CertificateSummary::of(&artifact, program);
2843    let mut certificate = crate::spatial::lower::rdu::certificate_summary(&artifact.certificate);
2844    certificate["digest_hex"] = serde_json::json!(summary.digest_hex);
2845    certificate["rechecked"] = serde_json::json!(summary.rechecked);
2846    certificate["provenance"] = serde_json::json!(PROVENANCE_MODELED);
2847    let mut notes = Vec::new();
2848    let spatial_source = match emit_spatial_program(program, &target, None) {
2849        Ok(s) => Some(s),
2850        Err(e) => {
2851            notes.push(format!(
2852                "spatial: the Spatial emitter refused {}: {e:?}",
2853                program.name
2854            ));
2855            None
2856        }
2857    };
2858    let pretty =
2859        |v: &serde_json::Value| format!("{}\n", serde_json::to_string_pretty(v).expect("JSON"));
2860    let report = serde_json::json!({
2861        "schema": RDU_EMIT_REPORT_SCHEMA,
2862        "version": 1,
2863        "provenance": PROVENANCE_MODELED,
2864        "no_speed_claim": true,
2865        "honesty": HONESTY,
2866        "lane": lane,
2867        "chip": chip.as_str(),
2868        "target": target.name,
2869        "gated": artifact.reason,
2870        "program": ProgramSummary::of(program, &artifact.census),
2871        "certificate": summary,
2872        "ii_report": IiBlock::of(&rdu_ii_report(program, facts), format!("the emitted program {} on the {}", program.name, target.name)),
2873        // ★ THE COVERAGE BLOCK IS THE HONESTY SURFACE. A bundle that lowered part of a program must SAY
2874        // so in the artifact a vendor engineer reads, not only in the refusal a caller might discard.
2875        "coverage": coverage.unwrap_or(serde_json::json!({ "whole_program": true, "statements_total": 1, "statements_lowered": 1, "sections": 1 })),
2876        "spatial_source": spatial_source.is_some(),
2877        "notes": notes,
2878        "chip_facts": ChipBlock::of(facts),
2879    });
2880    Ok(RduArtifact {
2881        chip: chip.as_str(),
2882        lane,
2883        neutral_json: artifact.json.clone(),
2884        placement_txt: artifact.pretty.clone(),
2885        certificate_json: pretty(&certificate),
2886        report_json: pretty(&report),
2887        spatial_source,
2888        neutral: Some(artifact),
2889        notes,
2890    })
2891}
2892
2893/// Compile to a **single-file CUDA program** — the LOGOS → CUDA AOT tier. Lifts the
2894/// C tier's program body ([`compile_to_c`], byte-for-byte ≡ the VM) onto one GPU thread
2895/// as `__device__` code, over a `printf`-based `Show` preamble, plus a host launcher.
2896/// Uses the SAME Oracle-optimized bytecode to refuse anything outside the integer/bool
2897/// scalar fragment (a GPU thread has no dynamic C runtime), returning a `Custom`
2898/// `ParseError` — a sound refusal, never wrong code. Returns the emitted
2899/// [`crate::codegen_cuda::CudaArtifact`].
2900#[cfg(feature = "codegen")]
2901pub fn compile_to_cuda(source: &str) -> Result<crate::codegen_cuda::CudaArtifact, ParseError> {
2902    fn custom(msg: String) -> ParseError {
2903        ParseError {
2904            kind: crate::error::ParseErrorKind::Custom(msg),
2905            span: crate::token::Span::default(),
2906        }
2907    }
2908    // The C oracle is the proven ≡VM compute body; its program region is lifted to the device. A concurrent
2909    // program's is the stepped tier's — its tasks as step functions under the scheduler core, which a GPU
2910    // thread runs as the host does; a program with no tasks lowers to the same C on either tier.
2911    // `codegen_program_cuda` refuses (typed) any op/value outside the fragment.
2912    refuse_exact(source, "CUDA tier", "a GPU thread")?;
2913    let oracle_c = compile_to_c_stepped(source)?;
2914    crate::ui_bridge::with_parsed_program_checked(source, |parsed, interner| {
2915        let (stmts, types, _policies) = parsed?;
2916        let oracle = crate::optimize::oracle_analyze_with(stmts, interner);
2917        let program = crate::vm::Compiler::compile_with_oracle_located(
2918            stmts,
2919            interner,
2920            Some(types),
2921            Some(oracle),
2922        )?;
2923        crate::codegen_cuda::codegen_program_cuda(&program, &oracle_c)
2924            .map_err(|e| custom(e.to_string()))
2925    })
2926}
2927
2928/// Emit an **int8 weight-stationary GEMM** CUDA program for `O(m×n) = A(m×k)·W(k×n)` — the DP4A
2929/// kernel path of the CUDA tier. Uses a deterministic int8 sample ([`crate::codegen_cuda::sample_gemm_data`])
2930/// baked into the `.cu`; its numerics are anchored to the certified `eval_systolic` reference by
2931/// `cuda_matrix_lock`. Refuses (typed) if the RDU-shaped target lacks int8 weight-stationary GEMM.
2932#[cfg(feature = "codegen")]
2933pub fn compile_to_cuda_gemm(
2934    m: usize,
2935    k: usize,
2936    n: usize,
2937) -> Result<crate::codegen_cuda::CudaGemmArtifact, ParseError> {
2938    fn custom(msg: String) -> ParseError {
2939        ParseError {
2940            kind: crate::error::ParseErrorKind::Custom(msg),
2941            span: crate::token::Span::default(),
2942        }
2943    }
2944    let (weights, acts) = crate::codegen_cuda::sample_gemm_data(m, k, n);
2945    crate::codegen_cuda::emit_int8_gemm(m, k, n, &weights, &acts).map_err(|e| custom(e.to_string()))
2946}
2947
2948/// Genuinely LOWER an ordinary LOGOS matmul program (a triple-loop `C[i][j] += A[i][k]*B[k][j]`) to a tiled
2949/// Tensix matrix-engine compute kernel — the compiler *recognizes* the GEMM idiom (affine index analysis)
2950/// and *generates* the kernel from the program's dimensions, or REFUSES (typed) if the program is not a
2951/// matmul. This is the honest counterpart to the hand-written template kernels: the kernel is a function of
2952/// the source, not a canned string. Returns the recognized `(spec, kernel_cpp)`.
2953pub fn compile_to_tenstorrent_matmul(
2954    source: &str,
2955) -> Result<(crate::codegen_tt::matmul_lower::MatmulSpec, String), String> {
2956    crate::ui_bridge::with_parsed_program(source, |parsed, interner| {
2957        let (stmts, _types, _policies) = parsed?;
2958        let spec = crate::tensor_recognize::recognize_matmul(stmts, interner)
2959            .map_err(|r| format!("not a tile-matmul the compiler can lower: {r:?}"))?;
2960        // The kernel comes from the spatial IR, like every other tensor lowering — see
2961        // `compile_to_tenstorrent_tensor_op` for why the templates this replaced could not be trusted.
2962        // The SPEC is still returned from the recognizer: it is what the source said, and callers
2963        // assert on it directly rather than on the kernel's text.
2964        let target = crate::spatial::target::SpatialTarget::wormhole();
2965        let program = crate::spatial::pipeline::compile_to_spatial(source, &target)
2966            .map_err(|e| format!("not a tile-matmul the compiler can lower: {e:?}"))?;
2967        let kernel = crate::spatial::lower::tensix::TensixBackend::new(target)
2968            .compute_kernel_source(&program)
2969            .map_err(|e| format!("the Tensix printer refused the recognized matmul: {e:?}"))?;
2970        Ok((spec, kernel))
2971    })
2972}
2973
2974/// Genuinely LOWER an ordinary LOGOS matmul program to an optimized **CUDA** GEMM kernel — the CUDA analog
2975/// of [`compile_to_tenstorrent_matmul`]. Recognizes the GEMM idiom with the SAME backend-agnostic
2976/// [`crate::tensor_recognize::recognize_matmul`], extracts `(M,N,K)` from the source, and emits a
2977/// CUDA program whose dims are the program's (a function of the source, not a canned template); a non-matmul
2978/// is REFUSED (typed). Returns the recognized `(spec, kernel_cu)`; the emitted program's checksum equals the
2979/// VM's `Show` byte-for-byte.
2980#[cfg(feature = "codegen")]
2981pub fn compile_to_cuda_matmul(
2982    source: &str,
2983) -> Result<(crate::codegen_tt::matmul_lower::MatmulSpec, String), String> {
2984    compile_to_cuda_matmul_with(source, &crate::codegen_cuda::knobs::CudaKnobs::default())
2985}
2986
2987/// Knob-driven counterpart of [`compile_to_cuda_matmul`] — recognize the matmul, then lower it under an
2988/// explicit [`crate::codegen_cuda::knobs::CudaKnobs`] point in the optimization lattice (e.g. the `Int8Dp4a`
2989/// precision fast path). This is the user-facing surface the CLI/API drive to select a trade-off; a
2990/// non-matmul is refused (typed) regardless of the knobs.
2991#[cfg(feature = "codegen")]
2992pub fn compile_to_cuda_matmul_with(
2993    source: &str,
2994    knobs: &crate::codegen_cuda::knobs::CudaKnobs,
2995) -> Result<(crate::codegen_tt::matmul_lower::MatmulSpec, String), String> {
2996    crate::ui_bridge::with_parsed_program(source, |parsed, interner| {
2997        let (stmts, _types, _policies) = parsed?;
2998        let spec = crate::tensor_recognize::recognize_matmul(stmts, interner)
2999            .map_err(|r| format!("not a matmul the CUDA backend can lower: {r:?}"))?;
3000        let cu = crate::codegen_cuda::matrix::lower_matmul_to_cuda_with(&spec, knobs);
3001        Ok((spec, cu))
3002    })
3003}
3004
3005/// Recognize ANY supported tensor op — `matmul` OR elementwise (`plus`/`hadamard`) — in a LOGOS program and
3006/// lower it to CUDA. The unified accelerator entrypoint: tries the GEMM idiom first, then the elementwise
3007/// idiom, and REFUSES (typed) only if neither is present. This is what closes the tensor-op × backend matrix
3008/// to zero gaps on the CUDA cell.
3009#[cfg(feature = "codegen")]
3010pub fn compile_to_cuda_tensor_op(source: &str) -> Result<String, String> {
3011    crate::ui_bridge::with_parsed_program(source, |parsed, interner| {
3012        let (stmts, _types, _policies) = parsed?;
3013        // ── GUARD: composite blocks must not be claimed by the simple recognizers ──
3014        // A composite tensor op CONTAINS the simpler idioms. `moe` has a softmax over its router logits;
3015        // `attention` has a score GEMV. The recognizers below match those FRAGMENTS, so without this guard a
3016        // Mixture-of-Experts program compiled successfully to a bare `fused_row` softmax kernel over the
3017        // router's E logits — a silent miscompile that reported success and computed almost none of the block.
3018        // `recognize_stages` avoids this by trying the composite recognizers first; this entry point had no
3019        // such ordering. Fail closed: composites lower through the forward path
3020        // (`compile_to_cuda_forward_q8_moe*`), which emits the grouped-expert / attention kernels.
3021        if crate::codegen_cuda::qwen_emit::recognize_moe(stmts).is_some() {
3022            return Err("`moe` is a composite block — lower it with compile_to_cuda_forward_q8_moe*, not the single-op path".to_string());
3023        }
3024        if crate::codegen_cuda::qwen_emit::recognize_attention(stmts).is_some() {
3025            return Err("`attention` is a composite block — lower it through the forward path, not the single-op path".to_string());
3026        }
3027        if let Ok(spec) = crate::tensor_recognize::recognize_matmul(stmts, interner) {
3028            return Ok(crate::codegen_cuda::matrix::lower_matmul_to_cuda(&spec));
3029        }
3030        if let Ok(spec) = crate::tensor_recognize::recognize_elementwise(stmts, interner) {
3031            return Ok(crate::codegen_cuda::matrix::lower_elementwise_to_cuda(
3032                &spec,
3033            ));
3034        }
3035        if let Ok(spec) = crate::tensor_recognize::recognize_swiglu(stmts, interner) {
3036            return Ok(crate::codegen_cuda::fused_row::emit_swiglu(
3037                &spec,
3038                &crate::codegen_cuda::knobs::CudaKnobs::default(),
3039            ));
3040        }
3041        if let Ok(spec) = crate::tensor_recognize::recognize_fused_row(stmts, interner) {
3042            return Ok(crate::codegen_cuda::fused_row::emit_fused_row(
3043                &spec,
3044                &crate::codegen_cuda::knobs::CudaKnobs::default(),
3045            ));
3046        }
3047        Err("not a tensor op the CUDA backend can lower (matmul / elementwise / reduction / swiglu)".to_string())
3048    })
3049}
3050
3051/// Compile a LOGOS fused-row program straight into a **SOL-ExecBench** submission — recognize the op and emit
3052/// the `solution.json` + torch-binding CUDA kernel the benchmark evaluates on the B200. `definition` is the
3053/// problem's Definition name; `inputs`/`output` are the tensor names in Definition order. This closes the loop
3054/// from English LOGOS to a submittable, compiler-generated kernel.
3055#[cfg(feature = "codegen")]
3056pub fn compile_to_sol_solution(
3057    source: &str,
3058    definition: &str,
3059    inputs: &[&str],
3060    output: &str,
3061) -> Result<crate::codegen_cuda::SolSolution, String> {
3062    crate::ui_bridge::with_parsed_program(source, |parsed, interner| {
3063        let (stmts, _types, _policies) = parsed?;
3064        let spec = crate::tensor_recognize::recognize_fused_row(stmts, interner)
3065            .map_err(|r| format!("not a fused-row op the SOL-ExecBench bridge can lower: {r:?}"))?;
3066        Ok(crate::codegen_cuda::emit_fused_row_solution(
3067            &spec,
3068            &crate::codegen_cuda::knobs::CudaKnobs::default(),
3069            definition,
3070            inputs,
3071            output,
3072        ))
3073    })
3074}
3075
3076/// Recognize the ordered tensor-op stages of a MULTI-STAGE forward and lower it to ONE CUDA program that
3077/// chains their parallel kernels through shared device buffers — the whole-forward orchestrator
3078/// ([`crate::codegen_cuda::qwen_emit`]). Where [`compile_to_cuda_tensor_op`] emits ONE op's kernel, this
3079/// composes a sequence (`rmsnorm → matmul → softmax → …`). Refuses (typed) if no stage is recognized.
3080#[cfg(feature = "codegen")]
3081pub fn compile_to_cuda_forward(source: &str) -> Result<String, String> {
3082    compile_to_cuda_forward_weighted(source, &std::collections::HashMap::new())
3083}
3084
3085/// [`compile_to_cuda_forward`] with a WEIGHT MANIFEST: `var name → (file path, float count)`. Any tensor
3086/// variable named in the manifest is loaded from that file by the emitted host at runtime instead of being
3087/// inlined — the mechanism the real-8B forward needs, since the Qwen weights are gigabytes (extracted from the
3088/// GGUF checkpoint). Every other input still uses its literal `Set` values / the deterministic fill.
3089#[cfg(feature = "codegen")]
3090pub fn compile_to_cuda_forward_weighted(
3091    source: &str,
3092    weights: &std::collections::HashMap<String, (String, usize)>,
3093) -> Result<String, String> {
3094    compile_to_cuda_forward_q8(source, weights, &std::collections::HashMap::new())
3095}
3096
3097/// [`compile_to_cuda_forward_weighted`] with an INT8 (Q8_0) weight manifest: any tensor variable named in `q8`
3098/// is loaded resident as int8 quants + f32 block scales, and a matmul against it becomes a dequant-in-kernel
3099/// GEMV. This is what fits real 8B weights on a 12 GB card (8 GB int8, not 32 GB f32) and the DP4A path that
3100/// beats llama.cpp — see [`crate::codegen_cuda::qwen_emit::Q8Ref`].
3101#[cfg(feature = "codegen")]
3102pub fn compile_to_cuda_forward_q8(
3103    source: &str,
3104    weights: &std::collections::HashMap<String, (String, usize)>,
3105    q8: &std::collections::HashMap<String, crate::codegen_cuda::qwen_emit::Q8Ref>,
3106) -> Result<String, String> {
3107    compile_to_cuda_forward_q8_impl(
3108        source,
3109        weights,
3110        q8,
3111        &std::collections::HashMap::new(),
3112        crate::codegen_cuda::qwen_emit::Q8MatKind::Dequant,
3113    )
3114}
3115
3116/// [`compile_to_cuda_forward_q8`] emitting the INT8-**activation** DP4A MMQ kernel for each Q8 matmul: the
3117/// activation is quantized to int8 per 32-block and `__dp4a`'d against the int8 weight (int32 accumulate) —
3118/// the same kernel shape llama.cpp's fast path uses, and the shipped batch-1 default. Numerically the
3119/// int8-activation approximation of the dequant GEMV (small quantization error), not bit-identical; the
3120/// `TwoPassInt8` mode recovers ~14-bit activation exactness at two `__dp4a` per block.
3121#[cfg(feature = "codegen")]
3122pub fn compile_to_cuda_forward_q8_dp4a(
3123    source: &str,
3124    weights: &std::collections::HashMap<String, (String, usize)>,
3125    q8: &std::collections::HashMap<String, crate::codegen_cuda::qwen_emit::Q8Ref>,
3126) -> Result<String, String> {
3127    compile_to_cuda_forward_q8_impl(
3128        source,
3129        weights,
3130        q8,
3131        &std::collections::HashMap::new(),
3132        crate::codegen_cuda::qwen_emit::Q8MatKind::Int8Act,
3133    )
3134}
3135
3136#[cfg(feature = "codegen")]
3137fn compile_to_cuda_forward_q8_impl(
3138    source: &str,
3139    weights: &std::collections::HashMap<String, (String, usize)>,
3140    q8: &std::collections::HashMap<String, crate::codegen_cuda::qwen_emit::Q8Ref>,
3141    moe: &std::collections::HashMap<String, crate::codegen_cuda::qwen_emit::MoeWeights>,
3142    kind: crate::codegen_cuda::qwen_emit::Q8MatKind,
3143) -> Result<String, String> {
3144    compile_to_cuda_forward_holding(source, weights, q8, moe, kind, &[])
3145}
3146
3147/// The older forward of `source` at `kind`'s numerics with the optimizer's steps `held` held back: each kernel it
3148/// would fuse emitted apart, the program the fused one is held equal to.
3149#[cfg(feature = "codegen")]
3150pub fn compile_to_cuda_forward_holding(
3151    source: &str,
3152    weights: &std::collections::HashMap<String, (String, usize)>,
3153    q8: &std::collections::HashMap<String, crate::codegen_cuda::qwen_emit::Q8Ref>,
3154    moe: &std::collections::HashMap<String, crate::codegen_cuda::qwen_emit::MoeWeights>,
3155    kind: crate::codegen_cuda::qwen_emit::Q8MatKind,
3156    held: &[&str],
3157) -> Result<String, String> {
3158    crate::ui_bridge::with_parsed_program(source, |parsed, interner| {
3159        let (stmts, _types, _policies) = parsed?;
3160        let graph = crate::codegen_cuda::qwen_emit::forward_graph_holding(stmts, interner, q8, moe, kind, held)
3161            .map_err(|e| e.to_string())?;
3162        let inits = crate::codegen_cuda::qwen_emit::collect_inits(stmts, interner);
3163        crate::codegen_cuda::qwen_emit::emit_forward(
3164            &graph, &inits, weights, q8, moe, kind, interner,
3165        )
3166        .map_err(|e| e.to_string())
3167    })
3168}
3169
3170/// [`compile_to_cuda_forward_q8`] with a **MoE weight manifest**: any `moe` op in the source lowers to
3171/// grouped-expert CUDA (router GEMV → top-K route → per-expert SwiGLU → weighted combine), its router/gate/up/
3172/// down weights loaded int8-resident from the files named in `moe` (keyed by the block's output variable). This
3173/// is the Qwen3-30B-A3B FFN — the SAME emitter as the dense 8B forward, plus the MoE stage.
3174#[cfg(feature = "codegen")]
3175pub fn compile_to_cuda_forward_q8_moe(
3176    source: &str,
3177    weights: &std::collections::HashMap<String, (String, usize)>,
3178    q8: &std::collections::HashMap<String, crate::codegen_cuda::qwen_emit::Q8Ref>,
3179    moe: &std::collections::HashMap<String, crate::codegen_cuda::qwen_emit::MoeWeights>,
3180) -> Result<String, String> {
3181    compile_to_cuda_forward_q8_impl(
3182        source,
3183        weights,
3184        q8,
3185        moe,
3186        crate::codegen_cuda::qwen_emit::Q8MatKind::Dequant,
3187    )
3188}
3189
3190/// [`compile_to_cuda_forward_q8_moe`] emitting the **sparse top-K, deeply-fused, coalesced int8-activation**
3191/// MoE path — THE SHIPPED DEFAULT: only the K selected experts' weights are gathered per token (the "A3B = 3B
3192/// active" sparsity), and the FFN collapses to three kernels — router+topk, gate+up+SwiGLU fused, down+combine
3193/// fused — so every intermediate stays off HBM. One `__dp4a` per 32-block (single-pass int8 activation) is the
3194/// shortest dependency chain, the fastest batch-1 path at llama.cpp-matched activation precision (the A100
3195/// head-to-head beat: identical greedy token, more tok/s). For logits within ~1e-3 of the f64 reference — the
3196/// correctness mode llama.cpp does not have — use [`compile_to_cuda_forward_q8_moe_exact`].
3197#[cfg(feature = "codegen")]
3198pub fn compile_to_cuda_forward_q8_moe_dp4a(
3199    source: &str,
3200    weights: &std::collections::HashMap<String, (String, usize)>,
3201    q8: &std::collections::HashMap<String, crate::codegen_cuda::qwen_emit::Q8Ref>,
3202    moe: &std::collections::HashMap<String, crate::codegen_cuda::qwen_emit::MoeWeights>,
3203) -> Result<String, String> {
3204    compile_to_cuda_forward_q8_impl(
3205        source,
3206        weights,
3207        q8,
3208        moe,
3209        crate::codegen_cuda::qwen_emit::Q8MatKind::Int8Act,
3210    )
3211}
3212
3213/// [`compile_to_cuda_forward_q8_moe_dp4a`]'s LOGIT-EXACT sibling: the same sparse top-K deeply-fused kernel
3214/// shape, but the activation is quantized TWO-PASS (hi byte + lo residual byte ⇒ ~14-bit) and every block runs
3215/// two `__dp4a` (hi and lo) — ~2× the activation math for logits within ~1e-3 of the f64 reference, so a
3216/// near-tie greedy token does NOT flip (single int8 activation flips it — llama.cpp included). Weights are
3217/// still read once, so the memory-bound cost is unchanged; the measured price of exactness is ~6% tok/s.
3218#[cfg(feature = "codegen")]
3219pub fn compile_to_cuda_forward_q8_moe_exact(
3220    source: &str,
3221    weights: &std::collections::HashMap<String, (String, usize)>,
3222    q8: &std::collections::HashMap<String, crate::codegen_cuda::qwen_emit::Q8Ref>,
3223    moe: &std::collections::HashMap<String, crate::codegen_cuda::qwen_emit::MoeWeights>,
3224) -> Result<String, String> {
3225    compile_to_cuda_forward_q8_impl(
3226        source,
3227        weights,
3228        q8,
3229        moe,
3230        crate::codegen_cuda::qwen_emit::Q8MatKind::TwoPassInt8,
3231    )
3232}
3233
3234/// The Tenstorrent analog of [`compile_to_cuda_tensor_op`]: recognize `matmul` OR elementwise and lower to a
3235/// Tensix compute kernel, refusing (typed) if neither is present. Closes the Tenstorrent cell of the matrix.
3236#[cfg(feature = "codegen")]
3237pub fn compile_to_tenstorrent_tensor_op(source: &str) -> Result<String, String> {
3238    crate::ui_bridge::with_parsed_program(source, |parsed, interner| {
3239        let (stmts, _types, _policies) = parsed?;
3240        // ★ THROUGH THE SPATIAL IR, NOT THE TEMPLATES — AND THIS IS A CORRECTNESS FIX, NOT A TIDY-UP.
3241        //
3242        // The four `lower_*_to_tensix` templates this replaced were not all real. `lower_fused_row_to_tensix`
3243        // declared `cb_w`, `cb_res` and `cb_sq`, included `sqrt.h`, and promised
3244        // `Y = (X+R)/sqrt(mean+eps)·W[i]` in its header comment — while its body did one `reduce_tile` and a
3245        // `pack_tile`. No sqrt, no rsqrt, no multiply, no weight, no residual. One of its format arguments
3246        // was literally `if residual { "" } else { "" }`. Nothing in the tree called it except this function,
3247        // and no test checked its NUMBERS — the row-op locks assert kernel text, so a kernel that computed
3248        // the wrong thing passed them for as long as it contained the word `reduce_tile`.
3249        //
3250        // The IR path is checked the other way round: `spatial_algebra_semantics_lock` compares it against an
3251        // independent statement of the mathematics, and `spatial_tensix_p4_ttsim_lock` runs it on
3252        // Tenstorrent's own simulator against a golden. Six workloads (matmul, elementwise, swiglu, rmsnorm,
3253        // softmax, layernorm) lower this way, from ONE general compute form.
3254        let _ = (stmts, interner);
3255        let target = crate::spatial::target::SpatialTarget::wormhole();
3256        let program = crate::spatial::pipeline::compile_to_spatial(source, &target).map_err(|e| {
3257            format!("not a tensor op the Tenstorrent backend can lower (matmul / elementwise / reduction / swiglu): {e:?}")
3258        })?;
3259        // Kernels only: this returns a KERNEL, and the host's golden would additionally demand fills the
3260        // compiler can reproduce — a requirement that belongs to a runnable bundle, not to a kernel.
3261        crate::spatial::lower::tensix::TensixBackend::new(target)
3262            .compute_kernel_source(&program)
3263            .map_err(|e| format!("the Tensix printer refused the recognized tensor op: {e:?}"))
3264    })
3265}
3266
3267/// Lower a recognized concurrency pattern's value stream to a spatial program: the sends become the input
3268/// tensor's init, the fold becomes a reduction, and the Tensix printer emits the kernels. This is the one
3269/// place the concurrency tier turns a recognized pattern into a PROGRAM — every pattern below reduces to a
3270/// stream of values and a fold over it, which is why none of them needs an emitter of its own any more.
3271#[cfg(feature = "codegen")]
3272fn mesh_program(values: &[i64]) -> Result<crate::spatial::ir::SpatialProgram, String> {
3273    let target = crate::spatial::target::SpatialTarget::wormhole();
3274    let tpl = crate::spatial::passes::from_tensor_op::from_pipe(values, &target)
3275        .map_err(|e| format!("the pattern's value stream does not lower: {e:?}"))?;
3276    crate::spatial::pipeline::run_passes(tpl, &target)
3277        .map_err(|e| format!("the lowered pattern did not survive the passes: {e:?}"))
3278}
3279
3280/// Recognize a producer/consumer pipe program and lower its CONCURRENCY onto the Tensix mesh — the task on
3281/// one baby RISC-V, main on the other, the pipe as a circular buffer. Returns the recognized spec + the
3282/// complete 2-core program, or an error if the program is not the recognized pattern (the caller then falls
3283/// back to the sound single-core refusal). The mesh output is ≡ the VM's deterministic interleaving.
3284pub fn compile_to_tenstorrent_concurrency(
3285    source: &str,
3286) -> Result<
3287    crate::codegen_tt::concurrency_mesh::MeshLowering<
3288        crate::codegen_tt::concurrency_mesh::ConcurrencySpec,
3289    >,
3290    String,
3291> {
3292    crate::ui_bridge::with_parsed_program(source, |parsed, interner| {
3293        let (stmts, _types, _policies) = parsed?;
3294        let spec =
3295            crate::codegen_tt::concurrency_mesh::recognize_producer_consumer(stmts, interner)
3296                .ok_or_else(|| {
3297                    "not a producer/consumer pipe program the mesh tier can lower".to_string()
3298                })?;
3299        let program = Some(mesh_program(&spec.sends)?);
3300        Ok(crate::codegen_tt::concurrency_mesh::MeshLowering { spec, program })
3301    })
3302}
3303
3304/// Recognize a **fan-out** program (N distinct tasks each send one value into a shared pipe; main folds all
3305/// N) and lower its concurrency onto the Tensix mesh — one core per task, main folding via a NoC + semaphore
3306/// barrier. The commutative fold makes the mesh's arrival order irrelevant, so it is ≡VM. Errors if the
3307/// program is not the fan-out pattern (the caller falls back to the sound refusal).
3308pub fn compile_to_tenstorrent_fanout(
3309    source: &str,
3310) -> Result<
3311    crate::codegen_tt::concurrency_mesh::MeshLowering<
3312        crate::codegen_tt::concurrency_mesh::FanoutSpec,
3313    >,
3314    String,
3315> {
3316    crate::ui_bridge::with_parsed_program(source, |parsed, interner| {
3317        let (stmts, _types, _policies) = parsed?;
3318        let spec = crate::codegen_tt::concurrency_mesh::recognize_fanout(stmts, interner)
3319            .ok_or_else(|| "not a fan-out program the mesh tier can lower".to_string())?;
3320        let program = Some(mesh_program(&spec.values)?);
3321        Ok(crate::codegen_tt::concurrency_mesh::MeshLowering { spec, program })
3322    })
3323}
3324
3325/// Recognize a **select** (`Await the first of { Receive … / After … }`) on a ready channel and lower it to
3326/// a single-core program whose non-blocking readiness check reproduces the VM's deterministic arm choice.
3327pub fn compile_to_tenstorrent_select(
3328    source: &str,
3329) -> Result<
3330    crate::codegen_tt::concurrency_mesh::MeshLowering<
3331        crate::codegen_tt::concurrency_mesh::SelectSpec,
3332    >,
3333    String,
3334> {
3335    crate::ui_bridge::with_parsed_program(source, |parsed, interner| {
3336        let (stmts, _types, _policies) = parsed?;
3337        let spec = crate::codegen_tt::concurrency_mesh::recognize_select(stmts, interner)
3338            .ok_or_else(|| "not a select program the mesh tier can lower".to_string())?;
3339        // The channel is READY (main pre-sends before the await), so the VM's deterministic select takes
3340        // the receive arm — and the compiler resolves it the same way rather than emitting a device-side
3341        // readiness check whose answer is already a literal of the source.
3342        let program = Some(mesh_program(&[spec.presend])?);
3343        Ok(crate::codegen_tt::concurrency_mesh::MeshLowering { spec, program })
3344    })
3345}
3346
3347/// Recognize a **racy select** (a task sleeps then sends; main awaits a receive-or-timeout) and lower it to
3348/// a coordinator + task program. The coordinator compares the reported send virtual-time against the
3349/// timeout — the VM's deterministic scheduler rule — so the outcome is ≡VM on both branches, independent of
3350/// real hardware timing.
3351pub fn compile_to_tenstorrent_racy_select(
3352    source: &str,
3353) -> Result<
3354    crate::codegen_tt::concurrency_mesh::MeshLowering<
3355        crate::codegen_tt::concurrency_mesh::RacySelectSpec,
3356    >,
3357    String,
3358> {
3359    crate::ui_bridge::with_parsed_program(source, |parsed, interner| {
3360        let (stmts, _types, _policies) = parsed?;
3361        let spec = crate::codegen_tt::concurrency_mesh::recognize_racy_select(stmts, interner)
3362            .ok_or_else(|| "not a racy select program the mesh tier can lower".to_string())?;
3363        // NOT a real-time race: the VM fires whichever event has the smaller VIRTUAL time, and both
3364        // times are literals of the source. When the send wins, the program is a one-value pipe; when the
3365        // timeout wins the answer is a constant string, which has no dataflow to place.
3366        let program = if spec.send_vtime_ms < spec.timeout_ms {
3367            Some(mesh_program(&[spec.value])?)
3368        } else {
3369            None
3370        };
3371        Ok(crate::codegen_tt::concurrency_mesh::MeshLowering { spec, program })
3372    })
3373}
3374
3375/// Recognize a **dynamic-channel** program (a loop-driven producer feeding the pipe with computed values)
3376/// and lower it to a 2-core program: the producer loops pushing `f(i)` onto a bounded circular buffer; the
3377/// consumer folds the stream. Order-deterministic FIFO ⇒ ≡VM.
3378pub fn compile_to_tenstorrent_dynamic(
3379    source: &str,
3380) -> Result<
3381    crate::codegen_tt::concurrency_mesh::MeshLowering<
3382        crate::codegen_tt::concurrency_mesh::DynamicSpec,
3383    >,
3384    String,
3385> {
3386    crate::ui_bridge::with_parsed_program(source, |parsed, interner| {
3387        let (stmts, _types, _policies) = parsed?;
3388        let spec = crate::codegen_tt::concurrency_mesh::recognize_dynamic_producer(stmts, interner)
3389            .ok_or_else(|| "not a dynamic loop producer the mesh tier can lower".to_string())?;
3390        let program = Some(mesh_program(&spec.values)?);
3391        Ok(crate::codegen_tt::concurrency_mesh::MeshLowering { spec, program })
3392    })
3393}
3394
3395/// Recognize a **multi-task race** (≥2 tasks each sleep then send; main awaits receive-or-timeout) and lower
3396/// it to a coordinator + N-task program. The coordinator collects every task's `(value, send-vtime)`, picks
3397/// the global-minimum send-vtime, and compares it to the timeout — the VM's deterministic winner. ≡VM.
3398pub fn compile_to_tenstorrent_multi_racy(
3399    source: &str,
3400) -> Result<
3401    crate::codegen_tt::concurrency_mesh::MeshLowering<
3402        crate::codegen_tt::concurrency_mesh::RacyMultiSpec,
3403    >,
3404    String,
3405> {
3406    crate::ui_bridge::with_parsed_program(source, |parsed, interner| {
3407        let (stmts, _types, _policies) = parsed?;
3408        let spec = crate::codegen_tt::concurrency_mesh::recognize_multi_racy(stmts, interner)
3409            .ok_or_else(|| "not a multi-task racy select the mesh tier can lower".to_string())?;
3410        // The winner is the globally smallest send virtual time, and it only fires if it beats the
3411        // timeout — the same rule the VM's scheduler applies, evaluated here because every term is a
3412        // literal of the source.
3413        let winner = spec.tasks.iter().min_by_key(|(_, vt)| *vt).copied();
3414        let program = match winner {
3415            Some((value, vt)) if vt < spec.timeout_ms => Some(mesh_program(&[value])?),
3416            _ => None,
3417        };
3418        Ok(crate::codegen_tt::concurrency_mesh::MeshLowering { spec, program })
3419    })
3420}
3421
3422pub fn compile_to_wasm(source: &str) -> Result<Vec<u8>, ParseError> {
3423    compile_to_wasm_with(source, &crate::vm::reach::HostEntries::default())
3424}
3425
3426/// [`compile_to_wasm`] for a host that enters the module by name beyond `main`: the components a
3427/// test mounts at a statement of its own ([`crate::vm::reach::HostEntries`]). A shipped page's
3428/// entries are the default, and its module is exactly the one [`compile_to_wasm`] writes.
3429pub fn compile_to_wasm_with(
3430    source: &str,
3431    entries: &crate::vm::reach::HostEntries,
3432) -> Result<Vec<u8>, ParseError> {
3433    compile_to_wasm_module(source, entries, false)
3434}
3435
3436/// [`compile_to_wasm`] as a check-mode module: the same program through the same pipeline, with the
3437/// heap census exported ([`crate::vm::wasm::assemble_program_checked`]) for a heap test to read
3438/// every true count back through. A shipped page never carries it.
3439pub fn compile_to_wasm_checked(source: &str) -> Result<Vec<u8>, ParseError> {
3440    compile_to_wasm_module(source, &crate::vm::reach::HostEntries::default(), true)
3441}
3442
3443fn compile_to_wasm_module(
3444    source: &str,
3445    entries: &crate::vm::reach::HostEntries,
3446    checked: bool,
3447) -> Result<Vec<u8>, ParseError> {
3448    fn custom(msg: String) -> ParseError {
3449        ParseError {
3450            kind: crate::error::ParseErrorKind::Custom(msg),
3451            span: crate::token::Span::default(),
3452        }
3453    }
3454    // The module lowers concrete code only: the program arrives monomorphic (the VM's own `Option`
3455    // stays built in).
3456    let concrete = crate::monomorphize::Options {
3457        lower_option: false,
3458    };
3459    crate::ui_bridge::with_monomorphic_program_checked(source, concrete, |parsed, interner| {
3460        let (stmts, types, policies) = parsed?;
3461        // Compile with the SAME Oracle the VM/native tier use (`run_to_outcome`), so the AOT receives
3462        // the optimized bytecode — DivPow2 / MagicDivU (magic-reciprocal division) and the Oracle-proven
3463        // bounds-check-elimination forms (IndexUnchecked / SetIndexUnchecked / RegionBoundsGuard). The
3464        // AOT lowers each (division bit-exact to the VM's `magic_eval`; the unchecked forms keep the
3465        // bounds check, a safe superset), so WASM == VM stays exact while the two share one bytecode.
3466        let oracle = crate::optimize::oracle_analyze_with(stmts, interner);
3467        // Located: a refusal of the author's construct reaches the caller AT that construct.
3468        let mut program = crate::vm::Compiler::compile_with_oracle_located(
3469            stmts,
3470            interner,
3471            Some(types),
3472            Some(oracle),
3473        )?;
3474        // Coalesce register-move cascades before lowering — the direct-WASM backend emits final code
3475        // with no downstream optimizing assembler. Semantics-preserving (peephole_soundness_lock ≡ VM).
3476        crate::vm::peephole::peephole(&mut program);
3477        refuse_unlinkable_with(&program, interner, Backend::WebAssembly, entries)
3478            .map_err(custom)?;
3479        let assemble = if checked {
3480            crate::vm::wasm::assemble_program_checked
3481        } else {
3482            crate::vm::wasm::assemble_program_with
3483        };
3484        assemble(&program, &policies, interner, entries).map_err(|e| custom(e.to_string()))
3485    })
3486}
3487
3488/// Compile to WebAssembly in the **OBSERVED profile** (Wave 13): `Note`/`Warn`/
3489/// `Record`/`During` lower to `Op::Obs`, which the WASM backend emits as calls to
3490/// the host `obs(site_id)` import — the browser-tracing analog of the VM's
3491/// observation emission. Returns the module bytes AND the `observation_sites`
3492/// table: the host (which compiled the program) resolves each `site_id` to its
3493/// category / message / span kind. The default [`compile_to_wasm`] stays the
3494/// elided profile, byte-identical to the observation-free program (§0.7).
3495pub fn compile_to_wasm_observed(
3496    source: &str,
3497) -> Result<(Vec<u8>, Vec<crate::vm::ObsSiteDesc>), ParseError> {
3498    fn custom(msg: String) -> ParseError {
3499        ParseError {
3500            kind: crate::error::ParseErrorKind::Custom(msg),
3501            span: crate::token::Span::default(),
3502        }
3503    }
3504    let concrete = crate::monomorphize::Options {
3505        lower_option: false,
3506    };
3507    crate::ui_bridge::with_monomorphic_program(source, concrete, |parsed, interner| {
3508        let (stmts, types, policies) = parsed.map_err(custom)?;
3509        let mut program =
3510            crate::vm::Compiler::compile_observed_located(stmts, interner, Some(types))?;
3511        let sites = program.observation_sites.clone();
3512        // The observed profile keeps `Op::Obs` (its args stay live; `site` indexes the untouched
3513        // observation_sites table), so the peephole only coalesces the move cascades around them.
3514        crate::vm::peephole::peephole(&mut program);
3515        refuse_unlinkable(&program, interner, Backend::WebAssembly).map_err(custom)?;
3516        let wasm = crate::vm::wasm::assemble_program(&program, &policies, interner)
3517            .map_err(|e| custom(e.to_string()))?;
3518        Ok((wasm, sites))
3519    })
3520}
3521
3522/// Compile LOGOS source to a LINKED WebAssembly module that uses the real `logicaffeine_base::BigInt`
3523/// runtime for arbitrary-precision integer arithmetic: an overflowing integer expression
3524/// (`Show 99999999999 * 99999999999`, `Show 2 to the power of 200`) computes the EXACT big number —
3525/// matching the VM's promote-on-overflow — instead of trapping, and `Show` prints its decimal.
3526///
3527/// Unlike [`compile_to_wasm`] (fully self-contained, no toolchain), this is TOOLCHAIN-DEPENDENT: the
3528/// BigInt-aware emitter (`crate::vm::wasm::assemble_program_linked`) produces a RELOCATABLE object that
3529/// is linked against `logicaffeine_base` (compiled once to `wasm32-unknown-unknown`) with the Rust
3530/// toolchain's `rust-lld`. The runtime object is cached per process, so the amortized cost is one link.
3531/// Returns the bytes of a `.wasm` file, or a [`ParseError`] carrying the reason the backend or linker
3532/// declined (an unsupported program shape, or an unavailable toolchain / base wasm32 build).
3533#[cfg(all(feature = "wasm-jit", not(target_arch = "wasm32")))]
3534pub fn compile_to_wasm_linked(source: &str) -> Result<Vec<u8>, ParseError> {
3535    let relocatable = compile_to_wasm_relocatable(source)?;
3536    crate::vm::wasm::link_relocatable_bigint(&relocatable).map_err(|e| ParseError {
3537        kind: crate::error::ParseErrorKind::Custom(e.to_string()),
3538        span: crate::token::Span::default(),
3539    })
3540}
3541
3542/// The RELOCATABLE object [`compile_to_wasm_linked`] hands the linker: the program monomorphized,
3543/// compiled with the optimizer's oracle, peephole-coalesced, checked linkable, lowered by the
3544/// BigInt-aware emitter (`crate::vm::wasm::assemble_program_linked`) and carried with its
3545/// relocations — not yet linked, so a caller can link it against a runtime of its own.
3546#[cfg(all(feature = "wasm-jit", not(target_arch = "wasm32")))]
3547pub fn compile_to_wasm_relocatable(source: &str) -> Result<Vec<u8>, ParseError> {
3548    fn custom(msg: String) -> ParseError {
3549        ParseError {
3550            kind: crate::error::ParseErrorKind::Custom(msg),
3551            span: crate::token::Span::default(),
3552        }
3553    }
3554    let concrete = crate::monomorphize::Options {
3555        lower_option: false,
3556    };
3557    crate::ui_bridge::with_monomorphic_program(
3558        source,
3559        concrete,
3560        |parsed, interner| -> Result<Vec<u8>, ParseError> {
3561            let (stmts, types, policies) = parsed.map_err(custom)?;
3562            let oracle = crate::optimize::oracle_analyze_with(stmts, interner);
3563            let mut program = crate::vm::Compiler::compile_with_oracle_located(
3564                stmts,
3565                interner,
3566                Some(types),
3567                Some(oracle),
3568            )?;
3569            // Same coalescing before the BigInt-linked WASM lowering (no downstream optimizer). ≡ VM.
3570            crate::vm::peephole::peephole(&mut program);
3571            refuse_unlinkable(&program, interner, Backend::WebAssembly).map_err(custom)?;
3572            let module = crate::vm::wasm::assemble_program_linked(&program, &policies, interner)
3573                .map_err(|e| custom(e.to_string()))?;
3574            crate::vm::wasm::module_to_relocatable(&module).map_err(|e| custom(e.to_string()))
3575        },
3576    )
3577}
3578
3579/// Format an `f64` exactly as a `Show` of a `Float` would — i.e. byte-identical to the
3580/// tree-walker / VM (`RuntimeValue::to_display_string`). The direct-WASM host's `print_f64`
3581/// sink uses this so a `Show` of a float matches every other engine. Delegating to the real
3582/// formatter (rather than re-deriving it) makes drift impossible.
3583pub fn display_float_like_logos(f: f64) -> String {
3584    crate::interpreter::RuntimeValue::Float(f).to_display_string()
3585}
3586
3587/// Classify the determinacy of a LOGOS program.
3588///
3589/// Parses `source` and runs the determinacy classifier over the parsed program.
3590/// Pure analysis — no optimization, no codegen. Returns whether the program is
3591/// in the determinate (Kahn-deterministic) or nondeterminate fragment, with the
3592/// nondeterminism witnesses.
3593pub fn classify_source(source: &str) -> Result<crate::concurrency::Determinacy, ParseError> {
3594    let mut interner = Interner::new();
3595    let mut lexer = Lexer::new(source, &mut interner);
3596    let tokens = lexer.tokenize();
3597
3598    let (type_registry, _policy_registry) = {
3599        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
3600        let result = discovery.run_full();
3601        (result.types, result.policies)
3602    };
3603
3604    let mut world_state = WorldState::new();
3605    let expr_arena = Arena::new();
3606    let term_arena = Arena::new();
3607    let np_arena = Arena::new();
3608    let sym_arena = Arena::new();
3609    let role_arena = Arena::new();
3610    let pp_arena = Arena::new();
3611    let stmt_arena: Arena<Stmt> = Arena::new();
3612    let _compile_facts = crate::optimize::facts::scope();
3613    let imperative_expr_arena: Arena<Expr> = Arena::new();
3614    let type_expr_arena: Arena<TypeExpr> = Arena::new();
3615
3616    let ast_ctx = AstContext::with_types(
3617        &expr_arena,
3618        &term_arena,
3619        &np_arena,
3620        &sym_arena,
3621        &role_arena,
3622        &pp_arena,
3623        &stmt_arena,
3624        &imperative_expr_arena,
3625        &type_expr_arena,
3626    );
3627
3628    let mut parser = Parser::new(
3629        tokens,
3630        &mut world_state,
3631        &mut interner,
3632        ast_ctx,
3633        type_registry,
3634    );
3635    let stmts = parser.parse_program()?;
3636    Ok(crate::concurrency::classify_program(&stmts))
3637}
3638
3639/// Phase 0 test seam: is the first `Simultaneously:` / `Attempt all of the
3640/// following:` block in `source` made of data-independent branches?
3641/// `None` if the program contains no such block.
3642pub fn first_parallel_block_independent(source: &str) -> Result<Option<bool>, ParseError> {
3643    let mut interner = Interner::new();
3644    let mut lexer = Lexer::new(source, &mut interner);
3645    let tokens = lexer.tokenize();
3646
3647    let (type_registry, _policy_registry) = {
3648        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
3649        let result = discovery.run_full();
3650        (result.types, result.policies)
3651    };
3652
3653    let mut world_state = WorldState::new();
3654    let expr_arena = Arena::new();
3655    let term_arena = Arena::new();
3656    let np_arena = Arena::new();
3657    let sym_arena = Arena::new();
3658    let role_arena = Arena::new();
3659    let pp_arena = Arena::new();
3660    let stmt_arena: Arena<Stmt> = Arena::new();
3661    let _compile_facts = crate::optimize::facts::scope();
3662    let imperative_expr_arena: Arena<Expr> = Arena::new();
3663    let type_expr_arena: Arena<TypeExpr> = Arena::new();
3664
3665    let ast_ctx = AstContext::with_types(
3666        &expr_arena,
3667        &term_arena,
3668        &np_arena,
3669        &sym_arena,
3670        &role_arena,
3671        &pp_arena,
3672        &stmt_arena,
3673        &imperative_expr_arena,
3674        &type_expr_arena,
3675    );
3676
3677    let mut parser = Parser::new(
3678        tokens,
3679        &mut world_state,
3680        &mut interner,
3681        ast_ctx,
3682        type_registry,
3683    );
3684    let stmts = parser.parse_program()?;
3685    Ok(find_first_parallel_independence(&stmts))
3686}
3687
3688fn find_first_parallel_independence(stmts: &[Stmt]) -> Option<bool> {
3689    for s in stmts {
3690        match s {
3691            Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => {
3692                return Some(crate::concurrency::branches_independent(tasks));
3693            }
3694            Stmt::FunctionDef { body, .. }
3695            | Stmt::While { body, .. }
3696            | Stmt::Repeat { body, .. }
3697            | Stmt::Zone { body, .. } => {
3698                if let Some(r) = find_first_parallel_independence(body) {
3699                    return Some(r);
3700                }
3701            }
3702            Stmt::If {
3703                then_block,
3704                else_block,
3705                ..
3706            } => {
3707                if let Some(r) = find_first_parallel_independence(then_block) {
3708                    return Some(r);
3709                }
3710                if let Some(eb) = else_block {
3711                    if let Some(r) = find_first_parallel_independence(eb) {
3712                        return Some(r);
3713                    }
3714                }
3715            }
3716            _ => {}
3717        }
3718    }
3719    None
3720}
3721
3722/// Run the Send/escape analysis over a program.
3723///
3724/// Parses `source` and returns the Send/escape diagnostics (empty = the program
3725/// respects the message-passing + CRDT discipline). Pure analysis — no codegen.
3726pub fn send_check_source(
3727    source: &str,
3728) -> Result<Vec<crate::concurrency::SendDiagnostic>, ParseError> {
3729    let mut interner = Interner::new();
3730    let mut lexer = Lexer::new(source, &mut interner);
3731    let tokens = lexer.tokenize();
3732
3733    let (type_registry, _policy_registry) = {
3734        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
3735        let result = discovery.run_full();
3736        (result.types, result.policies)
3737    };
3738
3739    let mut world_state = WorldState::new();
3740    let expr_arena = Arena::new();
3741    let term_arena = Arena::new();
3742    let np_arena = Arena::new();
3743    let sym_arena = Arena::new();
3744    let role_arena = Arena::new();
3745    let pp_arena = Arena::new();
3746    let stmt_arena: Arena<Stmt> = Arena::new();
3747    let _compile_facts = crate::optimize::facts::scope();
3748    let imperative_expr_arena: Arena<Expr> = Arena::new();
3749    let type_expr_arena: Arena<TypeExpr> = Arena::new();
3750
3751    let ast_ctx = AstContext::with_types(
3752        &expr_arena,
3753        &term_arena,
3754        &np_arena,
3755        &sym_arena,
3756        &role_arena,
3757        &pp_arena,
3758        &stmt_arena,
3759        &imperative_expr_arena,
3760        &type_expr_arena,
3761    );
3762
3763    let mut parser = Parser::new(
3764        tokens,
3765        &mut world_state,
3766        &mut interner,
3767        ast_ctx,
3768        type_registry,
3769    );
3770    let stmts = parser.parse_program()?;
3771    Ok(crate::concurrency::check_send_escape(&stmts))
3772}
3773
3774/// [`compile_program_full`] for **deterministic replay** — the full
3775/// output (rust + dependencies) with every scheduler operation lowered onto
3776/// `logicaffeine_system::replay`. The seeded differential harness uses this so it
3777/// gets the same dependency set as the default build.
3778pub fn compile_program_full_deterministic(source: &str) -> Result<CompileOutput, ParseError> {
3779    crate::codegen::with_deterministic_replay(|| compile_program_full(source))
3780}
3781
3782/// Refuse the first type the parsed program names that nothing supplies
3783/// (`analysis::check::first_undeclared_type`), located at the top-level statement that names it —
3784/// `spans` are the parser's statement spans, aligned with `parsed` as the parser returned it; a
3785/// declaration's field type has no statement, and the refusal names the type alone.
3786fn refuse_undeclared_types(
3787    parsed: &[Stmt],
3788    spans: &[crate::token::Span],
3789    registry: &crate::analysis::TypeRegistry,
3790    interner: &Interner,
3791) -> Result<(), ParseError> {
3792    match crate::analysis::check::first_undeclared_type(parsed, registry, interner) {
3793        Some((index, name)) => Err(ParseError {
3794            kind: crate::error::ParseErrorKind::Custom(format!(
3795                "`{}` is not a type this program declares or imports",
3796                interner.resolve(name)
3797            )),
3798            span: index
3799                .and_then(|i| spans.get(i))
3800                .copied()
3801                .unwrap_or_default(),
3802        }),
3803        None => Ok(()),
3804    }
3805}
3806
3807/// Compile LOGOS source and return full output including dependency metadata.
3808///
3809/// This is the primary compilation entry point that returns both the generated
3810/// Rust code and any crate dependencies declared in `## Requires` blocks.
3811pub fn compile_program_full(source: &str) -> Result<CompileOutput, ParseError> {
3812    // Mixed-document aware: a source interleaving imperative code with Coq-style math
3813    // (`Definition`/`## Theorem:`/…) routes the math to the Forge and bundles it as
3814    // `mod proven`. Pure imperative programs partition to `(source, None)` — a no-op.
3815    let (imperative_src, math_src) = crate::ui_bridge::partition_mixed(source);
3816    let proven = match math_src.as_deref() {
3817        Some(math) => crate::ui_bridge::mixed_proven_module(math)?,
3818        None => None,
3819    };
3820    compile_program_full_with_proven(&imperative_src, proven.as_deref())
3821}
3822
3823/// Like [`compile_program_full`], but every emitted (non-generic) `enum` also gets
3824/// `WireEncode`/`WireDecode` impls over the shared `logicaffeine_data::wire` codec — byte-identical
3825/// to the peer codec's `encode_value_raw`. This lets a compile-once native partial evaluator
3826/// receive a program AST as data over the same fast codec the interpreter uses. Ordinary compiles
3827/// (the default) are byte-unchanged.
3828pub fn compile_program_full_with_wire(source: &str) -> Result<CompileOutput, ParseError> {
3829    crate::codegen::types::with_wire_impls(true, || compile_program_full(source))
3830}
3831
3832/// Like [`compile_program_full`], but bundles an extracted math/logic module
3833/// (`proven`) into the generated Rust — the imperative half of a mixed document.
3834/// The module is emitted as `pub mod proven { … } use proven::*;` so the imperative
3835/// program can call its functions / `check_*` predicates by name. `None` (or a
3836/// blank module) yields output byte-identical to [`compile_program_full`].
3837pub fn compile_program_full_with_proven(
3838    source: &str,
3839    proven: Option<&str>,
3840) -> Result<CompileOutput, ParseError> {
3841    // Phase 10: auto-prepend the stdlib modules the program references (no-op when
3842    // it uses no stdlib vocabulary, so the benchmark corpus stays byte-identical).
3843    let prelude_src = crate::loader::apply_prelude(source);
3844    // Drop the DEAD prelude functions the whole-module splice dragged in but the program never
3845    // reaches (e.g. a postgres program pulls all of crypto.lg for md5/sha256/pbkdf2, but never the
3846    // ML-DSA signature functions). This never touches a user function and is byte-identical when
3847    // nothing is dead, so live programs are unchanged; it removes stdlib code the AOT-Rust backend
3848    // would otherwise have to compile — including any latent codegen gap it is never reached through.
3849    let pruned = crate::loader::prune_unreachable_prelude_from(source, prelude_src.as_ref());
3850    let source = pruned.as_str();
3851    let library = crate::loader::LibraryProvenance::of(source);
3852
3853    let mut interner = Interner::new();
3854    let mut lexer = Lexer::new(source, &mut interner);
3855    let tokens = lexer.tokenize();
3856
3857    // Pass 1: Discovery - scan for type definitions and policies
3858    let (type_registry, policy_registry) = {
3859        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
3860        let result = discovery.run_full();
3861        (result.types, result.policies)
3862    };
3863    let codegen_policies = policy_registry.clone();
3864
3865    let mut world_state = WorldState::new();
3866    let expr_arena = Arena::new();
3867    let term_arena = Arena::new();
3868    let np_arena = Arena::new();
3869    let sym_arena = Arena::new();
3870    let role_arena = Arena::new();
3871    let pp_arena = Arena::new();
3872    let stmt_arena: Arena<Stmt> = Arena::new();
3873    let _compile_facts = crate::optimize::facts::scope();
3874    let imperative_expr_arena: Arena<Expr> = Arena::new();
3875    let type_expr_arena: Arena<TypeExpr> = Arena::new();
3876
3877    let ast_ctx = AstContext::with_types(
3878        &expr_arena,
3879        &term_arena,
3880        &np_arena,
3881        &sym_arena,
3882        &role_arena,
3883        &pp_arena,
3884        &stmt_arena,
3885        &imperative_expr_arena,
3886        &type_expr_arena,
3887    );
3888
3889    // Pass 2: Parse with type context
3890    let mut parser = Parser::new(
3891        tokens,
3892        &mut world_state,
3893        &mut interner,
3894        ast_ctx,
3895        type_registry,
3896    );
3897    // Note: Don't call process_block_headers() - parse_program handles blocks itself
3898
3899    let stmts = parser.parse_program()?;
3900    let (parsed, parsed_spans) = (stmts.clone(), parser.stmt_spans().to_vec());
3901
3902    // §0.7 — in the ELIDED (release) profile, observation is ERASED at lowering,
3903    // before the optimizer and codegen: Note/Warn/Record vanish and During spans unwrap to
3904    // their bodies, so observation cannot perturb one instruction of the emitted
3905    // code (not even through the optimizer's overflow/range analysis). No-op for
3906    // programs that observe nothing. Locked by `obs_zero_cost_codegen_lock`. In
3907    // the OBSERVED profile the statements survive and the AOT backend emits
3908    // `logicaffeine_system::obs` calls for them (Wave 13).
3909    let stmts: Vec<Stmt> = if crate::codegen::observed_codegen_enabled() {
3910        stmts
3911    } else {
3912        match crate::elide_observation::elide_observation(&stmts, &stmt_arena) {
3913            Some(elided) => elided.to_vec(),
3914            None => stmts,
3915        }
3916    };
3917
3918    // The ONE optimization config for this compile: env baseline merged with the
3919    // file-level `## No <X>` decorators (program-wide), normalized. Threaded to
3920    // BOTH the optimizer and codegen so they never disagree. Captured here (the
3921    // last use of `parser`) so its `&mut interner` borrow ends before reuse.
3922    // `## No` / `## Require` decorators via the shared gate: merge `## No` into the active
3923    // config (so the optimizer AND codegen honor it), and open a firing trace so an unfired
3924    // `## Require` (Ray Myers' wish) fails the compile. Captured here (last use of `parser`)
3925    // so its `&mut interner` borrow ends before reuse; verified after codegen.
3926    let (opt_config, gate) = crate::optimize::install_decorators(
3927        crate::optimization::OptimizationConfig::from_env(),
3928        &parser.program_opt_flags(),
3929        parser.required_optimizations(),
3930    );
3931    let codegen_registry = parser.into_type_registry();
3932    refuse_undeclared_types(&parsed, &parsed_spans, &codegen_registry, &interner)?;
3933
3934    // Escape analysis reads the program as written, before observation was elided.
3935    check_as_written(&parsed, &interner, AsWritten::Escapes)?;
3936
3937    // Type-directed division: rewrite `Divide → ExactDivide` in every Rational context
3938    // (the integer default stays floor), so a `Let x: Rational be 7 / 2` compiles exact
3939    // (`7/2`) instead of flooring to `3` — matching the tree-walker and VM. The optimizer
3940    // treats `ExactDivide` as opaque (never floor-folds it), so this is purely additive.
3941    let resolved = crate::resolve_program::resolve_program(
3942        &stmts,
3943        crate::ast_map::Arenas {
3944            exprs: &imperative_expr_arena,
3945            stmts: &stmt_arena,
3946            types: &type_expr_arena,
3947        },
3948        &mut interner,
3949        opt_config.is_on(crate::optimization::Opt::Comptime),
3950        library.functions(),
3951    );
3952    let stmts: Vec<Stmt> = match resolved {
3953        Some(rw) => rw.to_vec(),
3954        None => stmts,
3955    };
3956    let (stmts, codegen_registry) = lift_program_bindings(
3957        stmts,
3958        codegen_registry,
3959        &mut interner,
3960        crate::ast_map::Arenas {
3961            exprs: &imperative_expr_arena,
3962            stmts: &stmt_arena,
3963            types: &type_expr_arena,
3964        },
3965    )?;
3966
3967    // Pass 2.5: Optimization - constant folding and dead code elimination
3968    let stmts = crate::optimize::optimize_program(
3969        stmts,
3970        &imperative_expr_arena,
3971        &stmt_arena,
3972        &mut interner,
3973        &opt_config,
3974    );
3975
3976    // Extract dependencies
3977    let mut dependencies = extract_dependencies(&stmts, &interner)?;
3978
3979    // FFI: Auto-inject wasm-bindgen dependency if any function is exported for WASM
3980    let needs_wasm_bindgen = stmts.iter().any(|stmt| {
3981        if let Stmt::FunctionDef {
3982            is_exported: true,
3983            export_target: Some(target),
3984            ..
3985        } = stmt
3986        {
3987            interner.resolve(*target).eq_ignore_ascii_case("wasm")
3988        } else {
3989            false
3990        }
3991    });
3992    if needs_wasm_bindgen && !dependencies.iter().any(|d| d.name == "wasm-bindgen") {
3993        dependencies.push(CrateDependency {
3994            name: "wasm-bindgen".to_string(),
3995            version: "0.2".to_string(),
3996            features: vec![],
3997        });
3998    }
3999
4000    // Note: Static verification is available when the `verification` feature is enabled,
4001    // but must be explicitly invoked via compile_to_rust_verified().
4002
4003    // A call to a name that exists nowhere in the post-prelude program is a
4004    // check error here — not a rustc E0425 after codegen. The bundled proven
4005    // module's `pub fn`s are in scope via `use proven::*;`, so they count.
4006    let proven_exports = proven
4007        .map(crate::analysis::proven_module_exports)
4008        .unwrap_or_default();
4009    crate::analysis::check_unknown_calls_with_exports(
4010        &stmts,
4011        &interner,
4012        &codegen_registry,
4013        &proven_exports,
4014    )
4015    .map_err(|e| ParseError {
4016        kind: e.to_parse_error_kind(&interner),
4017        span: crate::token::Span::default(),
4018    })?;
4019
4020    let type_env = crate::analysis::check_program_located(&stmts, &interner, &codegen_registry)
4021        .map_err(|e| ParseError {
4022            kind: e.to_parse_error_kind(&interner, &stmts),
4023            span: crate::token::Span::default(),
4024        })?;
4025    let rust_code = crate::optimize::with_backend_lowering(|| {
4026        crate::codegen::codegen_program_with_proven(
4027            &stmts,
4028            &codegen_registry,
4029            &codegen_policies,
4030            &interner,
4031            &type_env,
4032            &opt_config,
4033            "proven",
4034            proven,
4035        )
4036    });
4037
4038    // `## Require <opt>`: every demanded optimization must have fired for this
4039    // program, or the compile fails loudly — the inverse of `## No`, and strictly
4040    // more general than Zig's tail-call-only `@call(.always_tail)`.
4041    gate.verify().map_err(|m| ParseError {
4042        kind: crate::error::ParseErrorKind::Custom(m),
4043        span: crate::token::Span::default(),
4044    })?;
4045
4046    // Universal ABI: Generate C header + bindings if any C exports exist
4047    let has_c = stmts.iter().any(|stmt| {
4048        if let Stmt::FunctionDef {
4049            is_exported: true,
4050            export_target,
4051            ..
4052        } = stmt
4053        {
4054            match export_target {
4055                None => true,
4056                Some(t) => interner.resolve(*t).eq_ignore_ascii_case("c"),
4057            }
4058        } else {
4059            false
4060        }
4061    });
4062
4063    let c_header = if has_c {
4064        Some(generate_c_header(
4065            &stmts,
4066            "module",
4067            &interner,
4068            &codegen_registry,
4069        ))
4070    } else {
4071        None
4072    };
4073
4074    // Auto-inject serde_json dependency when C exports exist (needed for collection to_json and portable struct JSON accessors)
4075    if has_c && !dependencies.iter().any(|d| d.name == "serde_json") {
4076        dependencies.push(CrateDependency {
4077            name: "serde_json".to_string(),
4078            version: "1".to_string(),
4079            features: vec![],
4080        });
4081    }
4082
4083    let python_bindings = if has_c {
4084        Some(generate_python_bindings(
4085            &stmts,
4086            "module",
4087            &interner,
4088            &codegen_registry,
4089        ))
4090    } else {
4091        None
4092    };
4093
4094    let (typescript_bindings, typescript_types) = if has_c {
4095        let (js, dts) =
4096            generate_typescript_bindings(&stmts, "module", &interner, &codegen_registry);
4097        (Some(js), Some(dts))
4098    } else {
4099        (None, None)
4100    };
4101
4102    Ok(CompileOutput {
4103        rust_code,
4104        dependencies,
4105        c_header,
4106        python_bindings,
4107        typescript_types,
4108        typescript_bindings,
4109    })
4110}
4111
4112/// Generate the Rust SOURCE for an AOT-native cdylib of ONE function (HOTSWAP §Axis-3
4113/// / P14b): the `target` function plus its transitive callees ([`crate::codegen::function_slice`]),
4114/// emitted through the normal ARCHITECT codegen, with the
4115/// [`crate::codegen::codegen_native_tier_export`] shim appended so the loader can
4116/// resolve the `logos_native_<target>` symbol. Mirrors [`compile_program_full`]'s
4117/// front-end, then slices before codegen.
4118///
4119/// Returns `Ok(None)` when `target` is absent or outside the sound scalar ABI subset —
4120/// the caller then keeps that function on VM+JIT (no AOT-native, no gap at the seam).
4121/// `Err` only on a genuine parse/type error in the source.
4122pub fn compile_function_to_native_rust(
4123    source: &str,
4124    target: &str,
4125) -> Result<Option<AotModule>, ParseError> {
4126    let library = crate::loader::LibraryProvenance::of(source);
4127    let mut interner = Interner::new();
4128    let mut lexer = Lexer::new(source, &mut interner);
4129    let tokens = lexer.tokenize();
4130
4131    let (type_registry, policy_registry) = {
4132        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
4133        let result = discovery.run_full();
4134        (result.types, result.policies)
4135    };
4136    let codegen_policies = policy_registry.clone();
4137
4138    let mut world_state = WorldState::new();
4139    let expr_arena = Arena::new();
4140    let term_arena = Arena::new();
4141    let np_arena = Arena::new();
4142    let sym_arena = Arena::new();
4143    let role_arena = Arena::new();
4144    let pp_arena = Arena::new();
4145    let stmt_arena: Arena<Stmt> = Arena::new();
4146    let _compile_facts = crate::optimize::facts::scope();
4147    let imperative_expr_arena: Arena<Expr> = Arena::new();
4148    let type_expr_arena: Arena<TypeExpr> = Arena::new();
4149    let ast_ctx = AstContext::with_types(
4150        &expr_arena,
4151        &term_arena,
4152        &np_arena,
4153        &sym_arena,
4154        &role_arena,
4155        &pp_arena,
4156        &stmt_arena,
4157        &imperative_expr_arena,
4158        &type_expr_arena,
4159    );
4160
4161    let mut parser = Parser::new(
4162        tokens,
4163        &mut world_state,
4164        &mut interner,
4165        ast_ctx,
4166        type_registry,
4167    );
4168    let stmts = parser.parse_program()?;
4169    let (parsed, parsed_spans) = (stmts.clone(), parser.stmt_spans().to_vec());
4170    let opt_config = {
4171        let mut c =
4172            crate::optimization::OptimizationConfig::from_env().merged(&parser.program_opt_flags());
4173        c.normalize();
4174        c
4175    };
4176    let codegen_registry = parser.into_type_registry();
4177    refuse_undeclared_types(&parsed, &parsed_spans, &codegen_registry, &interner)?;
4178    let resolved = crate::resolve_program::resolve_program(
4179        &stmts,
4180        crate::ast_map::Arenas {
4181            exprs: &imperative_expr_arena,
4182            stmts: &stmt_arena,
4183            types: &type_expr_arena,
4184        },
4185        &mut interner,
4186        opt_config.is_on(crate::optimization::Opt::Comptime),
4187        library.functions(),
4188    );
4189    let stmts: Vec<Stmt> = match resolved {
4190        Some(rw) => rw.to_vec(),
4191        None => stmts,
4192    };
4193    // Optimize the whole program (ARCHITECT), THEN slice: the slice picks the optimized
4194    // target + its (optimized) transitive callees.
4195    let stmts = crate::optimize::optimize_program(
4196        stmts,
4197        &imperative_expr_arena,
4198        &stmt_arena,
4199        &mut interner,
4200        &opt_config,
4201    );
4202
4203    // Resolve the target's symbol + signature for the shim; absent ⇒ no AOT-native fn.
4204    let target_sig = stmts.iter().find_map(|s| match s {
4205        Stmt::FunctionDef {
4206            name,
4207            params,
4208            return_type,
4209            ..
4210        } if interner.resolve(*name) == target => {
4211            let ps: Vec<(crate::intern::Symbol, &TypeExpr)> =
4212                params.iter().map(|(s, t)| (*s, *t)).collect();
4213            Some((*name, ps, *return_type))
4214        }
4215        _ => None,
4216    });
4217    let Some((target_sym, params, return_type)) = target_sig else {
4218        return Ok(None);
4219    };
4220    // Native code that stops partway hands the call back to bytecode, which re-runs it and raises
4221    // the exact error — sound only for a call with nothing observable to repeat. A function with an
4222    // effect (a `Show`, IO, concurrency) stays on VM+JIT.
4223    if !crate::optimize::effects::EffectEnv::from_stmts(&stmts, &interner)
4224        .function_is_replayable(target)
4225    {
4226        return Ok(None);
4227    }
4228    // The shim only exists for the sound scalar subset; otherwise no AOT-native fn.
4229    let Some(shim) =
4230        crate::codegen::codegen_native_tier_export(target_sym, &params, return_type, &interner)
4231    else {
4232        return Ok(None);
4233    };
4234
4235    let slice = crate::codegen::function_slice(&stmts, target_sym, &interner);
4236    let type_env = crate::analysis::check_program_located(&slice, &interner, &codegen_registry)
4237        .map_err(|e| ParseError {
4238            kind: e.to_parse_error_kind(&interner, &slice),
4239            span: crate::token::Span::default(),
4240        })?;
4241    let module = crate::codegen::codegen_program(
4242        &slice,
4243        &codegen_registry,
4244        &codegen_policies,
4245        &interner,
4246        &type_env,
4247        &opt_config,
4248    );
4249    let symbol = format!(
4250        "logos_native_{}",
4251        crate::analysis::types::RustNames::new(&interner).raw(target_sym)
4252    );
4253    Ok(Some(AotModule {
4254        rust: format!("{module}\n{shim}"),
4255        symbol,
4256        arity: params.len(),
4257    }))
4258}
4259
4260/// A compiled AOT-native module (HOTSWAP §Axis-3): the cdylib Rust SOURCE plus the
4261/// exact exported `symbol` to resolve and its `arity` — everything the loader needs.
4262#[derive(Debug, Clone)]
4263pub struct AotModule {
4264    pub rust: String,
4265    pub symbol: String,
4266    pub arity: usize,
4267}
4268
4269/// Build a function's AOT module to a browser-loadable `wasm32-unknown-unknown` cdylib
4270/// (HOTSWAP §Axis-3 / P17 — the browser analog of [`build_native_cdylib`]). The module
4271/// is the same scalar-ABI shim; the wasm crate keeps `logicaffeine-data` +
4272/// `logicaffeine-system` (both wasm-ready) but drops the desktop-only `tokio`, the
4273/// `logicaffeine-system` `full` feature, and `target-cpu=native`. Returns the `.wasm` path;
4274/// the browser then `WebAssembly.instantiate`s it and the entry calls into it through
4275/// the warm-bytecode indirection. Requires the `wasm32-unknown-unknown` target.
4276#[cfg(not(target_arch = "wasm32"))]
4277pub fn build_native_wasm(
4278    rust_source: &str,
4279    crate_name: &str,
4280    work_dir: &std::path::Path,
4281) -> Result<std::path::PathBuf, String> {
4282    use std::process::Command;
4283    let proj = work_dir.join(crate_name);
4284    let _ = fs::remove_dir_all(&proj);
4285    fs::create_dir_all(proj.join("src")).map_err(|e| e.to_string())?;
4286    fs::write(proj.join("src").join("lib.rs"), rust_source).map_err(|e| e.to_string())?;
4287
4288    let cargo_toml = format!(
4289        "[package]\nname = \"{crate_name}\"\nversion = \"0.0.0\"\nedition = \"2021\"\n\n\
4290         [lib]\ncrate-type = [\"cdylib\"]\n\n\
4291         [dependencies]\n\
4292         logicaffeine-data = {{ path = \"./crates/logicaffeine_data\" }}\n\
4293         logicaffeine-system = {{ path = \"./crates/logicaffeine_system\" }}\n\n\
4294         [profile.release]\nlto = true\nopt-level = 3\ncodegen-units = 1\nstrip = true\n"
4295    );
4296    fs::write(proj.join("Cargo.toml"), &cargo_toml).map_err(|e| e.to_string())?;
4297
4298    copy_runtime_crates(&proj).map_err(|e| e.to_string())?;
4299
4300    // The artifact is read back from `proj/target`, so the build writes there whatever the caller's
4301    // environment says: an inherited `CARGO_TARGET_DIR` would put it somewhere this code never looks.
4302    let out = Command::new("cargo")
4303        .args([
4304            "build",
4305            "--release",
4306            "--lib",
4307            "--target",
4308            "wasm32-unknown-unknown",
4309        ])
4310        .arg("--target-dir")
4311        .arg(proj.join("target"))
4312        .current_dir(&proj)
4313        .output()
4314        .map_err(|e| format!("failed to run cargo: {e}"))?;
4315    if !out.status.success() {
4316        return Err(format!(
4317            "wasm bundle build failed:\n{}",
4318            String::from_utf8_lossy(&out.stderr)
4319        ));
4320    }
4321
4322    let wasm = proj
4323        .join("target")
4324        .join("wasm32-unknown-unknown")
4325        .join("release")
4326        .join(format!("{crate_name}.wasm"));
4327    if !wasm.exists() {
4328        return Err(format!("wasm module not found at {}", wasm.display()));
4329    }
4330    Ok(wasm)
4331}
4332
4333/// Build AOT-native cdylib Rust source (from [`compile_function_to_native_rust`]) into
4334/// a loadable `cdylib` (HOTSWAP §Axis-3 / P16). Generates a minimal crate under
4335/// `work_dir/<crate_name>`, copies the shared runtime crates (so the `.so` and the
4336/// interpreter share the SAME `logicaffeine_data` ABI), and runs `cargo build
4337/// --release`. Returns the path to the produced dynamic library. `panic = "unwind"`
4338/// (the default) — NOT `abort` — so a panic in a loaded function can be contained
4339/// rather than killing the host process.
4340#[cfg(not(target_arch = "wasm32"))]
4341pub fn build_native_cdylib(
4342    rust_source: &str,
4343    crate_name: &str,
4344    work_dir: &std::path::Path,
4345) -> Result<std::path::PathBuf, String> {
4346    use std::process::Command;
4347    let proj = work_dir.join(crate_name);
4348    let _ = fs::remove_dir_all(&proj);
4349    fs::create_dir_all(proj.join("src")).map_err(|e| e.to_string())?;
4350    fs::write(proj.join("src").join("lib.rs"), rust_source).map_err(|e| e.to_string())?;
4351
4352    let cargo_toml = format!(
4353        "[package]\nname = \"{crate_name}\"\nversion = \"0.0.0\"\nedition = \"2021\"\n\n\
4354         [lib]\ncrate-type = [\"cdylib\"]\n\n\
4355         [dependencies]\n\
4356         logicaffeine-data = {{ path = \"./crates/logicaffeine_data\" }}\n\
4357         logicaffeine-system = {{ path = \"./crates/logicaffeine_system\", features = [\"full\"] }}\n\
4358         tokio = {{ version = \"1\", features = [\"rt-multi-thread\", \"macros\"] }}\n\n\
4359         [profile.release]\nlto = true\nopt-level = 3\ncodegen-units = 1\nstrip = true\n"
4360    );
4361    fs::write(proj.join("Cargo.toml"), &cargo_toml).map_err(|e| e.to_string())?;
4362
4363    let cargo_cfg = proj.join(".cargo");
4364    fs::create_dir_all(&cargo_cfg).map_err(|e| e.to_string())?;
4365    fs::write(
4366        cargo_cfg.join("config.toml"),
4367        "[build]\nrustflags = [\"-C\", \"target-cpu=native\"]\n",
4368    )
4369    .map_err(|e| e.to_string())?;
4370
4371    copy_runtime_crates(&proj).map_err(|e| e.to_string())?;
4372
4373    // The `.so` is read back from `proj/target/release`, so the build writes there whatever the
4374    // caller's environment says: an inherited `CARGO_TARGET_DIR` would put the library somewhere this
4375    // code never looks, and the native tier would silently never load.
4376    let out = Command::new("cargo")
4377        .args(["build", "--release", "--lib"])
4378        .arg("--target-dir")
4379        .arg(proj.join("target"))
4380        .current_dir(&proj)
4381        .output()
4382        .map_err(|e| format!("failed to run cargo: {e}"))?;
4383    if !out.status.success() {
4384        return Err(format!(
4385            "AOT cdylib build failed:\n{}",
4386            String::from_utf8_lossy(&out.stderr)
4387        ));
4388    }
4389
4390    let so = proj.join("target").join("release").join(format!(
4391        "{}{}{}",
4392        std::env::consts::DLL_PREFIX,
4393        crate_name,
4394        std::env::consts::DLL_SUFFIX
4395    ));
4396    if !so.exists() {
4397        return Err(format!("AOT cdylib not found at {}", so.display()));
4398    }
4399    Ok(so)
4400}
4401
4402/// The cache key for an AOT-native artifact (HOTSWAP §Axis-3 / P16): a deterministic
4403/// FNV-1a hash of the rustc toolchain version AND the optimized Rust source. The
4404/// toolchain is in the key because Rust has no stable cross-version ABI — a different
4405/// `rustc`/runtime yields a different key, so a stale, ABI-mismatched `.so` is NEVER
4406/// reused (soundness over convenience). The source captures the function, its callees,
4407/// and the optimization config (it IS the codegen output).
4408#[cfg(not(target_arch = "wasm32"))]
4409pub fn aot_cache_key(rust_source: &str) -> String {
4410    let toolchain = std::process::Command::new("rustc")
4411        .arg("--version")
4412        .output()
4413        .ok()
4414        .map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
4415        .unwrap_or_default();
4416    let mut h: u64 = 0xcbf29ce4_84222325;
4417    for b in toolchain.bytes().chain(rust_source.bytes()) {
4418        h ^= b as u64;
4419        h = h.wrapping_mul(0x0000_0100_0000_01b3);
4420    }
4421    format!("{h:016x}")
4422}
4423
4424/// [`build_native_cdylib`] with a persistent cache (HOTSWAP §Axis-3 / P16). The artifact
4425/// lives at `cache_dir/aot_<fn>_<key>/…` keyed by [`aot_cache_key`]; an identical
4426/// function reuses its `.so` across runs (no rebuild), and a toolchain change yields a
4427/// new key so the stale library is never loaded.
4428#[cfg(not(target_arch = "wasm32"))]
4429pub fn build_native_cdylib_cached(
4430    rust_source: &str,
4431    fn_name: &str,
4432    cache_dir: &std::path::Path,
4433) -> Result<std::path::PathBuf, String> {
4434    let key = aot_cache_key(rust_source);
4435    let crate_name = format!("aot_{fn_name}_{key}");
4436    let so = cache_dir
4437        .join(&crate_name)
4438        .join("target")
4439        .join("release")
4440        .join(format!(
4441            "{}{}{}",
4442            std::env::consts::DLL_PREFIX,
4443            crate_name,
4444            std::env::consts::DLL_SUFFIX
4445        ));
4446    if so.exists() {
4447        return Ok(so); // cache hit — reuse, skip the rustc build
4448    }
4449    fs::create_dir_all(cache_dir).map_err(|e| e.to_string())?;
4450    build_native_cdylib(rust_source, &crate_name, cache_dir)
4451}
4452
4453/// On-demand AOT-native build + load (HOTSWAP §Axis-3): compile `fn_name` (and its
4454/// callees) to an optimized cdylib (cached), `dlopen` it, and return the loaded
4455/// [`crate::vm::NativeFn`] ready to install via `Vm::install_aot_native`. `None` if the
4456/// function is absent / outside the scalar subset / the build or load failed — the
4457/// caller keeps it on VM+JIT. Blocking (runs `rustc`); the background worker
4458/// (`BgAotCompiler`) calls this off the interpreter thread.
4459#[cfg(not(target_arch = "wasm32"))]
4460pub fn aot_build_function(
4461    source: &str,
4462    fn_name: &str,
4463    cache_dir: &std::path::Path,
4464) -> Option<Box<dyn crate::vm::NativeFn>> {
4465    let module = compile_function_to_native_rust(source, fn_name)
4466        .ok()
4467        .flatten()?;
4468    let so = build_native_cdylib_cached(&module.rust, fn_name, cache_dir).ok()?;
4469    let (nf, _calls) = crate::vm::aot_tier::load_aot_native(&so, &module.symbol, module.arity)?;
4470    Some(nf)
4471}
4472
4473/// The names of functions annotated for the AOT-native tier — `## To <fn> … is
4474/// exported for native:` (HOTSWAP §Axis-3 selectivity). These are the functions
4475/// `largo build --native-functions` pre-bundles; everything else stays on VM+JIT.
4476pub fn native_export_function_names(source: &str) -> Vec<String> {
4477    crate::ui_bridge::with_parsed_program(source, |parsed, interner| match parsed {
4478        Ok((stmts, _types, _policies)) => stmts
4479            .iter()
4480            .filter_map(|s| match s {
4481                Stmt::FunctionDef {
4482                    name,
4483                    is_exported: true,
4484                    export_target: Some(t),
4485                    ..
4486                } if interner.resolve(*t).eq_ignore_ascii_case("native") => {
4487                    Some(interner.resolve(*name).to_string())
4488                }
4489                _ => None,
4490            })
4491            .collect(),
4492        Err(_) => Vec::new(),
4493    })
4494}
4495
4496/// Load every `native`-annotated function in `source` as a compiled-native
4497/// [`crate::vm::NativeFn`] (HOTSWAP §Axis-3): the run path installs these via
4498/// `Vm::install_aot_native`, so an annotated function dispatches to `rustc -O3` machine
4499/// code from its first call. Uses the persistent cache, so a bundle pre-built by
4500/// `largo build --native-functions` is a cache hit — no `rustc` on the run path. A
4501/// function outside the scalar subset / failing to build is skipped (stays on VM+JIT).
4502#[cfg(not(target_arch = "wasm32"))]
4503pub fn aot_load_bundle(
4504    source: &str,
4505    cache_dir: &std::path::Path,
4506) -> Vec<(String, Box<dyn crate::vm::NativeFn>)> {
4507    native_export_function_names(source)
4508        .into_iter()
4509        .filter_map(|name| aot_build_function(source, &name, cache_dir).map(|nf| (name, nf)))
4510        .collect()
4511}
4512
4513/// Pre-build every `native`-annotated function in `source` into the AOT bundle under
4514/// `bundle_dir` (HOTSWAP §Axis-3 / P16 — the "tools to bundle them"). Returns the
4515/// `(function_name, cdylib_path)` manifest. Functions outside the sound scalar subset
4516/// are silently skipped — they keep running on VM+JIT, no gap at the seam. `Err` only
4517/// on a genuine parse/type error.
4518#[cfg(not(target_arch = "wasm32"))]
4519pub fn build_native_bundle(
4520    source: &str,
4521    bundle_dir: &std::path::Path,
4522) -> Result<Vec<(String, std::path::PathBuf)>, ParseError> {
4523    let mut manifest = Vec::new();
4524    for name in native_export_function_names(source) {
4525        let Some(module) = compile_function_to_native_rust(source, &name)? else {
4526            continue; // not in the scalar subset — stays on VM+JIT
4527        };
4528        if let Ok(so) = build_native_cdylib_cached(&module.rust, &name, bundle_dir) {
4529            manifest.push((name, so));
4530        }
4531    }
4532    Ok(manifest)
4533}
4534
4535/// Extract crate dependencies from `Stmt::Require` nodes.
4536///
4537/// Deduplicates by crate name: same name + same version keeps one copy.
4538/// Same name + different version returns a `ParseError`.
4539/// Preserves declaration order (first occurrence wins).
4540fn extract_dependencies(
4541    stmts: &[Stmt],
4542    interner: &Interner,
4543) -> Result<Vec<CrateDependency>, ParseError> {
4544    use std::collections::HashMap;
4545
4546    let mut seen: HashMap<String, String> = HashMap::new(); // name → version
4547    let mut deps: Vec<CrateDependency> = Vec::new();
4548
4549    for stmt in stmts {
4550        if let Stmt::Require {
4551            crate_name,
4552            version,
4553            features,
4554            span,
4555        } = stmt
4556        {
4557            let name = interner.resolve(*crate_name).to_string();
4558            let ver = interner.resolve(*version).to_string();
4559
4560            if let Some(existing_ver) = seen.get(&name) {
4561                if *existing_ver != ver {
4562                    return Err(ParseError {
4563                        kind: crate::error::ParseErrorKind::Custom(format!(
4564                            "Conflicting versions for crate \"{}\": \"{}\" and \"{}\".",
4565                            name, existing_ver, ver
4566                        )),
4567                        span: *span,
4568                    });
4569                }
4570                // Same name + same version: skip duplicate
4571            } else {
4572                seen.insert(name.clone(), ver.clone());
4573                deps.push(CrateDependency {
4574                    name,
4575                    version: ver,
4576                    features: features
4577                        .iter()
4578                        .map(|f| interner.resolve(*f).to_string())
4579                        .collect(),
4580                });
4581            }
4582        }
4583    }
4584
4585    Ok(deps)
4586}
4587
4588/// What an entry point judges on the program as written.
4589#[derive(Clone, Copy, PartialEq, Eq)]
4590enum AsWritten {
4591    /// Zone escapes — every compile refuses one.
4592    Escapes,
4593    /// Zone escapes and uses after `Give` — the checked compile.
4594    EscapesAndOwnership,
4595}
4596
4597/// Judge the program as its author wrote it: the freshly-parsed statements, before observation
4598/// elision, division resolution or the optimizer rewrite them. Those rewrites can fold away the
4599/// very names the checks follow — once `x` is a known constant, propagation turns `Give x to p.`
4600/// into `Give 5 to p.` and `Show x.` into `Show 5.`, and folding flattens a constant `If` — so a
4601/// check run afterwards passes whatever the optimizer happened to fold, and disagrees with the
4602/// editor, which judges the parse. Run it before `install_decorators`, so a refused program never
4603/// opens a `## Require` trace.
4604fn check_as_written(
4605    stmts: &[Stmt],
4606    interner: &Interner,
4607    checks: AsWritten,
4608) -> Result<(), ParseError> {
4609    fn refusal(message: String, span: crate::token::Span) -> ParseError {
4610        ParseError {
4611            kind: crate::error::ParseErrorKind::Custom(message),
4612            span,
4613        }
4614    }
4615    EscapeChecker::new(interner)
4616        .check_program(stmts)
4617        .map_err(|e| refusal(e.to_string(), e.span))?;
4618    if checks == AsWritten::EscapesAndOwnership {
4619        OwnershipChecker::new(interner)
4620            .check_program(stmts)
4621            .map_err(|e| refusal(e.to_string(), e.span))?;
4622    }
4623    Ok(())
4624}
4625
4626/// Compile LOGOS source to Rust with ownership checking enabled.
4627///
4628/// This runs the lightweight ownership analysis pass that catches use-after-move
4629/// errors with control flow awareness. The analysis is fast enough to run on
4630/// every keystroke in an IDE. It judges the program as written, before the
4631/// optimizer runs: constant propagation would otherwise fold a given-away name
4632/// into its value and hide the use after it.
4633///
4634/// # Arguments
4635///
4636/// * `source` - LOGOS source code as a string
4637///
4638/// # Returns
4639///
4640/// Generated Rust source code on success.
4641///
4642/// # Errors
4643///
4644/// Returns [`ParseError`] if:
4645/// - Any error from [`compile_to_rust`] occurs
4646/// - Ownership analysis detects use-after-move
4647/// - Ownership analysis detects use-after-borrow violations
4648///
4649/// # Example
4650///
4651/// ```
4652/// # use logicaffeine_compile::compile::compile_to_rust_checked;
4653/// // This will fail ownership checking
4654/// let source = "## Main\nLet x be 5.\nGive x to y.\nShow x.";
4655/// let result = compile_to_rust_checked(source);
4656/// assert!(result.is_err()); // "x has already been given away"
4657/// ```
4658///
4659/// # Use Case
4660///
4661/// Use this function with the `--check` CLI flag for instant feedback on
4662/// ownership errors before running the full Rust compilation.
4663pub fn compile_to_rust_checked(source: &str) -> Result<String, ParseError> {
4664    // Mixed document: ownership-check only the imperative stream (math blocks are
4665    // blanked, preserving line numbers). The math half is checked by the kernel.
4666    let (imperative_src, _) = crate::ui_bridge::partition_mixed(source);
4667    let source = imperative_src.as_str();
4668    let library = crate::loader::LibraryProvenance::of(source);
4669    let mut interner = Interner::new();
4670    let mut lexer = Lexer::new(source, &mut interner);
4671    let tokens = lexer.tokenize();
4672
4673    // Pass 1: Discovery - scan for type definitions and policies
4674    let (type_registry, policy_registry) = {
4675        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
4676        let result = discovery.run_full();
4677        (result.types, result.policies)
4678    };
4679    let codegen_policies = policy_registry.clone();
4680
4681    let mut world_state = WorldState::new();
4682    let expr_arena = Arena::new();
4683    let term_arena = Arena::new();
4684    let np_arena = Arena::new();
4685    let sym_arena = Arena::new();
4686    let role_arena = Arena::new();
4687    let pp_arena = Arena::new();
4688    let stmt_arena: Arena<Stmt> = Arena::new();
4689    let _compile_facts = crate::optimize::facts::scope();
4690    let imperative_expr_arena: Arena<Expr> = Arena::new();
4691    let type_expr_arena: Arena<TypeExpr> = Arena::new();
4692
4693    let ast_ctx = AstContext::with_types(
4694        &expr_arena,
4695        &term_arena,
4696        &np_arena,
4697        &sym_arena,
4698        &role_arena,
4699        &pp_arena,
4700        &stmt_arena,
4701        &imperative_expr_arena,
4702        &type_expr_arena,
4703    );
4704
4705    // Pass 2: Parse with type context
4706    let mut parser = Parser::new(
4707        tokens,
4708        &mut world_state,
4709        &mut interner,
4710        ast_ctx,
4711        type_registry,
4712    );
4713    let stmts = parser.parse_program()?;
4714    let (parsed, parsed_spans) = (stmts.clone(), parser.stmt_spans().to_vec());
4715
4716    // Pass 2.5: Optimization - constant folding, propagation, and dead code elimination.
4717    // Honor `## No`/`## Require` decorators (merge parser flags; a bare `from_env()` drops
4718    // them) and open a firing trace so an unfired `## Require` fails this path too.
4719    // `## No`/`## Require` decorators via the shared gate (merge into active config; verify
4720    // required opts fired after codegen). Last use of `parser` before `&mut interner` is reused.
4721    let (opt_config, gate) = crate::optimize::install_decorators(
4722        crate::optimization::OptimizationConfig::from_env(),
4723        &parser.program_opt_flags(),
4724        parser.required_optimizations(),
4725    );
4726    let codegen_registry = parser.into_type_registry();
4727    refuse_undeclared_types(&parsed, &parsed_spans, &codegen_registry, &interner)?;
4728
4729    // Pass 3: Escape and ownership analysis — use-after-move with control-flow awareness —
4730    // on the program as written.
4731    check_as_written(&stmts, &interner, AsWritten::EscapesAndOwnership)?;
4732
4733    let resolved = crate::resolve_program::resolve_program(
4734        &stmts,
4735        crate::ast_map::Arenas {
4736            exprs: &imperative_expr_arena,
4737            stmts: &stmt_arena,
4738            types: &type_expr_arena,
4739        },
4740        &mut interner,
4741        opt_config.is_on(crate::optimization::Opt::Comptime),
4742        library.functions(),
4743    );
4744    let stmts: Vec<Stmt> = match resolved {
4745        Some(rw) => rw.to_vec(),
4746        None => stmts,
4747    };
4748    let (stmts, codegen_registry) = lift_program_bindings(
4749        stmts,
4750        codegen_registry,
4751        &mut interner,
4752        crate::ast_map::Arenas {
4753            exprs: &imperative_expr_arena,
4754            stmts: &stmt_arena,
4755            types: &type_expr_arena,
4756        },
4757    )?;
4758    let stmts = crate::optimize::optimize_program(
4759        stmts,
4760        &imperative_expr_arena,
4761        &stmt_arena,
4762        &mut interner,
4763        &opt_config,
4764    );
4765
4766    let type_env = crate::analysis::check_program_located(&stmts, &interner, &codegen_registry)
4767        .map_err(|e| ParseError {
4768            kind: e.to_parse_error_kind(&interner, &stmts),
4769            span: crate::token::Span::default(),
4770        })?;
4771    let rust_code = codegen_program(
4772        &stmts,
4773        &codegen_registry,
4774        &codegen_policies,
4775        &interner,
4776        &type_env,
4777        &opt_config,
4778    );
4779
4780    gate.verify().map_err(|m| ParseError {
4781        kind: crate::error::ParseErrorKind::Custom(m),
4782        span: crate::token::Span::default(),
4783    })?;
4784
4785    Ok(rust_code)
4786}
4787
4788/// Compile LOGOS source to Rust with full Z3 static verification.
4789///
4790/// This runs the Z3-based verifier on Assert statements before code generation,
4791/// proving that assertions hold for all possible inputs. This is the most
4792/// thorough compilation mode, suitable for high-assurance code.
4793///
4794/// # Arguments
4795///
4796/// * `source` - LOGOS source code as a string
4797///
4798/// # Returns
4799///
4800/// Generated Rust source code on success.
4801///
4802/// # Errors
4803///
4804/// Returns [`ParseError`] if:
4805/// - Any error from [`compile_to_rust`] occurs
4806/// - Z3 cannot prove an Assert statement
4807/// - Refinement type constraints cannot be satisfied
4808/// - Termination cannot be proven for loops with `decreasing`
4809///
4810/// # Example
4811///
4812/// ```no_run
4813/// # use logicaffeine_compile::compile::compile_to_rust_verified;
4814/// # use logicaffeine_compile::ParseError;
4815/// # fn main() -> Result<(), ParseError> {
4816/// let source = r#"
4817/// ## Main
4818/// Let x: { it: Int | it > 0 } be 5.
4819/// Assert that x > 0.
4820/// "#;
4821/// let rust_code = compile_to_rust_verified(source)?;
4822/// # Ok(())
4823/// # }
4824/// ```
4825///
4826/// # Feature Flag
4827///
4828/// This function requires the `verification` feature to be enabled:
4829///
4830/// ```toml
4831/// [dependencies]
4832/// logicaffeine_compile = { version = "...", features = ["verification"] }
4833/// ```
4834#[cfg(feature = "verification")]
4835pub fn compile_to_rust_verified(source: &str) -> Result<String, ParseError> {
4836    use crate::verification::VerificationPass;
4837    let library = crate::loader::LibraryProvenance::of(source);
4838
4839    let mut interner = Interner::new();
4840    let mut lexer = Lexer::new(source, &mut interner);
4841    let tokens = lexer.tokenize();
4842
4843    // Pass 1: Discovery - scan for type definitions and policies
4844    let (type_registry, policy_registry) = {
4845        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
4846        let result = discovery.run_full();
4847        (result.types, result.policies)
4848    };
4849    let codegen_policies = policy_registry.clone();
4850
4851    let mut world_state = WorldState::new();
4852    let expr_arena = Arena::new();
4853    let term_arena = Arena::new();
4854    let np_arena = Arena::new();
4855    let sym_arena = Arena::new();
4856    let role_arena = Arena::new();
4857    let pp_arena = Arena::new();
4858    let stmt_arena: Arena<Stmt> = Arena::new();
4859    let _compile_facts = crate::optimize::facts::scope();
4860    let imperative_expr_arena: Arena<Expr> = Arena::new();
4861    let type_expr_arena: Arena<TypeExpr> = Arena::new();
4862
4863    let ast_ctx = AstContext::with_types(
4864        &expr_arena,
4865        &term_arena,
4866        &np_arena,
4867        &sym_arena,
4868        &role_arena,
4869        &pp_arena,
4870        &stmt_arena,
4871        &imperative_expr_arena,
4872        &type_expr_arena,
4873    );
4874
4875    // Pass 2: Parse with type context
4876    let mut parser = Parser::new(
4877        tokens,
4878        &mut world_state,
4879        &mut interner,
4880        ast_ctx,
4881        type_registry,
4882    );
4883    let stmts = parser.parse_program()?;
4884    let (parsed, parsed_spans) = (stmts.clone(), parser.stmt_spans().to_vec());
4885
4886    // Honor `## No`/`## Require` decorators on the verified path too. Captured here (the last
4887    // use of `parser`) so its `&mut interner` borrow ends before the immutable `&interner`
4888    // passes below; a bare `from_env()` at codegen would silently drop them.
4889    // `## No`/`## Require` decorators via the shared gate (merge into active config; verify
4890    // required opts fired after codegen). Last use of `parser` before `&mut interner` is reused.
4891    let (opt_config, gate) = crate::optimize::install_decorators(
4892        crate::optimization::OptimizationConfig::from_env(),
4893        &parser.program_opt_flags(),
4894        parser.required_optimizations(),
4895    );
4896    let codegen_registry = parser.into_type_registry();
4897    refuse_undeclared_types(&parsed, &parsed_spans, &codegen_registry, &interner)?;
4898
4899    // Pass 3: Escape analysis, on the program as written
4900    check_as_written(&stmts, &interner, AsWritten::Escapes)?;
4901
4902    let resolved = crate::resolve_program::resolve_program(
4903        &stmts,
4904        crate::ast_map::Arenas {
4905            exprs: &imperative_expr_arena,
4906            stmts: &stmt_arena,
4907            types: &type_expr_arena,
4908        },
4909        &mut interner,
4910        opt_config.is_on(crate::optimization::Opt::Comptime),
4911        library.functions(),
4912    );
4913    let stmts: Vec<Stmt> = match resolved {
4914        Some(rw) => rw.to_vec(),
4915        None => stmts,
4916    };
4917
4918    // Pass 4: Static verification
4919    let mut verifier = VerificationPass::new(&interner);
4920    verifier.verify_program(&stmts).map_err(|e| ParseError {
4921        kind: crate::error::ParseErrorKind::Custom(format!("Verification Failed:\n\n{}", e)),
4922        span: crate::token::Span::default(),
4923    })?;
4924
4925    let type_env = crate::analysis::check_program_located(&stmts, &interner, &codegen_registry)
4926        .map_err(|e| ParseError {
4927            kind: e.to_parse_error_kind(&interner, &stmts),
4928            span: crate::token::Span::default(),
4929        })?;
4930    let rust_code = codegen_program(
4931        &stmts,
4932        &codegen_registry,
4933        &codegen_policies,
4934        &interner,
4935        &type_env,
4936        &opt_config,
4937    );
4938
4939    gate.verify().map_err(|m| ParseError {
4940        kind: crate::error::ParseErrorKind::Custom(m),
4941        span: crate::token::Span::default(),
4942    })?;
4943
4944    Ok(rust_code)
4945}
4946
4947/// Compile LOGOS source and write output to a directory as a Cargo project.
4948///
4949/// Creates a complete Cargo project structure with:
4950/// - `src/main.rs` containing the generated Rust code
4951/// - `Cargo.toml` with runtime dependencies
4952/// - `crates/` directory with runtime crate copies
4953///
4954/// # Arguments
4955///
4956/// * `source` - LOGOS source code as a string
4957/// * `output_dir` - Directory to create the Cargo project in
4958///
4959/// # Errors
4960///
4961/// Returns [`CompileError`] if:
4962/// - Compilation fails (wrapped as `CompileError::Parse`)
4963/// - File system operations fail (wrapped as `CompileError::Io`)
4964///
4965/// # Example
4966///
4967/// ```no_run
4968/// # use logicaffeine_compile::compile::{compile_to_dir, CompileError};
4969/// # use std::path::Path;
4970/// # fn main() -> Result<(), CompileError> {
4971/// let source = "## Main\nShow \"Hello\".";
4972/// compile_to_dir(source, Path::new("/tmp/my_project"))?;
4973/// // Now /tmp/my_project is a buildable Cargo project
4974/// # Ok(())
4975/// # }
4976/// ```
4977/// Everything [`rustc_check`] needs short of running cargo: generated Rust,
4978/// dependencies, the POPULATED rustc→LOGOS source map, and the interner the
4979/// program was compiled with — the substrate the diagnostic bridge translates
4980/// through.
4981pub struct CheckArtifacts {
4982    pub rust_code: String,
4983    pub dependencies: Vec<CrateDependency>,
4984    pub source_map: crate::sourcemap::SourceMap,
4985    pub interner: Interner,
4986}
4987
4988/// The offset in the author's own text that byte `pos` of the prelude-expanded text came from,
4989/// through the runs [`crate::loader::apply_prelude_mapped`] reports. A position inside spliced
4990/// stdlib text came from no byte the author wrote and maps to `None`; a run's END maps too, so an
4991/// exclusive span end and the end of the file translate.
4992pub fn prelude_user_offset(
4993    segments: &[crate::loader::PreludeSegment],
4994    pos: usize,
4995) -> Option<usize> {
4996    let mut at_end = None;
4997    for seg in segments {
4998        if pos >= seg.out_start && pos < seg.out_start + seg.len {
4999            return seg.user_start.map(|us| us + (pos - seg.out_start));
5000        }
5001        if pos == seg.out_start + seg.len {
5002            at_end = seg.user_start.map(|us| us + seg.len);
5003        }
5004    }
5005    at_end
5006}
5007
5008/// A span of the prelude-expanded text as a span of the author's own text — `None` when either
5009/// end lies in spliced stdlib text. The one inversion of the prelude splice: every surface that
5010/// reports a location against the author's file translates through this.
5011pub fn prelude_user_span(
5012    segments: &[crate::loader::PreludeSegment],
5013    span: crate::token::Span,
5014) -> Option<crate::token::Span> {
5015    match (
5016        prelude_user_offset(segments, span.start),
5017        prelude_user_offset(segments, span.end),
5018    ) {
5019        (Some(start), Some(end)) if start <= end => Some(crate::token::Span::new(start, end)),
5020        _ => None,
5021    }
5022}
5023
5024/// Compile for CHECKING: the same front as [`compile_program_full`] but with
5025/// the optimizer off and mapped codegen, so every generated line ties back to
5026/// its statement span and the map stays 1:1 (the optimizer may fuse or drop
5027/// statements; a check build has no use for its output anyway).
5028///
5029/// Deliberately does NOT bail on typecheck/escape/ownership findings — the
5030/// interactive pipeline already reports those; this path exists to surface
5031/// what only rustc can see, and a borrow error in the generated code comes
5032/// back TRANSLATED rather than pre-empted.
5033pub fn rustc_check_artifacts(source: &str) -> Result<CheckArtifacts, ParseError> {
5034    let user_source = source;
5035
5036    // The stdlib prelude is spliced in on demand — AFTER any leading
5037    // title/comment prose, and `## NoPrelude` strips its marker — so spans
5038    // from the parse are offsets into the expanded text and translate back
5039    // through the exact edit `apply_prelude` reports.
5040    let (prelude_src, prelude_segments) = crate::loader::apply_prelude_mapped(user_source);
5041    // Prune the DEAD prelude — the stdlib functions the whole-module splice pulled in
5042    // but the program never reaches — EXACTLY as `largo build` does before it parses
5043    // (`compile_project` = prune ∘ apply_prelude). Deep check then checks only what the
5044    // program executes and what the shipped binary contains: an UNREACHABLE stdlib
5045    // helper can never surface a finding (or a parse error) on code that never runs.
5046    let (pruned_src, kept_ranges) =
5047        crate::loader::prune_unreachable_prelude_mapped_from(user_source, prelude_src.as_ref());
5048    // Map an offset in the pre-prune (expanded) text to its offset in the pruned text:
5049    // the count of kept bytes lying before it. Only defined for kept offsets — every
5050    // user run is kept, which is all the span translation needs.
5051    let to_pruned = |x: usize| -> usize {
5052        let mut kept = 0usize;
5053        for &(s, e) in &kept_ranges {
5054            if e <= x {
5055                kept += e - s;
5056            } else if s < x {
5057                kept += x - s;
5058                break;
5059            } else {
5060                break;
5061            }
5062        }
5063        kept
5064    };
5065    // Rebuild the span segments in PRUNED coordinates. Only USER runs carry a mapping
5066    // (a spliced — or now pruned — prelude run maps to nothing); each user run's bytes
5067    // are intact and contiguous, so it shifts uniformly by the prelude removed before
5068    // it. Reuses the exact `user_pos` translation below, just over the pruned text.
5069    let prelude_segments: Vec<crate::loader::PreludeSegment> = prelude_segments
5070        .into_iter()
5071        .filter(|seg| seg.user_start.is_some())
5072        .map(|seg| crate::loader::PreludeSegment {
5073            out_start: to_pruned(seg.out_start),
5074            len: seg.len,
5075            user_start: seg.user_start,
5076        })
5077        .collect();
5078    let expanded: &str = pruned_src.as_str();
5079    let library = crate::loader::LibraryProvenance::of(expanded);
5080    for seg in &prelude_segments {
5081        if let Some(user_start) = seg.user_start {
5082            debug_assert_eq!(
5083                &expanded[seg.out_start..seg.out_start + seg.len],
5084                &user_source[user_start..user_start + seg.len],
5085                "prelude prune must keep user text byte-intact; span translation depends on it"
5086            );
5087        }
5088    }
5089
5090    let mut interner = Interner::new();
5091    let mut lexer = Lexer::new(expanded, &mut interner);
5092    let tokens = lexer.tokenize();
5093
5094    let (type_registry, policy_registry) = {
5095        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
5096        let result = discovery.run_full();
5097        (result.types, result.policies)
5098    };
5099    let codegen_policies = policy_registry.clone();
5100
5101    let mut world_state = WorldState::new();
5102    let expr_arena = Arena::new();
5103    let term_arena = Arena::new();
5104    let np_arena = Arena::new();
5105    let sym_arena = Arena::new();
5106    let role_arena = Arena::new();
5107    let pp_arena = Arena::new();
5108    let stmt_arena: Arena<Stmt> = Arena::new();
5109    let _compile_facts = crate::optimize::facts::scope();
5110    let imperative_expr_arena: Arena<Expr> = Arena::new();
5111    let type_expr_arena: Arena<TypeExpr> = Arena::new();
5112
5113    let ast_ctx = AstContext::with_types(
5114        &expr_arena,
5115        &term_arena,
5116        &np_arena,
5117        &sym_arena,
5118        &role_arena,
5119        &pp_arena,
5120        &stmt_arena,
5121        &imperative_expr_arena,
5122        &type_expr_arena,
5123    );
5124
5125    let mut parser = Parser::new(
5126        tokens,
5127        &mut world_state,
5128        &mut interner,
5129        ast_ctx,
5130        type_registry,
5131    );
5132    let stmts = parser.parse_program()?;
5133
5134    // Translate spans back into the USER buffer; spliced-prelude statements
5135    // become zero-width sentinels that mapped codegen skips.
5136    let stmt_spans: Vec<crate::token::Span> = parser
5137        .stmt_spans()
5138        .iter()
5139        .map(|span| prelude_user_span(&prelude_segments, *span).unwrap_or_default())
5140        .collect();
5141    let codegen_registry = parser.into_type_registry();
5142
5143    // Exact division still resolves (type semantics, statement-count
5144    // preserving); the optimizer stays OFF so spans align 1:1.
5145    let resolved = crate::resolve_program::resolve_program(
5146        &stmts,
5147        crate::ast_map::Arenas {
5148            exprs: &imperative_expr_arena,
5149            stmts: &stmt_arena,
5150            types: &type_expr_arena,
5151        },
5152        &mut interner,
5153        false,
5154        library.functions(),
5155    );
5156    let stmts: Vec<Stmt> = match resolved {
5157        Some(rw) => rw.to_vec(),
5158        None => stmts,
5159    };
5160    let lifted_from = stmts.len();
5161    let (stmts, codegen_registry) = lift_program_bindings(
5162        stmts,
5163        codegen_registry,
5164        &mut interner,
5165        crate::ast_map::Arenas {
5166            exprs: &imperative_expr_arena,
5167            stmts: &stmt_arena,
5168            types: &type_expr_arena,
5169        },
5170    )?;
5171    // The lift opens the program with the record's own `Let`, which no source line wrote.
5172    let stmt_spans: Vec<crate::token::Span> =
5173        std::iter::repeat_n(crate::token::Span::default(), stmts.len() - lifted_from)
5174            .chain(stmt_spans)
5175            .collect();
5176
5177    // Best-effort env: findings are the interactive pipeline's job here.
5178    let (type_env, _findings) =
5179        crate::analysis::check_program_collect(&stmts, &interner, &codegen_registry);
5180
5181    let dependencies = extract_dependencies(&stmts, &interner)?;
5182
5183    let (rust_code, source_map) = crate::codegen::codegen_program_mapped(
5184        &stmts,
5185        &codegen_registry,
5186        &codegen_policies,
5187        &interner,
5188        &type_env,
5189        &crate::optimization::OptimizationConfig::all_off(),
5190        &stmt_spans,
5191        user_source,
5192    );
5193
5194    Ok(CheckArtifacts {
5195        rust_code,
5196        dependencies,
5197        source_map,
5198        interner,
5199    })
5200}
5201
5202/// Run rustc's analysis over a LOGOS program and translate every finding
5203/// back to English with real user-source spans — the flycheck engine.
5204///
5205/// `cache_dir` is a persistent per-workspace directory: the first run stages
5206/// the runtime crates and compiles them; later runs are incremental. Uses
5207/// `cargo check` (no codegen, no linking).
5208///
5209/// Fail-loud contract: `Ok(vec![])` means cargo ran AND found nothing. A
5210/// cargo failure that translates to no LOGOS finding is a `Build` error, not
5211/// a silent all-clear.
5212pub fn rustc_check(source: &str, cache_dir: &Path) -> Result<Vec<LogosError>, CompileError> {
5213    let artifacts = rustc_check_artifacts(source).map_err(CompileError::Parse)?;
5214    write_cargo_project(&artifacts.rust_code, &artifacts.dependencies, cache_dir)?;
5215
5216    // The cache dir's own target, whatever the caller's environment says: under a shared
5217    // `CARGO_TARGET_DIR` a check of one program finds another's `logos_output` fingerprint fresh and
5218    // replays that program's diagnostics.
5219    let check_output = Command::new("cargo")
5220        .arg("check")
5221        .arg("--message-format=json")
5222        .current_dir(cache_dir)
5223        .env("CARGO_TARGET_DIR", cache_dir.join("target"))
5224        .output()
5225        .map_err(|e| CompileError::Io(e.to_string()))?;
5226
5227    let stdout = String::from_utf8_lossy(&check_output.stdout);
5228    let diagnostics = parse_rustc_json(&stdout);
5229    let findings = crate::diagnostic::translate_diagnostics_all(
5230        &diagnostics,
5231        &artifacts.source_map,
5232        &artifacts.interner,
5233    );
5234
5235    if !check_output.status.success() && findings.is_empty() {
5236        let stderr = String::from_utf8_lossy(&check_output.stderr);
5237        return Err(CompileError::Build(stderr.to_string()));
5238    }
5239
5240    Ok(findings)
5241}
5242
5243/// Remap every rustc error over a project's GENERATED Rust back to the LOGOS
5244/// source line it came from — the build path uses this so a generated-code
5245/// failure points at the LOGOS the user wrote, not `main.rs`. Compiles with the
5246/// source-mapped codegen (whose line numbers the map indexes), runs
5247/// `cargo check --message-format=json`, and remaps each diagnostic's primary
5248/// span. Returns `Ok(vec![])` when nothing maps (caller falls back to raw cargo
5249/// output).
5250pub fn remap_project_errors(
5251    source: &str,
5252    cache_dir: &Path,
5253    file_map: Option<&crate::analysis::SourceMap>,
5254) -> Result<Vec<crate::diagnostic::RemappedError>, CompileError> {
5255    let artifacts = rustc_check_artifacts(source).map_err(CompileError::Parse)?;
5256    write_cargo_project(&artifacts.rust_code, &artifacts.dependencies, cache_dir)?;
5257
5258    // The cache dir's own target, whatever the caller's environment says: under a shared
5259    // `CARGO_TARGET_DIR` a check of one program finds another's `logos_output` fingerprint fresh and
5260    // replays that program's diagnostics.
5261    let check_output = Command::new("cargo")
5262        .arg("check")
5263        .arg("--message-format=json")
5264        .current_dir(cache_dir)
5265        .env("CARGO_TARGET_DIR", cache_dir.join("target"))
5266        .output()
5267        .map_err(|e| CompileError::Io(e.to_string()))?;
5268
5269    let stdout = String::from_utf8_lossy(&check_output.stdout);
5270    let diagnostics = parse_rustc_json(&stdout);
5271
5272    // Attribute each LOGOS byte offset to its originating `.lg` file (multi-file)
5273    // via the assembler's byte-range→file map, when one is supplied.
5274    let file_of = |offset: usize| -> Option<String> {
5275        file_map
5276            .and_then(|m| m.file_for(offset))
5277            .and_then(|p| p.file_name())
5278            .and_then(|s| s.to_str())
5279            .map(String::from)
5280    };
5281    Ok(crate::diagnostic::remap_rustc_diagnostics(
5282        &diagnostics,
5283        &artifacts.source_map,
5284        &file_of,
5285    ))
5286}
5287
5288pub fn compile_to_dir(source: &str, output_dir: &Path) -> Result<(), CompileError> {
5289    let output = compile_program_full(source).map_err(CompileError::Parse)?;
5290    write_cargo_project(&output.rust_code, &output.dependencies, output_dir)
5291}
5292
5293/// How a generated project resolves the `logicaffeine` runtime crates.
5294///
5295/// Inside the monorepo we stage the crate *sources* beside the generated
5296/// program and path-depend on them (hackable, offline). An installed `largo`
5297/// has no checkout to stage from, so it version-depends on the published
5298/// crates.io releases pinned to this compiler's OWN version — the generated
5299/// Rust and the runtime API can then never drift.
5300pub enum RuntimeCrateSource {
5301    /// Monorepo checkout: stage sources under `./crates` and path-depend.
5302    Workspace,
5303    /// Standalone install: depend on the crates.io releases at `version`.
5304    Registry { version: String },
5305}
5306
5307impl RuntimeCrateSource {
5308    /// A monorepo checkout stages sources; anywhere else (an installed `largo`)
5309    /// pulls the matching crates.io release at this compiler's own version.
5310    pub fn detect() -> Self {
5311        match find_workspace_root() {
5312            Ok(_) => RuntimeCrateSource::Workspace,
5313            Err(_) => RuntimeCrateSource::Registry {
5314                version: env!("CARGO_PKG_VERSION").to_string(),
5315            },
5316        }
5317    }
5318
5319    /// True inside a checkout (stage sources + path-depend); false for an
5320    /// installed `largo` (nothing to copy — depend on crates.io).
5321    pub fn is_workspace(&self) -> bool {
5322        matches!(self, RuntimeCrateSource::Workspace)
5323    }
5324
5325    /// The `logicaffeine-data` dependency line for this source.
5326    pub fn data_dep(&self) -> String {
5327        match self {
5328            RuntimeCrateSource::Workspace => {
5329                "logicaffeine-data = { path = \"./crates/logicaffeine_data\" }".to_string()
5330            }
5331            // Exact-pin (`=`) so the generated Rust always links the runtime
5332            // whose API produced it — a caret would let a newer 0.x patch drift.
5333            RuntimeCrateSource::Registry { version } => {
5334                format!("logicaffeine-data = \"={version}\"")
5335            }
5336        }
5337    }
5338
5339    /// The `logicaffeine-system` dependency line carrying `features`.
5340    pub fn system_dep(&self, features: &[&str]) -> String {
5341        let feats = features
5342            .iter()
5343            .map(|f| format!("\"{f}\""))
5344            .collect::<Vec<_>>()
5345            .join(", ");
5346        match self {
5347            RuntimeCrateSource::Workspace => format!(
5348                "logicaffeine-system = {{ path = \"./crates/logicaffeine_system\", features = [{feats}] }}"
5349            ),
5350            RuntimeCrateSource::Registry { version } => {
5351                format!("logicaffeine-system = {{ version = \"={version}\", features = [{feats}] }}")
5352            }
5353        }
5354    }
5355
5356    /// The target section every generated project ends its dependencies with: on Linux the runtime
5357    /// carries `io-uring`, which cargo unifies with the features its `[dependencies]` line names,
5358    /// so a compiled server has the thread-per-core io_uring engine and the `UringVfs`, and every
5359    /// other target builds without them.
5360    pub fn linux_engine_section(&self) -> String {
5361        format!(
5362            "[target.'cfg(target_os = \"linux\")'.dependencies]\n{}\n",
5363            self.system_dep(&["full", "io-uring"])
5364        )
5365    }
5366}
5367
5368/// A declared field type's base name (`SharedMap` for `SharedMap from Text to Int`).
5369fn field_type_base_name<'i>(ty: &crate::analysis::FieldType, interner: &'i Interner) -> &'i str {
5370    use crate::analysis::FieldType;
5371    match ty {
5372        FieldType::Primitive(s) | FieldType::Named(s) | FieldType::TypeParam(s) => {
5373            interner.resolve(*s)
5374        }
5375        FieldType::Generic { base, .. } => interner.resolve(*base),
5376        FieldType::Tuple(_) => "Tuple",
5377        FieldType::Record(_) => "Record",
5378    }
5379}
5380
5381/// A backend that lowers compiled bytecode WITHOUT the Rust runtime — the tiers
5382/// [`refuse_unlinkable`] gates. What each one lowers is answered per construct against this type
5383/// (see [`crate::semantics::crdt::CrdtKind::lowered_by`]), so adding a backend fails to compile until
5384/// every such table classifies it.
5385#[derive(Clone, Copy, PartialEq, Eq, Debug)]
5386pub enum Backend {
5387    /// The bytecode → C op-walker (`compile_to_c_via_bytecode`).
5388    C,
5389    /// The AST → C backend (`compile_to_c`), which gates a program's declared field types itself.
5390    CFromAst,
5391    RiscV,
5392    WebAssembly,
5393    SoftCore,
5394}
5395
5396impl Backend {
5397    pub const ALL: [Backend; 5] = [
5398        Backend::C,
5399        Backend::CFromAst,
5400        Backend::RiscV,
5401        Backend::WebAssembly,
5402        Backend::SoftCore,
5403    ];
5404
5405    /// The backend's name in a refusal sentence.
5406    pub const fn name(self) -> &'static str {
5407        match self {
5408            Backend::C | Backend::CFromAst => "C",
5409            Backend::RiscV => "RISC-V",
5410            Backend::WebAssembly => "WebAssembly",
5411            Backend::SoftCore => "soft-core",
5412        }
5413    }
5414}
5415
5416/// The entry gate of every backend that lowers bytecode WITHOUT the Rust runtime (C, RISC-V,
5417/// WebAssembly, the soft core): refuse — by name — what only the interpreter, the VM, and the Rust tier
5418/// provide, rather than lower it as something else. A standard-library native kernel is Rust code; a
5419/// CRDT kind the backend does not lower is refused by its type name. Only code that can run is judged
5420/// ([`crate::vm::reach`]): the loader splices whole standard-library modules, and a function nothing
5421/// calls refuses nothing.
5422pub fn refuse_unlinkable(
5423    program: &crate::vm::CompiledProgram,
5424    interner: &Interner,
5425    backend: Backend,
5426) -> Result<(), String> {
5427    refuse_unlinkable_with(
5428        program,
5429        interner,
5430        backend,
5431        &crate::vm::reach::HostEntries::default(),
5432    )
5433}
5434
5435/// [`refuse_unlinkable`], judging what the host's own `entries` reach as well as Main — the same
5436/// roots a module built with those entries lowers.
5437pub fn refuse_unlinkable_with(
5438    program: &crate::vm::CompiledProgram,
5439    interner: &Interner,
5440    backend: Backend,
5441    entries: &crate::vm::reach::HostEntries,
5442) -> Result<(), String> {
5443    crate::semantics::native_kernels::refuse_kernel_calls_with(
5444        program,
5445        interner,
5446        backend.name(),
5447        entries,
5448    )?;
5449    for (_, op) in crate::vm::reach::running_ops_with(program, interner, entries) {
5450        if let crate::vm::Op::NewCrdt { kind, .. } = *op {
5451            if let Some(k) = crate::semantics::crdt::CrdtKind::from_new_crdt_code(kind) {
5452                if !k.lowered_by(backend) {
5453                    return Err(k.refusal(backend.name()));
5454                }
5455            }
5456        }
5457    }
5458    Ok(())
5459}
5460
5461/// The third-party crates the generated Rust names DIRECTLY (not through the runtime crates), each as
5462/// its `[dependencies]` line: declared iff the code uses it, and never when a `## Requires` already
5463/// brought it in (a duplicate key is a manifest error). The ONE list every generated manifest — the
5464/// `largo build` project and the staged checking project — takes its implied dependencies from.
5465pub fn implied_crate_deps(rust_code: &str, requires: &[CrateDependency]) -> Vec<&'static str> {
5466    const IMPLIED: &[(&str, &str, &str)] = &[
5467        // The parallel-reduction codegen (`rayon::prelude::*`) and `Simultaneously:` (`rayon::join`).
5468        ("rayon", "rayon::", "rayon = \"1\""),
5469        // The stdlib text-search intrinsic's SIMD `memchr`/`memmem`.
5470        ("memchr", "memchr::", "memchr = \"2\""),
5471        // `Shared`/`Portable` types derive `serde::Serialize`/`Deserialize` (sync + wire).
5472        (
5473            "serde",
5474            "serde::",
5475            "serde = { version = \"1\", features = [\"derive\"] }",
5476        ),
5477    ];
5478    IMPLIED
5479        .iter()
5480        .filter(|(name, marker, _)| {
5481            rust_code.contains(marker) && !requires.iter().any(|d| d.name == *name)
5482        })
5483        .map(|(_, _, line)| *line)
5484        .collect()
5485}
5486
5487/// Render the generated project's `Cargo.toml`. `source` selects staged path
5488/// deps (in-workspace) vs. crates.io version deps (standalone install); the
5489/// feature sets, tokio, user `## Requires` deps, and release profile are
5490/// identical either way.
5491fn render_cargo_manifest(
5492    rust_code: &str,
5493    dependencies: &[CrateDependency],
5494    source: &RuntimeCrateSource,
5495) -> String {
5496    let data_dep = source.data_dep();
5497    // A `Serve` program's generated code names `logicaffeine_system::http`;
5498    // the staged project must carry the same runtime feature the real build
5499    // manifest (`project/build.rs`) does, or checking a web handler drowns
5500    // the user in phantom findings.
5501    let system_features: &[&str] = if rust_code.contains("logicaffeine_system::http::") {
5502        &["full", "http"]
5503    } else {
5504        &["full"]
5505    };
5506    let system_dep = source.system_dep(system_features);
5507
5508    let mut cargo_toml = format!(
5509        "[package]\n\
5510         name = \"logos_output\"\n\
5511         version = \"0.1.0\"\n\
5512         edition = \"2021\"\n\
5513         \n\
5514         [dependencies]\n\
5515         {data_dep}\n\
5516         {system_dep}\n\
5517         tokio = {{ version = \"1\", features = [\"rt-multi-thread\", \"macros\"] }}\n"
5518    );
5519
5520    // User-declared `## Requires` deps — inside [dependencies], before any later
5521    // section header (a dep after a [target.*]/[profile.*] header changes meaning).
5522    for dep in dependencies {
5523        if dep.features.is_empty() {
5524            let _ = writeln!(cargo_toml, "{} = \"{}\"", dep.name, dep.version);
5525        } else {
5526            let feats = dep
5527                .features
5528                .iter()
5529                .map(|f| format!("\"{}\"", f))
5530                .collect::<Vec<_>>()
5531                .join(", ");
5532            let _ = writeln!(
5533                cargo_toml,
5534                "{} = {{ version = \"{}\", features = [{}] }}",
5535                dep.name, dep.version, feats
5536            );
5537        }
5538    }
5539
5540    for line in implied_crate_deps(rust_code, dependencies) {
5541        let _ = writeln!(cargo_toml, "{line}");
5542    }
5543
5544    let _ = write!(cargo_toml, "\n{}", source.linux_engine_section());
5545
5546    let panic_strategy = crate::codegen::release_panic_strategy(rust_code);
5547    let _ = write!(cargo_toml, "\n[profile.release]\nlto = true\nopt-level = 3\ncodegen-units = 1\npanic = \"{panic_strategy}\"\nstrip = true\n");
5548    cargo_toml
5549}
5550
5551/// Write a generated program as a runnable cargo project: `src/main.rs`,
5552/// `Cargo.toml` (runtime deps + user `## Requires`), `.cargo/config.toml`, and
5553/// — only inside a checkout — the staged runtime crates. Shared by
5554/// [`compile_to_dir`] and [`rustc_check`].
5555pub fn write_cargo_project(
5556    rust_code: &str,
5557    dependencies: &[CrateDependency],
5558    output_dir: &Path,
5559) -> Result<(), CompileError> {
5560    let source = RuntimeCrateSource::detect();
5561
5562    // Create output directory structure
5563    let src_dir = output_dir.join("src");
5564    fs::create_dir_all(&src_dir).map_err(|e| CompileError::Io(e.to_string()))?;
5565
5566    // Write main.rs (codegen already includes the use statements)
5567    let main_path = src_dir.join("main.rs");
5568    let mut file = fs::File::create(&main_path).map_err(|e| CompileError::Io(e.to_string()))?;
5569    file.write_all(rust_code.as_bytes())
5570        .map_err(|e| CompileError::Io(e.to_string()))?;
5571
5572    // Write Cargo.toml with runtime crate dependencies
5573    let cargo_toml = render_cargo_manifest(rust_code, dependencies, &source);
5574    let cargo_path = output_dir.join("Cargo.toml");
5575    let mut file = fs::File::create(&cargo_path).map_err(|e| CompileError::Io(e.to_string()))?;
5576    file.write_all(cargo_toml.as_bytes())
5577        .map_err(|e| CompileError::Io(e.to_string()))?;
5578
5579    // Write .cargo/config.toml with target-cpu=native for optimal codegen.
5580    // Enables SIMD auto-vectorization and CPU-specific instruction selection.
5581    let cargo_config_dir = output_dir.join(".cargo");
5582    fs::create_dir_all(&cargo_config_dir).map_err(|e| CompileError::Io(e.to_string()))?;
5583    let config_content = "[build]\nrustflags = [\"-C\", \"target-cpu=native\"]\n";
5584    let config_path = cargo_config_dir.join("config.toml");
5585    fs::write(&config_path, config_content).map_err(|e| CompileError::Io(e.to_string()))?;
5586
5587    // Stage the runtime sources only inside a checkout; a standalone install
5588    // pulls them from crates.io, so there is nothing to copy.
5589    if source.is_workspace() {
5590        copy_runtime_crates(output_dir)?;
5591    }
5592
5593    Ok(())
5594}
5595
5596/// Copy the runtime crates to the output directory.
5597/// Copies logicaffeine_data and logicaffeine_system.
5598pub fn copy_runtime_crates(output_dir: &Path) -> Result<(), CompileError> {
5599    let crates_dir = output_dir.join("crates");
5600    fs::create_dir_all(&crates_dir).map_err(|e| CompileError::Io(e.to_string()))?;
5601
5602    // Find workspace root
5603    let workspace_root = find_workspace_root()?;
5604    let workspace = WorkspacePackage::read(&workspace_root)?;
5605
5606    // Copy logicaffeine_data
5607    let data_src = workspace_root.join(CRATES_DATA_PATH);
5608    let data_dest = crates_dir.join("logicaffeine_data");
5609    copy_dir_recursive(&data_src, &data_dest)?;
5610    deworkspace_cargo_toml(&data_dest.join("Cargo.toml"), &workspace)?;
5611
5612    // Copy logicaffeine_system
5613    let system_src = workspace_root.join(CRATES_SYSTEM_PATH);
5614    let system_dest = crates_dir.join("logicaffeine_system");
5615    copy_dir_recursive(&system_src, &system_dest)?;
5616    deworkspace_cargo_toml(&system_dest.join("Cargo.toml"), &workspace)?;
5617
5618    // Also need to copy logicaffeine_base since both crates depend on it
5619    let base_src = workspace_root.join("crates/logicaffeine_base");
5620    let base_dest = crates_dir.join("logicaffeine_base");
5621    copy_dir_recursive(&base_src, &base_dest)?;
5622    deworkspace_cargo_toml(&base_dest.join("Cargo.toml"), &workspace)?;
5623
5624    // ★ AND THE WORKSPACE'S LOCKFILE. A generated project has no `Cargo.lock`, so cargo resolves
5625    // every transitive dependency to the newest version its requirement ALLOWS — which is not the
5626    // set this workspace has ever built. The copied crates carry unpinned minors by design
5627    // (`rustls = { version = "0.23", … }`), and on 2026-09-11 a fresh resolve paired rustls 0.23.44
5628    // with a `ring` that no longer satisfies it: 16 errors inside rustls itself
5629    // (`SystemRandom: SecureRandom` unsatisfied, `UnixTime::now` gone), none of them in generated
5630    // code, failing `hotswap_p17_wasm::scalar_function_builds_to_a_wasm_module` on all 3 attempts.
5631    //
5632    // Seeding the lock makes a generated build resolve to exactly the versions the workspace has
5633    // verified, so crates.io moving underneath us can no longer break a build nobody changed.
5634    // Cargo still updates it for anything genuinely new, so this pins without freezing.
5635    let lock_src = workspace_root.join("Cargo.lock");
5636    let lock_dest = output_dir.join("Cargo.lock");
5637    if lock_src.exists() && !lock_dest.exists() {
5638        fs::copy(&lock_src, &lock_dest).map_err(|e| CompileError::Io(e.to_string()))?;
5639    }
5640
5641    Ok(())
5642}
5643
5644/// The settings a staged crate inherits from the workspace, read from `[workspace.package]` in the
5645/// root `Cargo.toml`, so a standalone copy declares exactly the edition and minimum Rust the
5646/// workspace does.
5647struct WorkspacePackage {
5648    edition: String,
5649    rust_version: String,
5650}
5651
5652impl WorkspacePackage {
5653    fn read(workspace_root: &Path) -> Result<WorkspacePackage, CompileError> {
5654        let manifest = workspace_root.join("Cargo.toml");
5655        let text = fs::read_to_string(&manifest)
5656            .map_err(|e| CompileError::Io(format!("{}: {e}", manifest.display())))?;
5657        Self::parse(&text).ok_or_else(|| {
5658            CompileError::Io(format!(
5659                "{} declares no `edition` and `rust-version` under [workspace.package]",
5660                manifest.display()
5661            ))
5662        })
5663    }
5664
5665    /// The quoted `edition` and `rust-version` values of the `[workspace.package]` table.
5666    fn parse(root_manifest: &str) -> Option<WorkspacePackage> {
5667        let mut in_table = false;
5668        let (mut edition, mut rust_version) = (None, None);
5669        for line in root_manifest.lines() {
5670            let t = line.trim();
5671            if t.starts_with('[') {
5672                in_table = t == "[workspace.package]";
5673                continue;
5674            }
5675            let Some((key, value)) = t.split_once('=').filter(|_| in_table) else {
5676                continue;
5677            };
5678            let Some(quoted) = value
5679                .trim()
5680                .strip_prefix('"')
5681                .and_then(|v| v.split_once('"'))
5682                .map(|(v, _)| v.to_string())
5683            else {
5684                continue;
5685            };
5686            match key.trim() {
5687                "edition" => edition = Some(quoted),
5688                "rust-version" => rust_version = Some(quoted),
5689                _ => {}
5690            }
5691        }
5692        Some(WorkspacePackage {
5693            edition: edition?,
5694            rust_version: rust_version?,
5695        })
5696    }
5697}
5698
5699/// Resolve workspace-inherited fields in a copied crate's Cargo.toml.
5700///
5701/// When runtime crates are copied to a standalone project, any fields using
5702/// `*.workspace = true` won't resolve because there's no parent workspace.
5703/// This rewrites them with the workspace's own values.
5704fn deworkspace_cargo_toml(
5705    cargo_toml_path: &Path,
5706    workspace: &WorkspacePackage,
5707) -> Result<(), CompileError> {
5708    let content =
5709        fs::read_to_string(cargo_toml_path).map_err(|e| CompileError::Io(e.to_string()))?;
5710
5711    let mut result = String::with_capacity(content.len());
5712    for line in content.lines() {
5713        let trimmed = line.trim();
5714        if trimmed == "edition.workspace = true" {
5715            result.push_str(&format!("edition = \"{}\"", workspace.edition));
5716        } else if trimmed == "rust-version.workspace = true" {
5717            result.push_str(&format!("rust-version = \"{}\"", workspace.rust_version));
5718        } else if trimmed == "authors.workspace = true"
5719            || trimmed == "repository.workspace = true"
5720            || trimmed == "homepage.workspace = true"
5721            || trimmed == "documentation.workspace = true"
5722            || trimmed == "keywords.workspace = true"
5723            || trimmed == "categories.workspace = true"
5724            || trimmed == "license.workspace = true"
5725        {
5726            // Drop these lines — they're metadata not needed for compilation
5727            continue;
5728        } else if trimmed.contains(".workspace = true") {
5729            // Catch-all: drop any other workspace-inherited fields
5730            continue;
5731        } else if let Some(rewritten) = deworkspace_dep_line(trimmed)? {
5732            // A dependency-TABLE inheritance (`name = { workspace = true, … }`):
5733            // internal crates are staged side-by-side under `crates/`, so the
5734            // inherited entry rewrites to a sibling path (extra keys kept).
5735            result.push_str(&rewritten);
5736        } else {
5737            result.push_str(line);
5738        }
5739        result.push('\n');
5740    }
5741
5742    fs::write(cargo_toml_path, result).map_err(|e| CompileError::Io(e.to_string()))?;
5743
5744    Ok(())
5745}
5746
5747/// Rewrite a `name = { workspace = true, … }` DEPENDENCY line for a staged
5748/// crate. Internal `logicaffeine-*` deps become sibling-path deps (the staged
5749/// layout puts every runtime crate under one `crates/` directory); any other
5750/// key on the line (`features`, `optional`, …) is preserved. A THIRD-PARTY
5751/// workspace-inherited dep fails LOUDLY here — at staging time, with the dep
5752/// named — instead of as an opaque cargo resolution error deep in a build log.
5753/// Returns `Ok(None)` for lines that are not workspace-dep tables.
5754fn deworkspace_dep_line(trimmed: &str) -> Result<Option<String>, CompileError> {
5755    let Some((name_part, rest)) = trimmed.split_once('=') else {
5756        return Ok(None);
5757    };
5758    let rest = rest.trim();
5759    if !rest.starts_with('{') || !rest.ends_with('}') || !rest.contains("workspace = true") {
5760        return Ok(None);
5761    }
5762    let name = name_part.trim();
5763    if !name
5764        .chars()
5765        .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
5766    {
5767        return Ok(None);
5768    }
5769    let extra_keys: Vec<&str> = rest[1..rest.len() - 1]
5770        .split(',')
5771        .map(str::trim)
5772        .filter(|k| !k.is_empty() && *k != "workspace = true")
5773        .collect();
5774    if !name.starts_with("logicaffeine-") {
5775        return Err(CompileError::Io(format!(
5776            "staged crate inherits third-party dependency `{}` from the workspace — \
5777             declare a concrete version in the crate's Cargo.toml (the staged copy \
5778             has no workspace root to inherit from)",
5779            name
5780        )));
5781    }
5782    let dir = name.replace('-', "_");
5783    let mut entry = format!("{} = {{ path = \"../{}\"", name, dir);
5784    for key in extra_keys {
5785        entry.push_str(", ");
5786        entry.push_str(key);
5787    }
5788    entry.push_str(" }");
5789    Ok(Some(entry))
5790}
5791
5792/// Find the workspace root directory.
5793pub(crate) fn find_workspace_root() -> Result<std::path::PathBuf, CompileError> {
5794    // 1. Explicit override via LOGOS_WORKSPACE env var
5795    if let Ok(workspace) = std::env::var("LOGOS_WORKSPACE") {
5796        let path = Path::new(&workspace);
5797        if path.join("Cargo.toml").exists() && path.join("crates").exists() {
5798            return Ok(path.to_path_buf());
5799        }
5800    }
5801
5802    // 2. Try CARGO_MANIFEST_DIR (works during cargo build of largo itself)
5803    if let Ok(manifest_dir) = std::env::var("CARGO_MANIFEST_DIR") {
5804        let path = Path::new(&manifest_dir);
5805        if let Some(parent) = path.parent().and_then(|p| p.parent()) {
5806            if parent.join("Cargo.toml").exists() {
5807                return Ok(parent.to_path_buf());
5808            }
5809        }
5810    }
5811
5812    // 3. Infer from the largo binary's own location
5813    //    e.g. /workspace/target/release/largo → /workspace
5814    if let Ok(exe) = std::env::current_exe() {
5815        if let Some(dir) = exe.parent() {
5816            // Walk up from the binary's directory
5817            let mut candidate = dir.to_path_buf();
5818            for _ in 0..5 {
5819                if candidate.join("Cargo.toml").exists() && candidate.join("crates").exists() {
5820                    return Ok(candidate);
5821                }
5822                if !candidate.pop() {
5823                    break;
5824                }
5825            }
5826        }
5827    }
5828
5829    // 4. Fallback to current directory traversal
5830    let mut current = std::env::current_dir().map_err(|e| CompileError::Io(e.to_string()))?;
5831
5832    loop {
5833        if current.join("Cargo.toml").exists() && current.join("crates").exists() {
5834            return Ok(current);
5835        }
5836        if !current.pop() {
5837            return Err(CompileError::Io(
5838                "Could not find workspace root. Set LOGOS_WORKSPACE env var or run from within the workspace.".to_string()
5839            ));
5840        }
5841    }
5842}
5843
5844/// Recursively copy a directory.
5845/// Skips files that disappear during copy (race condition with parallel builds).
5846fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<(), CompileError> {
5847    fs::create_dir_all(dst).map_err(|e| CompileError::Io(e.to_string()))?;
5848
5849    for entry in fs::read_dir(src).map_err(|e| CompileError::Io(e.to_string()))? {
5850        let entry = entry.map_err(|e| CompileError::Io(e.to_string()))?;
5851        let src_path = entry.path();
5852        let file_name = entry.file_name();
5853        let dst_path = dst.join(&file_name);
5854
5855        // Skip target directory, build artifacts, and lock files
5856        if file_name == "target"
5857            || file_name == ".git"
5858            || file_name == "Cargo.lock"
5859            || file_name == ".DS_Store"
5860        {
5861            continue;
5862        }
5863
5864        // Skip files that start with a dot (hidden files)
5865        if file_name.to_string_lossy().starts_with('.') {
5866            continue;
5867        }
5868
5869        // Check if path still exists (race condition protection)
5870        if !src_path.exists() {
5871            continue;
5872        }
5873
5874        if src_path.is_dir() {
5875            copy_dir_recursive(&src_path, &dst_path)?;
5876        } else if file_name == "Cargo.toml" {
5877            // Special handling for Cargo.toml: remove [workspace] line
5878            // which can interfere with nested crate dependencies
5879            match fs::read_to_string(&src_path) {
5880                Ok(content) => {
5881                    let filtered: String = content
5882                        .lines()
5883                        .filter(|line| !line.trim().starts_with("[workspace]"))
5884                        .collect::<Vec<_>>()
5885                        .join("\n");
5886                    fs::write(&dst_path, filtered).map_err(|e| CompileError::Io(e.to_string()))?;
5887                }
5888                Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
5889                Err(e) => return Err(CompileError::Io(e.to_string())),
5890            }
5891        } else {
5892            match fs::copy(&src_path, &dst_path) {
5893                Ok(_) => {}
5894                Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
5895                Err(e) => return Err(CompileError::Io(e.to_string())),
5896            }
5897        }
5898    }
5899
5900    Ok(())
5901}
5902
5903/// Compile and run a LOGOS program end-to-end.
5904///
5905/// This function performs the full compilation workflow:
5906/// 1. Compile LOGOS to Rust via [`compile_to_dir`]
5907/// 2. Run `cargo build` with JSON diagnostics
5908/// 3. Translate any rustc errors to LOGOS-friendly messages
5909/// 4. Run the compiled program via `cargo run`
5910///
5911/// # Arguments
5912///
5913/// * `source` - LOGOS source code as a string
5914/// * `output_dir` - Directory to create the temporary Cargo project in
5915///
5916/// # Returns
5917///
5918/// The stdout output of the executed program.
5919///
5920/// # Errors
5921///
5922/// Returns [`CompileError`] if:
5923/// - Compilation fails (see [`compile_to_dir`])
5924/// - Rust compilation fails (`CompileError::Build` or `CompileError::Ownership`)
5925/// - The program crashes at runtime (`CompileError::Runtime`)
5926///
5927/// # Diagnostic Translation
5928///
5929/// When rustc reports errors (e.g., E0382 for use-after-move), this function
5930/// uses the [`diagnostic`](crate::diagnostic) module to translate them into
5931/// LOGOS-friendly Socratic error messages.
5932///
5933/// # Example
5934///
5935/// ```no_run
5936/// # use logicaffeine_compile::compile::{compile_and_run, CompileError};
5937/// # use std::path::Path;
5938/// # fn main() -> Result<(), CompileError> {
5939/// let source = "## Main\nShow \"Hello, World!\".";
5940/// let output = compile_and_run(source, Path::new("/tmp/run"))?;
5941/// assert_eq!(output.trim(), "Hello, World!");
5942/// # Ok(())
5943/// # }
5944/// ```
5945pub fn compile_and_run(source: &str, output_dir: &Path) -> Result<String, CompileError> {
5946    // Pre-check: catch ownership errors (use-after-move) with friendly messages
5947    // before codegen runs (codegen defensively clones, masking these errors)
5948    compile_to_rust_checked(source).map_err(CompileError::Parse)?;
5949
5950    compile_to_dir(source, output_dir)?;
5951
5952    // Every generated package is named `logos_output`, so the project builds into ITS OWN target
5953    // whatever the caller's environment says. Under an inherited `CARGO_TARGET_DIR` two projects
5954    // share one `target/debug/logos_output`: the second build finds the first's fingerprint fresh
5955    // and `cargo run` starts whichever program linked last.
5956    let target_dir = output_dir.join("target");
5957
5958    // Run cargo build with JSON message format for structured error parsing
5959    let build_output = Command::new("cargo")
5960        .arg("build")
5961        .arg("--message-format=json")
5962        .current_dir(output_dir)
5963        .env("CARGO_TARGET_DIR", &target_dir)
5964        .output()
5965        .map_err(|e| CompileError::Io(e.to_string()))?;
5966
5967    if !build_output.status.success() {
5968        let stderr = String::from_utf8_lossy(&build_output.stderr);
5969        let stdout = String::from_utf8_lossy(&build_output.stdout);
5970
5971        // Try to parse JSON diagnostics and translate them
5972        let diagnostics = parse_rustc_json(&stdout);
5973
5974        if !diagnostics.is_empty() {
5975            // Create a basic source map with the LOGOS source
5976            let source_map = SourceMap::new(source.to_string());
5977            let interner = Interner::new();
5978
5979            if let Some(logos_error) = translate_diagnostics(&diagnostics, &source_map, &interner) {
5980                return Err(CompileError::Ownership(logos_error));
5981            }
5982        }
5983
5984        // Fallback to raw error if translation fails
5985        return Err(CompileError::Build(stderr.to_string()));
5986    }
5987
5988    // Run the compiled program
5989    let run_output = Command::new("cargo")
5990        .arg("run")
5991        .arg("--quiet")
5992        .current_dir(output_dir)
5993        .env("CARGO_TARGET_DIR", &target_dir)
5994        .output()
5995        .map_err(|e| CompileError::Io(e.to_string()))?;
5996
5997    if !run_output.status.success() {
5998        let stderr = String::from_utf8_lossy(&run_output.stderr);
5999        return Err(CompileError::Runtime(stderr.to_string()));
6000    }
6001
6002    let stdout = String::from_utf8_lossy(&run_output.stdout);
6003    Ok(stdout.to_string())
6004}
6005
6006/// Compile a LOGOS source file.
6007/// For single-file compilation without dependencies.
6008pub fn compile_file(path: &Path) -> Result<String, CompileError> {
6009    let source = fs::read_to_string(path).map_err(|e| CompileError::Io(e.to_string()))?;
6010    compile_to_rust(&source).map_err(CompileError::Parse)
6011}
6012
6013/// Compile a multi-file LOGOS project with dependency resolution.
6014///
6015/// This function:
6016/// 1. Reads the entry file
6017/// 2. Scans for dependencies in the abstract (Markdown links)
6018/// 3. Recursively loads and discovers types from dependencies
6019/// 4. Compiles with the combined type registry
6020///
6021/// # Arguments
6022/// * `entry_file` - The main entry file to compile (root is derived from parent directory)
6023///
6024/// # Example
6025/// ```no_run
6026/// # use logicaffeine_compile::compile::compile_project;
6027/// # use std::path::Path;
6028/// let result = compile_project(Path::new("/project/main.md"));
6029/// ```
6030pub fn compile_project(entry_file: &Path) -> Result<CompileOutput, CompileError> {
6031    compile_project_with_deps(entry_file, Vec::new())
6032}
6033
6034/// [`compile_project`], additionally linking the declared dependency roots (see
6035/// [`assemble_project_with_deps`](crate::analysis::assemble_project_with_deps)).
6036/// `dep_roots` empty is byte-for-byte identical to [`compile_project`].
6037pub fn compile_project_with_deps(
6038    entry_file: &Path,
6039    dep_roots: Vec<crate::loader::DepRoot>,
6040) -> Result<CompileOutput, CompileError> {
6041    use crate::analysis::{assemble_project_with_deps, discover_with_imports};
6042    use crate::loader::Loader;
6043
6044    let root_path = entry_file.parent().unwrap_or(Path::new(".")).to_path_buf();
6045    let mut loader = Loader::with_dep_roots(root_path, dep_roots.clone());
6046    let mut interner = Interner::new();
6047
6048    // Assemble the whole project into ONE compilation unit: the entry with every
6049    // imported module's code (functions + type defs) spliced in, dependency-first
6050    // and cycle-safe. This is the seam that makes cross-file FUNCTION calls resolve
6051    // — imported `## To` definitions now reach the parser, call graph, and codegen
6052    // exactly as a single-file program's do.
6053    let assembled = assemble_project_with_deps(entry_file, dep_roots).map_err(CompileError::Io)?;
6054
6055    // Auto-import the demand-driven stdlib prelude (uuid.lg, io/net/crdt/time/…) — the SAME seam the
6056    // string-compile and interpreter paths use (see `apply_prelude`), so `largo build` resolves stdlib
6057    // functions like `md5`/`sha1`/`uuidV3`/`uuidParse`/`flush`. Demand-driven + idempotent: a program
6058    // that references no stdlib name compiles byte-identically to before. Then drop the DEAD prelude
6059    // functions the whole-module splice pulled in but the project never reaches (a postgres app pulls all
6060    // of crypto.lg for the SCRAM/MD5 auth path, but never the ML-DSA signature functions) — never touching
6061    // a user function, byte-identical when nothing is dead, so the AOT-Rust backend compiles only what the
6062    // program executes, exactly as `compile_program_full` does for the single-source path.
6063    let source = crate::loader::prune_unreachable_prelude_from(
6064        &assembled.source,
6065        crate::loader::apply_prelude(&assembled.source).as_ref(),
6066    );
6067
6068    // Discover types from the entry file and all imports (namespaced `Alias::Type`).
6069    let type_registry = discover_with_imports(entry_file, &source, &mut loader, &mut interner)
6070        .map_err(|e| CompileError::Io(e))?;
6071
6072    // Now compile with the discovered types, enforcing per-file scoping. A parse
6073    // error is attributed back to the SOURCE FILE it came from (not an offset in
6074    // the merged source the user never wrote).
6075    compile_to_rust_with_registry_full(
6076        &source,
6077        type_registry,
6078        &mut interner,
6079        Some(&assembled.scope),
6080    )
6081    .map_err(|pe| attribute_parse_error(pe, &assembled, &source))
6082}
6083
6084/// Attribute a parse error in a multi-file build back to the file it came from,
6085/// naming that file in the message. Best-effort: if the location can't be mapped,
6086/// the original error is returned unchanged.
6087///
6088/// The parse ran over `final_source` — the assembled program with the stdlib prelude spliced in as
6089/// ONE run after any leading prose (pruning keeps it one run) — so its span is moved back into the
6090/// assembled program's own coordinates, the ones every surface locates against: past the run it
6091/// moves back by the run's length, and a span inside the run names text the author never wrote and
6092/// carries no place (`Span::default()`).
6093fn attribute_parse_error(
6094    pe: ParseError,
6095    assembled: &crate::analysis::AssembledProgram,
6096    final_source: &str,
6097) -> CompileError {
6098    let prelude_len = final_source.len().saturating_sub(assembled.source.len());
6099    let insert_at = if assembled.source.starts_with("##") {
6100        0
6101    } else {
6102        assembled.source.find("\n##").map(|i| i + 1).unwrap_or(0)
6103    };
6104    let to_assembled = |at: usize| -> Option<usize> {
6105        if prelude_len == 0 || at <= insert_at {
6106            Some(at)
6107        } else if at >= insert_at + prelude_len {
6108            Some(at - prelude_len)
6109        } else {
6110            None
6111        }
6112    };
6113    let span = match (to_assembled(pe.span.start), to_assembled(pe.span.end)) {
6114        (Some(start), Some(end)) if start <= end => crate::token::Span::new(start, end),
6115        _ => crate::token::Span::default(),
6116    };
6117    let pe = ParseError { span, ..pe };
6118    // Scope/collision diagnostics are already well-formed (they name their files);
6119    // only raw syntax errors need location attribution.
6120    if matches!(pe.kind, crate::error::ParseErrorKind::Custom(_)) {
6121        return CompileError::Parse(pe);
6122    }
6123
6124    // Only IMPORTED-module errors need re-attribution — an error in the entry
6125    // file already reports correctly, and re-wrapping it would change the
6126    // single-file diagnostic format the CLI pins.
6127    if let Some(file) = assembled.source_map.file_for(pe.span.start) {
6128        if file != assembled.scope.entry() {
6129            if let Some(name) = file.file_name().and_then(|s| s.to_str()) {
6130                return CompileError::Parse(ParseError {
6131                    kind: crate::error::ParseErrorKind::Custom(format!(
6132                        "in `{name}`: {}",
6133                        describe_parse_error(&pe)
6134                    )),
6135                    span: pe.span,
6136                });
6137            }
6138        }
6139    }
6140    CompileError::Parse(pe)
6141}
6142
6143/// The author-facing sentence for a parse error in an imported module: the same explanation an
6144/// entry-file error carries (`ParseError::diagnostic_parts`). `socratic_explanation` matches every
6145/// `ParseErrorKind` with no wildcard arm, so a new kind cannot reach the author unexplained.
6146pub(crate) fn describe_parse_error(pe: &ParseError) -> String {
6147    crate::error::socratic_explanation(pe, &Interner::new())
6148}
6149
6150/// Enforce per-file scoping for a project WITHOUT codegen. The interpreter and
6151/// other lightweight tiers call this so transitive leakage is rejected uniformly
6152/// with `largo build` — a program that fails scoping on one tier fails on all.
6153/// Returns `Ok(())` when every reference stays within its file's scope, else the
6154/// clean scope-violation message.
6155pub fn enforce_project_scope(entry_file: &Path) -> Result<(), String> {
6156    enforce_project_scope_with_deps(entry_file, Vec::new()).map_err(|e| e.to_string())
6157}
6158
6159/// Why a project fails [`enforce_project_scope_with_deps`].
6160#[derive(Debug)]
6161pub enum ProjectScopeError {
6162    /// The assembled program does not parse — the parser's own error, so a surface can show it
6163    /// where it is rather than as a sentence with no place.
6164    Parse(ParseError),
6165    /// The project does not assemble, or a file reaches a name it neither defines nor imports.
6166    Refused(String),
6167}
6168
6169impl std::fmt::Display for ProjectScopeError {
6170    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
6171        match self {
6172            ProjectScopeError::Parse(pe) => f.write_str(&describe_parse_error(pe)),
6173            ProjectScopeError::Refused(why) => f.write_str(why),
6174        }
6175    }
6176}
6177
6178impl std::error::Error for ProjectScopeError {}
6179
6180/// [`enforce_project_scope`], additionally linking the declared dependency roots.
6181/// `dep_roots` empty is identical to [`enforce_project_scope`].
6182pub fn enforce_project_scope_with_deps(
6183    entry_file: &Path,
6184    dep_roots: Vec<crate::loader::DepRoot>,
6185) -> Result<(), ProjectScopeError> {
6186    use crate::analysis::{assemble_project_with_deps, check_scopes, discover_with_imports};
6187    use crate::loader::Loader;
6188
6189    let root_path = entry_file.parent().unwrap_or(Path::new(".")).to_path_buf();
6190    let mut loader = Loader::with_dep_roots(root_path, dep_roots.clone());
6191    let mut interner = Interner::new();
6192
6193    let assembled =
6194        assemble_project_with_deps(entry_file, dep_roots).map_err(ProjectScopeError::Refused)?;
6195    let source = crate::loader::apply_prelude(&assembled.source).into_owned();
6196    let type_registry = discover_with_imports(entry_file, &source, &mut loader, &mut interner)
6197        .map_err(ProjectScopeError::Refused)?;
6198
6199    let mut lexer = Lexer::new(&source, &mut interner);
6200    let mut tokens = lexer.tokenize();
6201    let functions = crate::analysis::assemble::defined_function_names(&source);
6202    crate::analysis::assemble::resolve_qualified_names(&mut tokens, &mut interner, &functions);
6203
6204    let mut world_state = WorldState::new();
6205    let expr_arena = Arena::new();
6206    let term_arena = Arena::new();
6207    let np_arena = Arena::new();
6208    let sym_arena = Arena::new();
6209    let role_arena = Arena::new();
6210    let pp_arena = Arena::new();
6211    let stmt_arena: Arena<Stmt> = Arena::new();
6212    let _compile_facts = crate::optimize::facts::scope();
6213    let imperative_expr_arena: Arena<Expr> = Arena::new();
6214    let type_expr_arena: Arena<TypeExpr> = Arena::new();
6215    let ast_ctx = AstContext::with_types(
6216        &expr_arena,
6217        &term_arena,
6218        &np_arena,
6219        &sym_arena,
6220        &role_arena,
6221        &pp_arena,
6222        &stmt_arena,
6223        &imperative_expr_arena,
6224        &type_expr_arena,
6225    );
6226
6227    let mut parser = Parser::new(
6228        tokens,
6229        &mut world_state,
6230        &mut interner,
6231        ast_ctx,
6232        type_registry,
6233    );
6234    let stmts = parser.parse_program().map_err(ProjectScopeError::Parse)?;
6235
6236    check_scopes(&stmts, &assembled.scope, &interner).map_err(ProjectScopeError::Refused)
6237}
6238
6239/// Compile LOGOS source with a pre-populated type registry, returning full output.
6240/// Returns both generated Rust code and extracted dependencies. `scope`, when
6241/// present (multi-file `largo` builds), enforces per-file scoping over the
6242/// assembled program — a file may only reference what it defines or imports.
6243fn compile_to_rust_with_registry_full(
6244    source: &str,
6245    type_registry: crate::analysis::TypeRegistry,
6246    interner: &mut Interner,
6247    scope: Option<&crate::analysis::ScopeInfo>,
6248) -> Result<CompileOutput, ParseError> {
6249    let library = crate::loader::LibraryProvenance::of(source);
6250    let mut lexer = Lexer::new(source, interner);
6251    let mut tokens = lexer.tokenize();
6252
6253    // Resolve the qualified escape hatch for cross-module calls: an `Alias::fn`
6254    // token whose tail is a known function is rewritten to the bare `fn` symbol
6255    // (types stay namespaced). No-op for single-file programs.
6256    let functions = crate::analysis::assemble::defined_function_names(source);
6257    crate::analysis::assemble::resolve_qualified_names(&mut tokens, interner, &functions);
6258
6259    // Discovery pass for policies (types already discovered)
6260    let policy_registry = {
6261        let mut discovery = DiscoveryPass::new(&tokens, interner);
6262        discovery.run_full().policies
6263    };
6264
6265    let codegen_policies = policy_registry.clone();
6266
6267    let mut world_state = WorldState::new();
6268    let expr_arena = Arena::new();
6269    let term_arena = Arena::new();
6270    let np_arena = Arena::new();
6271    let sym_arena = Arena::new();
6272    let role_arena = Arena::new();
6273    let pp_arena = Arena::new();
6274    let stmt_arena: Arena<Stmt> = Arena::new();
6275    let _compile_facts = crate::optimize::facts::scope();
6276    let imperative_expr_arena: Arena<Expr> = Arena::new();
6277    let type_expr_arena: Arena<TypeExpr> = Arena::new();
6278
6279    let ast_ctx = AstContext::with_types(
6280        &expr_arena,
6281        &term_arena,
6282        &np_arena,
6283        &sym_arena,
6284        &role_arena,
6285        &pp_arena,
6286        &stmt_arena,
6287        &imperative_expr_arena,
6288        &type_expr_arena,
6289    );
6290
6291    let mut parser = Parser::new(tokens, &mut world_state, interner, ast_ctx, type_registry);
6292    let stmts = parser.parse_program()?;
6293    let (parsed, parsed_spans) = (stmts.clone(), parser.stmt_spans().to_vec());
6294
6295    // The ONE optimization config for this (largo/production) compile: env baseline
6296    // merged with the file-level `## No <X>` decorators, normalized — threaded to BOTH
6297    // the optimizer and codegen so `largo build` / `largo emit` honor them exactly like
6298    // the traced `compile_program_full` path does. This path previously dropped them
6299    // (bare `from_env()`), silently ignoring every `## No` / `## Require` decorator for
6300    // real users. Captured here (last use of `parser`) so its interner borrow ends.
6301    let (opt_config, gate) = crate::optimize::install_decorators(
6302        crate::optimization::OptimizationConfig::from_env(),
6303        &parser.program_opt_flags(),
6304        parser.required_optimizations(),
6305    );
6306    let codegen_registry = parser.into_type_registry();
6307    refuse_undeclared_types(&parsed, &parsed_spans, &codegen_registry, interner)?;
6308
6309    // Per-file scoping: forbid a file from referencing a name it neither defines
6310    // nor imports (no transitive leakage). Runs on the freshly-parsed program,
6311    // before optimization can inline calls away.
6312    if let Some(scope) = scope {
6313        crate::analysis::check_scopes(&stmts, scope, interner).map_err(|msg| ParseError {
6314            kind: crate::error::ParseErrorKind::Custom(msg),
6315            span: crate::token::Span::default(),
6316        })?;
6317    }
6318    check_as_written(&stmts, interner, AsWritten::Escapes)?;
6319
6320    let resolved = crate::resolve_program::resolve_program(
6321        &stmts,
6322        crate::ast_map::Arenas {
6323            exprs: &imperative_expr_arena,
6324            stmts: &stmt_arena,
6325            types: &type_expr_arena,
6326        },
6327        interner,
6328        opt_config.is_on(crate::optimization::Opt::Comptime),
6329        library.functions(),
6330    );
6331    let stmts: Vec<Stmt> = match resolved {
6332        Some(rw) => rw.to_vec(),
6333        None => stmts,
6334    };
6335
6336    // Run the AST optimizer in the production (largo) compile path so
6337    // compiled binaries get the same optimizations the test path
6338    // (compile_program_full) already validates: closed-form / modulus
6339    // deferral, partial evaluation, constant folding, GVN, LICM,
6340    // deforestation, CTFE, supercompilation. Previously skipped here, which
6341    // left the whole optimize layer off for compiled programs. Confirmed a
6342    // clean win (geomean 1.388x -> 1.735x C-speed, all benchmarks verify
6343    // correct, no regressions).
6344    let (stmts, codegen_registry) = lift_program_bindings(
6345        stmts,
6346        codegen_registry,
6347        interner,
6348        crate::ast_map::Arenas {
6349            exprs: &imperative_expr_arena,
6350            stmts: &stmt_arena,
6351            types: &type_expr_arena,
6352        },
6353    )?;
6354    let stmts = crate::optimize::optimize_program(
6355        stmts,
6356        &imperative_expr_arena,
6357        &stmt_arena,
6358        interner,
6359        &opt_config,
6360    );
6361
6362    // Extract dependencies
6363    let mut dependencies = extract_dependencies(&stmts, interner)?;
6364
6365    // FFI: Auto-inject wasm-bindgen dependency if any function is exported for WASM
6366    let needs_wasm_bindgen = stmts.iter().any(|stmt| {
6367        if let Stmt::FunctionDef {
6368            is_exported: true,
6369            export_target: Some(target),
6370            ..
6371        } = stmt
6372        {
6373            interner.resolve(*target).eq_ignore_ascii_case("wasm")
6374        } else {
6375            false
6376        }
6377    });
6378    if needs_wasm_bindgen && !dependencies.iter().any(|d| d.name == "wasm-bindgen") {
6379        dependencies.push(CrateDependency {
6380            name: "wasm-bindgen".to_string(),
6381            version: "0.2".to_string(),
6382            features: vec![],
6383        });
6384    }
6385
6386    // A call to a name that exists nowhere in the post-prelude program is a
6387    // check error here — not a rustc E0425 after codegen (`largo check` runs
6388    // exactly this path).
6389    crate::analysis::check_unknown_calls(&stmts, interner, &codegen_registry).map_err(|e| {
6390        ParseError {
6391            kind: e.to_parse_error_kind(interner),
6392            span: crate::token::Span::default(),
6393        }
6394    })?;
6395
6396    let type_env = crate::analysis::check_program_located(&stmts, interner, &codegen_registry)
6397        .map_err(|e| ParseError {
6398            kind: e.to_parse_error_kind(interner, &stmts),
6399            span: crate::token::Span::default(),
6400        })?;
6401    let rust_code = codegen_program(
6402        &stmts,
6403        &codegen_registry,
6404        &codegen_policies,
6405        interner,
6406        &type_env,
6407        &opt_config,
6408    );
6409
6410    // `## Require <opt>`: every demanded optimization must have fired, or the compile
6411    // fails loudly — the inverse of `## No`, now enforced on the real `largo` path too.
6412    gate.verify().map_err(|m| ParseError {
6413        kind: crate::error::ParseErrorKind::Custom(m),
6414        span: crate::token::Span::default(),
6415    })?;
6416
6417    // Universal ABI: Generate C header + bindings if any C exports exist
6418    let has_c = stmts.iter().any(|stmt| {
6419        if let Stmt::FunctionDef {
6420            is_exported: true,
6421            export_target,
6422            ..
6423        } = stmt
6424        {
6425            match export_target {
6426                None => true,
6427                Some(t) => interner.resolve(*t).eq_ignore_ascii_case("c"),
6428            }
6429        } else {
6430            false
6431        }
6432    });
6433
6434    let c_header = if has_c {
6435        Some(generate_c_header(
6436            &stmts,
6437            "module",
6438            interner,
6439            &codegen_registry,
6440        ))
6441    } else {
6442        None
6443    };
6444
6445    if has_c && !dependencies.iter().any(|d| d.name == "serde_json") {
6446        dependencies.push(CrateDependency {
6447            name: "serde_json".to_string(),
6448            version: "1".to_string(),
6449            features: vec![],
6450        });
6451    }
6452
6453    let python_bindings = if has_c {
6454        Some(generate_python_bindings(
6455            &stmts,
6456            "module",
6457            interner,
6458            &codegen_registry,
6459        ))
6460    } else {
6461        None
6462    };
6463
6464    let (typescript_bindings, typescript_types) = if has_c {
6465        let (js, dts) = generate_typescript_bindings(&stmts, "module", interner, &codegen_registry);
6466        (Some(js), Some(dts))
6467    } else {
6468        (None, None)
6469    };
6470
6471    Ok(CompileOutput {
6472        rust_code,
6473        dependencies,
6474        c_header,
6475        python_bindings,
6476        typescript_types,
6477        typescript_bindings,
6478    })
6479}
6480
6481/// Errors that can occur during the LOGOS compilation pipeline.
6482///
6483/// This enum represents the different stages where compilation can fail,
6484/// from parsing through to runtime execution.
6485///
6486/// # Error Hierarchy
6487///
6488/// ```text
6489/// CompileError
6490/// ├── Parse      ← Lexing, parsing, or static analysis
6491/// ├── Io         ← File system operations
6492/// ├── Build      ← Rust compilation (cargo build)
6493/// ├── Ownership  ← Translated borrow checker errors
6494/// └── Runtime    ← Program execution failure
6495/// ```
6496///
6497/// # Error Translation
6498///
6499/// The `Ownership` variant contains LOGOS-friendly error messages translated
6500/// from rustc's borrow checker errors (E0382, E0505, E0597) using the
6501/// [`diagnostic`](crate::diagnostic) module.
6502#[derive(Debug)]
6503pub enum CompileError {
6504    /// Parsing or static analysis failed.
6505    ///
6506    /// This includes lexer errors, syntax errors, escape analysis failures,
6507    /// ownership analysis failures, and Z3 verification failures.
6508    Parse(ParseError),
6509
6510    /// File system operation failed.
6511    ///
6512    /// Typically occurs when reading source files or writing output.
6513    Io(String),
6514
6515    /// Rust compilation failed (`cargo build`).
6516    ///
6517    /// Contains the raw stderr output from rustc when diagnostic translation
6518    /// was not possible.
6519    Build(String),
6520
6521    /// Runtime execution failed.
6522    ///
6523    /// Contains stderr output from the executed program.
6524    Runtime(String),
6525
6526    /// Translated ownership/borrow checker error with LOGOS-friendly message.
6527    ///
6528    /// This variant is used when rustc reports errors like E0382 (use after move)
6529    /// and we can translate them into natural language error messages that
6530    /// reference the original LOGOS source.
6531    Ownership(LogosError),
6532}
6533
6534impl std::fmt::Display for CompileError {
6535    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
6536        match self {
6537            CompileError::Parse(e) => write!(f, "Parse error: {}", describe_parse_error(e)),
6538            CompileError::Io(e) => write!(f, "IO error: {}", e),
6539            CompileError::Build(e) => write!(f, "Build error: {}", e),
6540            CompileError::Runtime(e) => write!(f, "Runtime error: {}", e),
6541            CompileError::Ownership(e) => write!(f, "{}", e),
6542        }
6543    }
6544}
6545
6546impl std::error::Error for CompileError {}
6547
6548// ============================================================
6549// Futamura Projection Support — encode_program + verify_no_overhead
6550// ============================================================
6551
6552/// Encode a LOGOS program (given as source) into CProgram construction source.
6553///
6554/// Takes LOGOS source code (with or without `## Main` header) and returns
6555/// LOGOS source code that constructs the equivalent CProgram data structure.
6556/// The result defines a variable `prog` of type CProgram.
6557pub fn encode_program_source(source: &str) -> Result<String, ParseError> {
6558    let full_source = if source.contains("## Main") || source.contains("## To ") {
6559        source.to_string()
6560    } else {
6561        format!("## Main\n{}", source)
6562    };
6563
6564    let mut interner = Interner::new();
6565    let mut lexer = Lexer::new(&full_source, &mut interner);
6566    let tokens = lexer.tokenize();
6567
6568    let type_registry = {
6569        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
6570        let result = discovery.run_full();
6571        result.types
6572    };
6573
6574    // Collect variant constructors before the parser takes ownership of type_registry
6575    let mut variant_constructors: HashMap<String, Vec<String>> = HashMap::new();
6576    for (_type_name, type_def) in type_registry.iter_types() {
6577        if let crate::analysis::TypeDef::Enum { variants, .. } = type_def {
6578            for variant in variants {
6579                let vname = interner.resolve(variant.name).to_string();
6580                let field_names: Vec<String> = variant
6581                    .fields
6582                    .iter()
6583                    .map(|f| interner.resolve(f.name).to_string())
6584                    .collect();
6585                variant_constructors.insert(vname, field_names);
6586            }
6587        }
6588    }
6589
6590    let mut world_state = WorldState::new();
6591    let expr_arena = Arena::new();
6592    let term_arena = Arena::new();
6593    let np_arena = Arena::new();
6594    let sym_arena = Arena::new();
6595    let role_arena = Arena::new();
6596    let pp_arena = Arena::new();
6597    let stmt_arena: Arena<Stmt> = Arena::new();
6598    let _compile_facts = crate::optimize::facts::scope();
6599    let imperative_expr_arena: Arena<Expr> = Arena::new();
6600    let type_expr_arena: Arena<TypeExpr> = Arena::new();
6601
6602    let ast_ctx = AstContext::with_types(
6603        &expr_arena,
6604        &term_arena,
6605        &np_arena,
6606        &sym_arena,
6607        &role_arena,
6608        &pp_arena,
6609        &stmt_arena,
6610        &imperative_expr_arena,
6611        &type_expr_arena,
6612    );
6613
6614    let mut parser = crate::parser::Parser::new(
6615        tokens,
6616        &mut world_state,
6617        &mut interner,
6618        ast_ctx,
6619        type_registry,
6620    );
6621    let stmts = parser.parse_program()?;
6622
6623    let mut functions: Vec<(String, Vec<String>, Vec<String>, String, Vec<&Stmt>)> = Vec::new();
6624    let mut main_stmts: Vec<&Stmt> = Vec::new();
6625
6626    for stmt in &stmts {
6627        if let Stmt::FunctionDef {
6628            name,
6629            params,
6630            body,
6631            return_type,
6632            is_native,
6633            ..
6634        } = stmt
6635        {
6636            if *is_native {
6637                continue; // Skip native function declarations — they have no encodable body
6638            }
6639            let fn_name = interner.resolve(*name).to_string();
6640            let param_names: Vec<String> = params
6641                .iter()
6642                .map(|(name, _)| interner.resolve(*name).to_string())
6643                .collect();
6644            let param_types: Vec<String> = params
6645                .iter()
6646                .map(|(_, ty)| decompile_type_expr(ty, &interner))
6647                .collect();
6648            let ret_type = return_type
6649                .map(|rt| decompile_type_expr(rt, &interner))
6650                .unwrap_or_else(|| "Nothing".to_string());
6651            let body_stmts: Vec<&Stmt> = body.iter().collect();
6652            functions.push((fn_name, param_names, param_types, ret_type, body_stmts));
6653        } else {
6654            main_stmts.push(stmt);
6655        }
6656    }
6657
6658    let mut counter = 0usize;
6659    let mut output = String::new();
6660    reset_inspect_otherwise_idx(); // deterministic `__inspectMatched_N` numbering, shared with the native builder
6661
6662    // Build the funcMap directly (Map of Text to CFunc) with fixed name, plus a parallel
6663    // `encodedFuncSeq` (Seq of CFunc, declaration order) — the map has no meaning-preserving
6664    // iteration order, so the wire serializer (which ships a `CProg with funcs …`) needs the seq.
6665    output.push_str("Let encodedFuncMap be a new Map of Text to CFunc.\n");
6666    output.push_str("Let encodedFuncSeq be a new Seq of CFunc.\n");
6667
6668    for (fn_name, params, param_types, ret_type, body) in &functions {
6669        let body_var = encode_stmt_list_src(
6670            body,
6671            &mut counter,
6672            &mut output,
6673            &interner,
6674            &variant_constructors,
6675        );
6676
6677        let params_var = format!("params_{}", counter);
6678        counter += 1;
6679        output.push_str(&format!("Let {} be a new Seq of Text.\n", params_var));
6680        for p in params {
6681            output.push_str(&format!("Push \"{}\" to {}.\n", p, params_var));
6682        }
6683
6684        let param_types_var = format!("paramTypes_{}", counter);
6685        counter += 1;
6686        output.push_str(&format!("Let {} be a new Seq of Text.\n", param_types_var));
6687        for pt in param_types {
6688            output.push_str(&format!("Push \"{}\" to {}.\n", pt, param_types_var));
6689        }
6690
6691        let func_var = format!("func_{}", counter);
6692        counter += 1;
6693        output.push_str(&format!(
6694            "Let {} be a new CFuncDef with name \"{}\" and params {} and paramTypes {} and returnType \"{}\" and body {}.\n",
6695            func_var, fn_name, params_var, param_types_var, ret_type, body_var
6696        ));
6697        // `copy of` + emitted BEFORE the map `Set` (which MOVES func_var in AOT codegen): the seq
6698        // gets an identical clone, the map keeps the original — no use-after-move (E0382) when the
6699        // encoded program is compiled to Rust. The interpreter clones anyway, so this is a pure
6700        // codegen-soundness fix, behaviourally identical on every tier.
6701        output.push_str(&format!("Push copy of {} to encodedFuncSeq.\n", func_var));
6702        output.push_str(&format!(
6703            "Set item \"{}\" of encodedFuncMap to {}.\n",
6704            fn_name, func_var
6705        ));
6706    }
6707
6708    // Build main statement list with fixed name
6709    let main_var = encode_stmt_list_src(
6710        &main_stmts,
6711        &mut counter,
6712        &mut output,
6713        &interner,
6714        &variant_constructors,
6715    );
6716    output.push_str(&format!("Let encodedMain be {}.\n", main_var));
6717
6718    Ok(output)
6719}
6720
6721/// Compact encoding: inlines simple expressions (literals, variables) to reduce
6722/// encoding size by ~3x. Same semantics as encode_program_source but produces
6723/// fewer Let statements.
6724pub fn encode_program_source_compact(source: &str) -> Result<String, ParseError> {
6725    let full_source = if source.contains("## Main") || source.contains("## To ") {
6726        source.to_string()
6727    } else {
6728        format!("## Main\n{}", source)
6729    };
6730
6731    let mut interner = Interner::new();
6732    let mut lexer = Lexer::new(&full_source, &mut interner);
6733    let tokens = lexer.tokenize();
6734
6735    let type_registry = {
6736        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
6737        let result = discovery.run_full();
6738        result.types
6739    };
6740
6741    let mut variant_constructors: HashMap<String, Vec<String>> = HashMap::new();
6742    for (_type_name, type_def) in type_registry.iter_types() {
6743        if let crate::analysis::TypeDef::Enum { variants, .. } = type_def {
6744            for variant in variants {
6745                let vname = interner.resolve(variant.name).to_string();
6746                let field_names: Vec<String> = variant
6747                    .fields
6748                    .iter()
6749                    .map(|f| interner.resolve(f.name).to_string())
6750                    .collect();
6751                variant_constructors.insert(vname, field_names);
6752            }
6753        }
6754    }
6755
6756    let mut world_state = WorldState::new();
6757    let expr_arena = Arena::new();
6758    let term_arena = Arena::new();
6759    let np_arena = Arena::new();
6760    let sym_arena = Arena::new();
6761    let role_arena = Arena::new();
6762    let pp_arena = Arena::new();
6763    let stmt_arena: Arena<Stmt> = Arena::new();
6764    let _compile_facts = crate::optimize::facts::scope();
6765    let imperative_expr_arena: Arena<Expr> = Arena::new();
6766    let type_expr_arena: Arena<TypeExpr> = Arena::new();
6767
6768    let ast_ctx = AstContext::with_types(
6769        &expr_arena,
6770        &term_arena,
6771        &np_arena,
6772        &sym_arena,
6773        &role_arena,
6774        &pp_arena,
6775        &stmt_arena,
6776        &imperative_expr_arena,
6777        &type_expr_arena,
6778    );
6779
6780    let mut parser = crate::parser::Parser::new(
6781        tokens,
6782        &mut world_state,
6783        &mut interner,
6784        ast_ctx,
6785        type_registry,
6786    );
6787    let stmts = parser.parse_program()?;
6788
6789    let mut functions: Vec<(String, Vec<String>, Vec<String>, String, Vec<&Stmt>)> = Vec::new();
6790    let mut main_stmts: Vec<&Stmt> = Vec::new();
6791
6792    for stmt in &stmts {
6793        if let Stmt::FunctionDef {
6794            name,
6795            params,
6796            body,
6797            return_type,
6798            is_native,
6799            ..
6800        } = stmt
6801        {
6802            if *is_native {
6803                continue;
6804            }
6805            let fn_name = interner.resolve(*name).to_string();
6806            let param_names: Vec<String> = params
6807                .iter()
6808                .map(|(name, _)| interner.resolve(*name).to_string())
6809                .collect();
6810            let param_types: Vec<String> = params
6811                .iter()
6812                .map(|(_, ty)| decompile_type_expr(ty, &interner))
6813                .collect();
6814            let ret_type = return_type
6815                .map(|rt| decompile_type_expr(rt, &interner))
6816                .unwrap_or_else(|| "Nothing".to_string());
6817            let body_stmts: Vec<&Stmt> = body.iter().collect();
6818            functions.push((fn_name, param_names, param_types, ret_type, body_stmts));
6819        } else {
6820            main_stmts.push(stmt);
6821        }
6822    }
6823
6824    let mut counter = 0usize;
6825    let mut output = String::new();
6826
6827    output.push_str("Let encodedFuncMap be a new Map of Text to CFunc.\n");
6828
6829    for (fn_name, params, param_types, ret_type, body) in &functions {
6830        let body_var = encode_stmt_list_compact(
6831            body,
6832            &mut counter,
6833            &mut output,
6834            &interner,
6835            &variant_constructors,
6836        );
6837
6838        let params_var = format!("params_{}", counter);
6839        counter += 1;
6840        output.push_str(&format!("Let {} be a new Seq of Text.\n", params_var));
6841        for p in params {
6842            output.push_str(&format!("Push \"{}\" to {}.\n", p, params_var));
6843        }
6844
6845        let param_types_var = format!("paramTypes_{}", counter);
6846        counter += 1;
6847        output.push_str(&format!("Let {} be a new Seq of Text.\n", param_types_var));
6848        for pt in param_types {
6849            output.push_str(&format!("Push \"{}\" to {}.\n", pt, param_types_var));
6850        }
6851
6852        let func_var = format!("func_{}", counter);
6853        counter += 1;
6854        output.push_str(&format!(
6855            "Let {} be a new CFuncDef with name \"{}\" and params {} and paramTypes {} and returnType \"{}\" and body {}.\n",
6856            func_var, fn_name, params_var, param_types_var, ret_type, body_var
6857        ));
6858        output.push_str(&format!(
6859            "Set item \"{}\" of encodedFuncMap to {}.\n",
6860            fn_name, func_var
6861        ));
6862    }
6863
6864    let main_var = encode_stmt_list_compact(
6865        &main_stmts,
6866        &mut counter,
6867        &mut output,
6868        &interner,
6869        &variant_constructors,
6870    );
6871    output.push_str(&format!("Let encodedMain be {}.\n", main_var));
6872
6873    Ok(output)
6874}
6875
6876/// Returns an inline expression string for simple expressions (no Let variable needed).
6877/// Returns None for complex expressions that require a Let variable.
6878fn try_inline_expr(expr: &Expr, interner: &Interner) -> Option<String> {
6879    match expr {
6880        Expr::Literal(lit) => match lit {
6881            Literal::Number(n) => Some(format!("(a new CInt with value {})", n)),
6882            Literal::Boolean(b) => Some(format!("(a new CBool with value {})", b)),
6883            Literal::Text(s) => {
6884                let text = interner.resolve(*s);
6885                Some(format!("(a new CText with value \"{}\")", text))
6886            }
6887            Literal::Float(f) => {
6888                let fs = format!("{}", f);
6889                let fs = if fs.contains('.') {
6890                    fs
6891                } else {
6892                    format!("{}.0", fs)
6893                };
6894                Some(format!("(a new CFloat with value {})", fs))
6895            }
6896            Literal::Nothing => Some("(a new CText with value \"nothing\")".to_string()),
6897            _ => None,
6898        },
6899        Expr::Identifier(sym) => {
6900            let name = interner.resolve(*sym);
6901            Some(format!("(a new CVar with name \"{}\")", name))
6902        }
6903        Expr::Not { operand } => {
6904            if let Some(inner) = try_inline_expr(operand, interner) {
6905                Some(format!("(a new CNot with inner {})", inner))
6906            } else {
6907                None
6908            }
6909        }
6910        Expr::OptionNone => Some("(a new COptionNone)".to_string()),
6911        _ => None,
6912    }
6913}
6914
6915fn encode_expr_compact(
6916    expr: &Expr,
6917    counter: &mut usize,
6918    output: &mut String,
6919    interner: &Interner,
6920    variants: &HashMap<String, Vec<String>>,
6921) -> String {
6922    // Try inline first
6923    if let Some(inline) = try_inline_expr(expr, interner) {
6924        return inline;
6925    }
6926
6927    // Fall back to Let variable (reuse encode_expr_src logic but with compact children)
6928    let var = format!("e_{}", *counter);
6929    *counter += 1;
6930
6931    match expr {
6932        Expr::BinaryOp { op, left, right } => {
6933            let left_var = encode_expr_compact(left, counter, output, interner, variants);
6934            let right_var = encode_expr_compact(right, counter, output, interner, variants);
6935            let op_str = match op {
6936                BinaryOpKind::Add => "+",
6937                BinaryOpKind::Subtract => "-",
6938                BinaryOpKind::Multiply => "*",
6939                BinaryOpKind::Divide | BinaryOpKind::ExactDivide => "/",
6940                BinaryOpKind::FloorDivide => "//",
6941                BinaryOpKind::Modulo => "%",
6942                BinaryOpKind::Eq => "==",
6943                BinaryOpKind::NotEq => "!=",
6944                BinaryOpKind::Lt => "<",
6945                BinaryOpKind::Gt => ">",
6946                BinaryOpKind::LtEq => "<=",
6947                BinaryOpKind::GtEq => ">=",
6948                BinaryOpKind::And => "&&",
6949                BinaryOpKind::Or => "||",
6950                BinaryOpKind::Concat => "+",
6951                BinaryOpKind::SeqConcat => "followed by",
6952                BinaryOpKind::ApproxEq => "is approximately",
6953                BinaryOpKind::Pow => "**",
6954                BinaryOpKind::BitXor => "^",
6955                BinaryOpKind::BitAnd => "&",
6956                BinaryOpKind::BitOr => "|",
6957                BinaryOpKind::Shl => "<<",
6958                BinaryOpKind::Shr => ">>",
6959            };
6960            output.push_str(&format!(
6961                "Let {} be a new CBinOp with op \"{}\" and left {} and right {}.\n",
6962                var, op_str, left_var, right_var
6963            ));
6964        }
6965        Expr::Call { function, args } => {
6966            let fn_name = interner.resolve(*function);
6967            if let Some(field_names) = variants.get(fn_name) {
6968                let names_var = format!("nvNames_{}", *counter);
6969                *counter += 1;
6970                output.push_str(&format!("Let {} be a new Seq of Text.\n", names_var));
6971                let vals_var = format!("nvVals_{}", *counter);
6972                *counter += 1;
6973                output.push_str(&format!("Let {} be a new Seq of CExpr.\n", vals_var));
6974                for (i, arg) in args.iter().enumerate() {
6975                    let fname = field_names.get(i).map(|s| s.as_str()).unwrap_or("value");
6976                    output.push_str(&format!("Push \"{}\" to {}.\n", fname, names_var));
6977                    let arg_var = encode_expr_compact(arg, counter, output, interner, variants);
6978                    output.push_str(&format!("Push {} to {}.\n", arg_var, vals_var));
6979                }
6980                output.push_str(&format!(
6981                    "Let {} be a new CNewVariant with tag \"{}\" and fnames {} and fvals {}.\n",
6982                    var, fn_name, names_var, vals_var
6983                ));
6984            } else {
6985                let args_var = format!("callArgs_{}", *counter);
6986                *counter += 1;
6987                output.push_str(&format!("Let {} be a new Seq of CExpr.\n", args_var));
6988                for arg in args {
6989                    let arg_var = encode_expr_compact(arg, counter, output, interner, variants);
6990                    output.push_str(&format!("Push {} to {}.\n", arg_var, args_var));
6991                }
6992                output.push_str(&format!(
6993                    "Let {} be a new CCall with name \"{}\" and args {}.\n",
6994                    var, fn_name, args_var
6995                ));
6996            }
6997        }
6998        Expr::Index { collection, index } => {
6999            let coll_var = encode_expr_compact(collection, counter, output, interner, variants);
7000            let idx_var = encode_expr_compact(index, counter, output, interner, variants);
7001            output.push_str(&format!(
7002                "Let {} be a new CIndex with coll {} and idx {}.\n",
7003                var, coll_var, idx_var
7004            ));
7005        }
7006        Expr::Length { collection } => {
7007            let coll_var = encode_expr_compact(collection, counter, output, interner, variants);
7008            output.push_str(&format!(
7009                "Let {} be a new CLen with target {}.\n",
7010                var, coll_var
7011            ));
7012        }
7013        Expr::FieldAccess { object, field } => {
7014            let obj_var = encode_expr_compact(object, counter, output, interner, variants);
7015            let field_name = interner.resolve(*field);
7016            output.push_str(&format!(
7017                "Let {} be a new CMapGet with target {} and key (a new CText with value \"{}\").\n",
7018                var, obj_var, field_name
7019            ));
7020        }
7021        Expr::NewVariant {
7022            variant, fields, ..
7023        } => {
7024            let variant_name = interner.resolve(*variant);
7025            let names_var = format!("nvNames_{}", *counter);
7026            *counter += 1;
7027            output.push_str(&format!("Let {} be a new Seq of Text.\n", names_var));
7028            let vals_var = format!("nvVals_{}", *counter);
7029            *counter += 1;
7030            output.push_str(&format!("Let {} be a new Seq of CExpr.\n", vals_var));
7031            for (field_name, field_expr) in fields {
7032                let fname = interner.resolve(*field_name);
7033                output.push_str(&format!("Push \"{}\" to {}.\n", fname, names_var));
7034                let field_var =
7035                    encode_expr_compact(field_expr, counter, output, interner, variants);
7036                output.push_str(&format!("Push {} to {}.\n", field_var, vals_var));
7037            }
7038            output.push_str(&format!(
7039                "Let {} be a new CNewVariant with tag \"{}\" and fnames {} and fvals {}.\n",
7040                var, variant_name, names_var, vals_var
7041            ));
7042        }
7043        Expr::New {
7044            type_name,
7045            init_fields,
7046            ..
7047        } => {
7048            let tn = interner.resolve(*type_name);
7049            if tn == "Seq" || tn == "List" {
7050                output.push_str(&format!("Let {} be a new CNewSeq.\n", var));
7051            } else if tn == "Set" {
7052                output.push_str(&format!("Let {} be a new CNewSet.\n", var));
7053            } else {
7054                let names_var = format!("nvNames_{}", *counter);
7055                *counter += 1;
7056                output.push_str(&format!("Let {} be a new Seq of Text.\n", names_var));
7057                let vals_var = format!("nvVals_{}", *counter);
7058                *counter += 1;
7059                output.push_str(&format!("Let {} be a new Seq of CExpr.\n", vals_var));
7060                for (field_name, field_expr) in init_fields {
7061                    let fname = interner.resolve(*field_name);
7062                    output.push_str(&format!("Push \"{}\" to {}.\n", fname, names_var));
7063                    let field_var =
7064                        encode_expr_compact(field_expr, counter, output, interner, variants);
7065                    output.push_str(&format!("Push {} to {}.\n", field_var, vals_var));
7066                }
7067                output.push_str(&format!(
7068                    "Let {} be a new CNewVariant with tag \"{}\" and fnames {} and fvals {}.\n",
7069                    var, tn, names_var, vals_var
7070                ));
7071            }
7072        }
7073        Expr::InterpolatedString(parts) => {
7074            if parts.is_empty() {
7075                output.push_str(&format!("Let {} be (a new CText with value \"\").\n", var));
7076            } else {
7077                // Preserve as a first-class CInterpolatedString rather than desugaring to a
7078                // lossy `+` chain (see encode_expr_src for the rationale).
7079                let parts_var = format!("isparts_{}", *counter);
7080                *counter += 1;
7081                output.push_str(&format!("Let {} be a new Seq of CStringPart.\n", parts_var));
7082                for part in parts {
7083                    match part {
7084                        StringPart::Literal(sym) => {
7085                            let text = interner.resolve(*sym);
7086                            output.push_str(&format!(
7087                                "Push a new CLiteralPart with value \"{}\" to {}.\n",
7088                                text, parts_var
7089                            ));
7090                        }
7091                        StringPart::Expr { value, .. } => {
7092                            let pv =
7093                                encode_expr_compact(value, counter, output, interner, variants);
7094                            output.push_str(&format!(
7095                                "Push a new CExprPart with expr {} to {}.\n",
7096                                pv, parts_var
7097                            ));
7098                        }
7099                    }
7100                }
7101                output.push_str(&format!(
7102                    "Let {} be a new CInterpolatedString with parts {}.\n",
7103                    var, parts_var
7104                ));
7105            }
7106        }
7107        Expr::Range { start, end } => {
7108            let start_var = encode_expr_compact(start, counter, output, interner, variants);
7109            let end_var = encode_expr_compact(end, counter, output, interner, variants);
7110            output.push_str(&format!(
7111                "Let {} be a new CRange with start {} and end {}.\n",
7112                var, start_var, end_var
7113            ));
7114        }
7115        Expr::Copy { expr } => {
7116            let inner_var = encode_expr_compact(expr, counter, output, interner, variants);
7117            output.push_str(&format!(
7118                "Let {} be a new CCopy with target {}.\n",
7119                var, inner_var
7120            ));
7121        }
7122        Expr::Contains { collection, value } => {
7123            let coll_var = encode_expr_compact(collection, counter, output, interner, variants);
7124            let val_var = encode_expr_compact(value, counter, output, interner, variants);
7125            output.push_str(&format!(
7126                "Let {} be a new CContains with coll {} and elem {}.\n",
7127                var, coll_var, val_var
7128            ));
7129        }
7130        Expr::OptionSome { value } => {
7131            let inner_var = encode_expr_compact(value, counter, output, interner, variants);
7132            output.push_str(&format!(
7133                "Let {} be a new COptionSome with inner {}.\n",
7134                var, inner_var
7135            ));
7136        }
7137        Expr::Tuple(elems) => {
7138            let items_var = format!("tupItems_{}", *counter);
7139            *counter += 1;
7140            output.push_str(&format!("Let {} be a new Seq of CExpr.\n", items_var));
7141            for elem in elems {
7142                let elem_var = encode_expr_compact(elem, counter, output, interner, variants);
7143                output.push_str(&format!("Push {} to {}.\n", elem_var, items_var));
7144            }
7145            output.push_str(&format!(
7146                "Let {} be a new CTuple with items {}.\n",
7147                var, items_var
7148            ));
7149        }
7150        Expr::Closure { params, body, .. } => {
7151            let params_var = format!("clp_{}", *counter);
7152            *counter += 1;
7153            output.push_str(&format!("Let {} be a new Seq of Text.\n", params_var));
7154            let mut param_names = HashSet::new();
7155            for (sym, _) in params {
7156                let name = interner.resolve(*sym);
7157                param_names.insert(name.to_string());
7158                output.push_str(&format!("Push \"{}\" to {}.\n", name, params_var));
7159            }
7160            let body_var = format!("clb_{}", *counter);
7161            *counter += 1;
7162            output.push_str(&format!("Let {} be a new Seq of CStmt.\n", body_var));
7163            match body {
7164                ClosureBody::Expression(e) => {
7165                    let ret_expr = encode_expr_compact(e, counter, output, interner, variants);
7166                    let ret_var = format!("s_{}", *counter);
7167                    *counter += 1;
7168                    output.push_str(&format!(
7169                        "Let {} be a new CReturn with expr {}.\n",
7170                        ret_var, ret_expr
7171                    ));
7172                    output.push_str(&format!("Push {} to {}.\n", ret_var, body_var));
7173                }
7174                ClosureBody::Block(stmts) => {
7175                    for s in stmts.iter() {
7176                        let sv = encode_stmt_compact(s, counter, output, interner, variants);
7177                        output.push_str(&format!("Push {} to {}.\n", sv, body_var));
7178                    }
7179                }
7180            }
7181            let bound: HashSet<String> = param_names;
7182            // Sort the captured free variables for a DETERMINISTIC encoding — a `HashSet`'s random
7183            // iteration order would make the wire bytes vary run-to-run (breaking content-addressing
7184            // AND the fast native-builder byte-identity). The capture set is order-independent
7185            // semantically, so sorting is a pure improvement.
7186            let mut free: Vec<String> = collect_free_vars_expr(expr, interner, &bound)
7187                .into_iter()
7188                .collect();
7189            free.sort();
7190            let cap_var = format!("clc_{}", *counter);
7191            *counter += 1;
7192            output.push_str(&format!("Let {} be a new Seq of Text.\n", cap_var));
7193            for fv in &free {
7194                output.push_str(&format!("Push \"{}\" to {}.\n", fv, cap_var));
7195            }
7196            output.push_str(&format!(
7197                "Let {} be a new CClosure with params {} and body {} and captured {}.\n",
7198                var, params_var, body_var, cap_var
7199            ));
7200        }
7201        Expr::CallExpr { callee, args } => {
7202            let callee_var = encode_expr_compact(callee, counter, output, interner, variants);
7203            let args_var = format!("cea_{}", *counter);
7204            *counter += 1;
7205            output.push_str(&format!("Let {} be a new Seq of CExpr.\n", args_var));
7206            for a in args {
7207                let av = encode_expr_compact(a, counter, output, interner, variants);
7208                output.push_str(&format!("Push {} to {}.\n", av, args_var));
7209            }
7210            output.push_str(&format!(
7211                "Let {} be a new CCallExpr with target {} and args {}.\n",
7212                var, callee_var, args_var
7213            ));
7214        }
7215        Expr::Slice {
7216            collection,
7217            start,
7218            end,
7219        } => {
7220            let coll_var = encode_expr_compact(collection, counter, output, interner, variants);
7221            let start_var = encode_expr_compact(start, counter, output, interner, variants);
7222            let end_var = encode_expr_compact(end, counter, output, interner, variants);
7223            output.push_str(&format!(
7224                "Let {} be a new CSlice with coll {} and startIdx {} and endIdx {}.\n",
7225                var, coll_var, start_var, end_var
7226            ));
7227        }
7228        Expr::Union { left, right } => {
7229            let left_var = encode_expr_compact(left, counter, output, interner, variants);
7230            let right_var = encode_expr_compact(right, counter, output, interner, variants);
7231            output.push_str(&format!(
7232                "Let {} be a new CUnion with left {} and right {}.\n",
7233                var, left_var, right_var
7234            ));
7235        }
7236        Expr::Intersection { left, right } => {
7237            let left_var = encode_expr_compact(left, counter, output, interner, variants);
7238            let right_var = encode_expr_compact(right, counter, output, interner, variants);
7239            output.push_str(&format!(
7240                "Let {} be a new CIntersection with left {} and right {}.\n",
7241                var, left_var, right_var
7242            ));
7243        }
7244        Expr::Give { value } => {
7245            let inner_var = encode_expr_compact(value, counter, output, interner, variants);
7246            output.push_str(&format!("Let {} be {}.\n", var, inner_var));
7247        }
7248        Expr::Escape { code, .. } => {
7249            let code_str = interner.resolve(*code);
7250            output.push_str(&format!(
7251                "Let {} be a new CEscExpr with code \"{}\".\n",
7252                var,
7253                code_str.replace('\"', "\\\"")
7254            ));
7255        }
7256        _ => {
7257            // For unsupported expressions, use the non-compact version
7258            output.push_str(&format!(
7259                "Let {} be (a new CText with value \"unsupported\").\n",
7260                var
7261            ));
7262        }
7263    }
7264
7265    var
7266}
7267
7268fn encode_stmt_compact(
7269    stmt: &Stmt,
7270    counter: &mut usize,
7271    output: &mut String,
7272    interner: &Interner,
7273    variants: &HashMap<String, Vec<String>>,
7274) -> String {
7275    let var = format!("s_{}", *counter);
7276    *counter += 1;
7277
7278    match stmt {
7279        Stmt::Let {
7280            var: name, value, ..
7281        } => {
7282            let name_str = interner.resolve(*name);
7283            let expr_var = encode_expr_compact(value, counter, output, interner, variants);
7284            output.push_str(&format!(
7285                "Let {} be a new CLet with name \"{}\" and expr {}.\n",
7286                var, name_str, expr_var
7287            ));
7288        }
7289        Stmt::Set { target, value } => {
7290            let name_str = interner.resolve(*target);
7291            let expr_var = encode_expr_compact(value, counter, output, interner, variants);
7292            output.push_str(&format!(
7293                "Let {} be a new CSet with name \"{}\" and expr {}.\n",
7294                var, name_str, expr_var
7295            ));
7296        }
7297        Stmt::If {
7298            cond,
7299            then_block,
7300            else_block,
7301        } => {
7302            let cond_var = encode_expr_compact(cond, counter, output, interner, variants);
7303            let then_stmts: Vec<&Stmt> = then_block.iter().collect();
7304            let then_var =
7305                encode_stmt_list_compact(&then_stmts, counter, output, interner, variants);
7306            let else_var = if let Some(els) = else_block {
7307                let else_stmts: Vec<&Stmt> = els.iter().collect();
7308                encode_stmt_list_compact(&else_stmts, counter, output, interner, variants)
7309            } else {
7310                let empty_var = format!("emptyBlock_{}", *counter);
7311                *counter += 1;
7312                output.push_str(&format!("Let {} be a new Seq of CStmt.\n", empty_var));
7313                empty_var
7314            };
7315            output.push_str(&format!(
7316                "Let {} be a new CIf with cond {} and thenBlock {} and elseBlock {}.\n",
7317                var, cond_var, then_var, else_var
7318            ));
7319        }
7320        Stmt::While { cond, body, .. } => {
7321            let cond_var = encode_expr_compact(cond, counter, output, interner, variants);
7322            let body_stmts: Vec<&Stmt> = body.iter().collect();
7323            let body_var =
7324                encode_stmt_list_compact(&body_stmts, counter, output, interner, variants);
7325            output.push_str(&format!(
7326                "Let {} be a new CWhile with cond {} and body {}.\n",
7327                var, cond_var, body_var
7328            ));
7329        }
7330        Stmt::Return { value } => {
7331            if let Some(val) = value {
7332                let expr_var = encode_expr_compact(val, counter, output, interner, variants);
7333                output.push_str(&format!(
7334                    "Let {} be a new CReturn with expr {}.\n",
7335                    var, expr_var
7336                ));
7337            } else {
7338                output.push_str(&format!(
7339                    "Let {} be a new CReturn with expr (a new CText with value \"nothing\").\n",
7340                    var
7341                ));
7342            }
7343        }
7344        Stmt::Show { object, .. } => {
7345            let expr_var = encode_expr_compact(object, counter, output, interner, variants);
7346            output.push_str(&format!(
7347                "Let {} be a new CShow with expr {}.\n",
7348                var, expr_var
7349            ));
7350        }
7351        Stmt::Repeat {
7352            pattern,
7353            iterable,
7354            body,
7355        } => {
7356            let var_str = match pattern {
7357                Pattern::Identifier(sym) => interner.resolve(*sym).to_string(),
7358                Pattern::Tuple(syms) => {
7359                    if let Some(s) = syms.first() {
7360                        interner.resolve(*s).to_string()
7361                    } else {
7362                        "item".to_string()
7363                    }
7364                }
7365            };
7366            let coll_var = encode_expr_compact(iterable, counter, output, interner, variants);
7367            let body_stmts: Vec<&Stmt> = body.iter().collect();
7368            let body_var =
7369                encode_stmt_list_compact(&body_stmts, counter, output, interner, variants);
7370            output.push_str(&format!(
7371                "Let {} be a new CRepeat with var \"{}\" and coll {} and body {}.\n",
7372                var, var_str, coll_var, body_var
7373            ));
7374        }
7375        Stmt::Push { value, collection } => {
7376            let coll_name = extract_ident_name(collection, interner);
7377            let expr_var = encode_expr_compact(value, counter, output, interner, variants);
7378            output.push_str(&format!(
7379                "Let {} be a new CPush with expr {} and target \"{}\".\n",
7380                var, expr_var, coll_name
7381            ));
7382        }
7383        Stmt::SetIndex {
7384            collection,
7385            index,
7386            value,
7387        } => {
7388            let target_str = extract_ident_name(collection, interner);
7389            let idx_var = encode_expr_compact(index, counter, output, interner, variants);
7390            let val_var = encode_expr_compact(value, counter, output, interner, variants);
7391            output.push_str(&format!(
7392                "Let {} be a new CSetIdx with target \"{}\" and idx {} and val {}.\n",
7393                var, target_str, idx_var, val_var
7394            ));
7395        }
7396        Stmt::SetField {
7397            object,
7398            field,
7399            value,
7400        } => {
7401            let target_str = extract_ident_name(object, interner);
7402            let field_str = interner.resolve(*field);
7403            let val_var = encode_expr_compact(value, counter, output, interner, variants);
7404            output.push_str(&format!(
7405                "Let {} be a new CSetField with target \"{}\" and field \"{}\" and val {}.\n",
7406                var, target_str, field_str, val_var
7407            ));
7408        }
7409        Stmt::Break => {
7410            output.push_str(&format!("Let {} be a new CBreak.\n", var));
7411        }
7412        Stmt::Inspect { target, arms, .. } => {
7413            let target_var = encode_expr_compact(target, counter, output, interner, variants);
7414            let arms_var = format!("arms_{}", *counter);
7415            *counter += 1;
7416            output.push_str(&format!("Let {} be a new Seq of CMatchArm.\n", arms_var));
7417            for arm in arms {
7418                if let Some(variant_sym) = arm.variant {
7419                    let vname = interner.resolve(variant_sym);
7420                    let bindings_var = format!("bindings_{}", *counter);
7421                    *counter += 1;
7422                    output.push_str(&format!("Let {} be a new Seq of Text.\n", bindings_var));
7423                    for (_, binding_name) in &arm.bindings {
7424                        let bn = interner.resolve(*binding_name);
7425                        output.push_str(&format!("Push \"{}\" to {}.\n", bn, bindings_var));
7426                    }
7427                    let body_stmts: Vec<&Stmt> = arm.body.iter().collect();
7428                    let body_var =
7429                        encode_stmt_list_compact(&body_stmts, counter, output, interner, variants);
7430                    let arm_var = format!("arm_{}", *counter);
7431                    *counter += 1;
7432                    output.push_str(&format!(
7433                        "Let {} be a new CWhen with variantName \"{}\" and bindings {} and body {}.\n",
7434                        arm_var, vname, bindings_var, body_var
7435                    ));
7436                    output.push_str(&format!("Push {} to {}.\n", arm_var, arms_var));
7437                } else {
7438                    let body_stmts: Vec<&Stmt> = arm.body.iter().collect();
7439                    let body_var =
7440                        encode_stmt_list_compact(&body_stmts, counter, output, interner, variants);
7441                    let arm_var = format!("arm_{}", *counter);
7442                    *counter += 1;
7443                    output.push_str(&format!(
7444                        "Let {} be a new COtherwise with body {}.\n",
7445                        arm_var, body_var
7446                    ));
7447                    output.push_str(&format!("Push {} to {}.\n", arm_var, arms_var));
7448                }
7449            }
7450            output.push_str(&format!(
7451                "Let {} be a new CInspect with target {} and arms {}.\n",
7452                var, target_var, arms_var
7453            ));
7454        }
7455        _ => {
7456            // Delegate to non-compact encoder for unsupported statements
7457            return encode_stmt_src(stmt, counter, output, interner, variants);
7458        }
7459    }
7460
7461    var
7462}
7463
7464fn encode_stmt_list_compact(
7465    stmts: &[&Stmt],
7466    counter: &mut usize,
7467    output: &mut String,
7468    interner: &Interner,
7469    variants: &HashMap<String, Vec<String>>,
7470) -> String {
7471    let list_var = format!("stmts_{}", *counter);
7472    *counter += 1;
7473    output.push_str(&format!("Let {} be a new Seq of CStmt.\n", list_var));
7474    for s in stmts {
7475        let sv = encode_stmt_compact(s, counter, output, interner, variants);
7476        output.push_str(&format!("Push {} to {}.\n", sv, list_var));
7477    }
7478    list_var
7479}
7480
7481fn collect_free_vars_expr<'a>(
7482    expr: &'a Expr,
7483    interner: &Interner,
7484    bound: &HashSet<String>,
7485) -> HashSet<String> {
7486    let mut free = HashSet::new();
7487    match expr {
7488        Expr::Identifier(sym) => {
7489            let name = interner.resolve(*sym).to_string();
7490            if !bound.contains(&name) {
7491                free.insert(name);
7492            }
7493        }
7494        Expr::BinaryOp { left, right, .. } => {
7495            free.extend(collect_free_vars_expr(left, interner, bound));
7496            free.extend(collect_free_vars_expr(right, interner, bound));
7497        }
7498        Expr::Not { operand } => {
7499            free.extend(collect_free_vars_expr(operand, interner, bound));
7500        }
7501        Expr::Copy { expr: inner } => {
7502            free.extend(collect_free_vars_expr(inner, interner, bound));
7503        }
7504        Expr::CallExpr { callee, args } => {
7505            free.extend(collect_free_vars_expr(callee, interner, bound));
7506            for a in args {
7507                free.extend(collect_free_vars_expr(a, interner, bound));
7508            }
7509        }
7510        Expr::Index { collection, index } => {
7511            free.extend(collect_free_vars_expr(collection, interner, bound));
7512            free.extend(collect_free_vars_expr(index, interner, bound));
7513        }
7514        Expr::InterpolatedString(parts) => {
7515            for part in parts {
7516                if let StringPart::Expr { value, .. } = part {
7517                    free.extend(collect_free_vars_expr(value, interner, bound));
7518                }
7519            }
7520        }
7521        Expr::Closure { params, body, .. } => {
7522            let mut inner_bound = bound.clone();
7523            for (sym, _) in params {
7524                inner_bound.insert(interner.resolve(*sym).to_string());
7525            }
7526            match body {
7527                ClosureBody::Expression(e) => {
7528                    free.extend(collect_free_vars_expr(e, interner, &inner_bound));
7529                }
7530                ClosureBody::Block(stmts) => {
7531                    for s in stmts.iter() {
7532                        free.extend(collect_free_vars_stmt(s, interner, &inner_bound));
7533                    }
7534                }
7535            }
7536        }
7537        _ => {}
7538    }
7539    free
7540}
7541
7542fn collect_free_vars_stmt<'a>(
7543    stmt: &'a Stmt,
7544    interner: &Interner,
7545    bound: &HashSet<String>,
7546) -> HashSet<String> {
7547    let mut free = HashSet::new();
7548    match stmt {
7549        Stmt::Let { var, value, .. } => {
7550            free.extend(collect_free_vars_expr(value, interner, bound));
7551        }
7552        Stmt::Set { target, value, .. } => {
7553            let n = interner.resolve(*target).to_string();
7554            if !bound.contains(&n) {
7555                free.insert(n);
7556            }
7557            free.extend(collect_free_vars_expr(value, interner, bound));
7558        }
7559        Stmt::Show { object, .. } => {
7560            free.extend(collect_free_vars_expr(object, interner, bound));
7561        }
7562        Stmt::Return { value } => {
7563            if let Some(v) = value {
7564                free.extend(collect_free_vars_expr(v, interner, bound));
7565            }
7566        }
7567        _ => {}
7568    }
7569    free
7570}
7571
7572fn encode_expr_src(
7573    expr: &Expr,
7574    counter: &mut usize,
7575    output: &mut String,
7576    interner: &Interner,
7577    variants: &HashMap<String, Vec<String>>,
7578) -> String {
7579    let var = format!("e_{}", *counter);
7580    *counter += 1;
7581
7582    match expr {
7583        Expr::Literal(lit) => match lit {
7584            Literal::Number(n) => {
7585                output.push_str(&format!("Let {} be a new CInt with value {}.\n", var, n));
7586            }
7587            Literal::Boolean(b) => {
7588                output.push_str(&format!("Let {} be a new CBool with value {}.\n", var, b));
7589            }
7590            Literal::Text(s) => {
7591                let text = interner.resolve(*s);
7592                output.push_str(&format!(
7593                    "Let {} be a new CText with value \"{}\".\n",
7594                    var, text
7595                ));
7596            }
7597            Literal::Float(f) => {
7598                // Format faithfully: Rust's `{}` prints integer-valued floats without a
7599                // decimal point (9.0 -> "9"), which would re-parse as an Int and silently
7600                // turn float ops into integer ops. Guarantee a decimal point.
7601                let fs = format!("{}", f);
7602                let fs = if fs.contains('.') || fs.contains('e') || fs.contains('E') {
7603                    fs
7604                } else {
7605                    format!("{}.0", fs)
7606                };
7607                output.push_str(&format!("Let {} be a new CFloat with value {}.\n", var, fs));
7608            }
7609            Literal::Duration(nanos) => {
7610                let millis = nanos / 1_000_000;
7611                let amount_var = format!("e_{}", *counter);
7612                *counter += 1;
7613                output.push_str(&format!(
7614                    "Let {} be a new CInt with value {}.\n",
7615                    amount_var, millis
7616                ));
7617                output.push_str(&format!(
7618                    "Let {} be a new CDuration with amount {} and unit \"milliseconds\".\n",
7619                    var, amount_var
7620                ));
7621            }
7622            Literal::Nothing => {
7623                output.push_str(&format!(
7624                    "Let {} be a new CText with value \"nothing\".\n",
7625                    var
7626                ));
7627            }
7628            _ => {
7629                output.push_str(&format!(
7630                    "Let {} be a new CText with value \"unsupported\".\n",
7631                    var
7632                ));
7633            }
7634        },
7635        Expr::Identifier(sym) => {
7636            let name = interner.resolve(*sym);
7637            output.push_str(&format!(
7638                "Let {} be a new CVar with name \"{}\".\n",
7639                var, name
7640            ));
7641        }
7642        Expr::BinaryOp { op, left, right } => {
7643            let left_var = encode_expr_src(left, counter, output, interner, variants);
7644            let right_var = encode_expr_src(right, counter, output, interner, variants);
7645            let op_str = match op {
7646                BinaryOpKind::Add => "+",
7647                BinaryOpKind::Subtract => "-",
7648                BinaryOpKind::Multiply => "*",
7649                BinaryOpKind::Divide | BinaryOpKind::ExactDivide => "/",
7650                BinaryOpKind::FloorDivide => "//",
7651                BinaryOpKind::Modulo => "%",
7652                BinaryOpKind::Eq => "==",
7653                BinaryOpKind::NotEq => "!=",
7654                BinaryOpKind::Lt => "<",
7655                BinaryOpKind::Gt => ">",
7656                BinaryOpKind::LtEq => "<=",
7657                BinaryOpKind::GtEq => ">=",
7658                BinaryOpKind::And => "&&",
7659                BinaryOpKind::Or => "||",
7660                BinaryOpKind::Concat => "+",
7661                BinaryOpKind::SeqConcat => "followed by",
7662                BinaryOpKind::ApproxEq => "is approximately",
7663                BinaryOpKind::Pow => "**",
7664                BinaryOpKind::BitXor => "^",
7665                BinaryOpKind::BitAnd => "&",
7666                BinaryOpKind::BitOr => "|",
7667                BinaryOpKind::Shl => "<<",
7668                BinaryOpKind::Shr => ">>",
7669            };
7670            output.push_str(&format!(
7671                "Let {} be a new CBinOp with op \"{}\" and left {} and right {}.\n",
7672                var, op_str, left_var, right_var
7673            ));
7674        }
7675        Expr::Not { operand } => {
7676            let inner_var = encode_expr_src(operand, counter, output, interner, variants);
7677            output.push_str(&format!(
7678                "Let {} be a new CNot with inner {}.\n",
7679                var, inner_var
7680            ));
7681        }
7682        Expr::Call { function, args } => {
7683            let fn_name = interner.resolve(*function);
7684            if let Some(field_names) = variants.get(fn_name) {
7685                // Variant constructor call — encode as CNewVariant
7686                let names_var = format!("nvNames_{}", *counter);
7687                *counter += 1;
7688                output.push_str(&format!("Let {} be a new Seq of Text.\n", names_var));
7689                let vals_var = format!("nvVals_{}", *counter);
7690                *counter += 1;
7691                output.push_str(&format!("Let {} be a new Seq of CExpr.\n", vals_var));
7692                for (i, arg) in args.iter().enumerate() {
7693                    let fname = field_names.get(i).map(|s| s.as_str()).unwrap_or("value");
7694                    output.push_str(&format!("Push \"{}\" to {}.\n", fname, names_var));
7695                    let arg_var = encode_expr_src(arg, counter, output, interner, variants);
7696                    output.push_str(&format!("Push {} to {}.\n", arg_var, vals_var));
7697                }
7698                output.push_str(&format!(
7699                    "Let {} be a new CNewVariant with tag \"{}\" and fnames {} and fvals {}.\n",
7700                    var, fn_name, names_var, vals_var
7701                ));
7702            } else {
7703                let args_var = format!("callArgs_{}", *counter);
7704                *counter += 1;
7705                output.push_str(&format!("Let {} be a new Seq of CExpr.\n", args_var));
7706                for arg in args {
7707                    let arg_var = encode_expr_src(arg, counter, output, interner, variants);
7708                    output.push_str(&format!("Push {} to {}.\n", arg_var, args_var));
7709                }
7710                output.push_str(&format!(
7711                    "Let {} be a new CCall with name \"{}\" and args {}.\n",
7712                    var, fn_name, args_var
7713                ));
7714            }
7715        }
7716        Expr::Index { collection, index } => {
7717            let coll_var = encode_expr_src(collection, counter, output, interner, variants);
7718            let idx_var = encode_expr_src(index, counter, output, interner, variants);
7719            output.push_str(&format!(
7720                "Let {} be a new CIndex with coll {} and idx {}.\n",
7721                var, coll_var, idx_var
7722            ));
7723        }
7724        Expr::Length { collection } => {
7725            let coll_var = encode_expr_src(collection, counter, output, interner, variants);
7726            output.push_str(&format!(
7727                "Let {} be a new CLen with target {}.\n",
7728                var, coll_var
7729            ));
7730        }
7731        Expr::FieldAccess { object, field } => {
7732            let obj_var = encode_expr_src(object, counter, output, interner, variants);
7733            let field_name = interner.resolve(*field);
7734            let key_var = format!("e_{}", *counter);
7735            *counter += 1;
7736            output.push_str(&format!(
7737                "Let {} be a new CText with value \"{}\".\n",
7738                key_var, field_name
7739            ));
7740            output.push_str(&format!(
7741                "Let {} be a new CMapGet with target {} and key {}.\n",
7742                var, obj_var, key_var
7743            ));
7744        }
7745        Expr::NewVariant {
7746            variant, fields, ..
7747        } => {
7748            let variant_name = interner.resolve(*variant);
7749            let names_var = format!("nvNames_{}", *counter);
7750            *counter += 1;
7751            output.push_str(&format!("Let {} be a new Seq of Text.\n", names_var));
7752            let vals_var = format!("nvVals_{}", *counter);
7753            *counter += 1;
7754            output.push_str(&format!("Let {} be a new Seq of CExpr.\n", vals_var));
7755            for (field_name, field_expr) in fields {
7756                let fname = interner.resolve(*field_name);
7757                output.push_str(&format!("Push \"{}\" to {}.\n", fname, names_var));
7758                let field_var = encode_expr_src(field_expr, counter, output, interner, variants);
7759                output.push_str(&format!("Push {} to {}.\n", field_var, vals_var));
7760            }
7761            output.push_str(&format!(
7762                "Let {} be a new CNewVariant with tag \"{}\" and fnames {} and fvals {}.\n",
7763                var, variant_name, names_var, vals_var
7764            ));
7765        }
7766        Expr::New {
7767            type_name,
7768            init_fields,
7769            ..
7770        } => {
7771            let tn = interner.resolve(*type_name);
7772            if tn == "Seq" || tn == "List" {
7773                output.push_str(&format!("Let {} be a new CNewSeq.\n", var));
7774            } else if tn == "Set" {
7775                output.push_str(&format!("Let {} be a new CNewSet.\n", var));
7776            } else if tn == "Map" || tn.starts_with("Map ") {
7777                // Empty map creation — encode as CNew with "Map" type
7778                let names_var = format!("nvNames_{}", *counter);
7779                *counter += 1;
7780                output.push_str(&format!("Let {} be a new Seq of Text.\n", names_var));
7781                let vals_var = format!("nvVals_{}", *counter);
7782                *counter += 1;
7783                output.push_str(&format!("Let {} be a new Seq of CExpr.\n", vals_var));
7784                output.push_str(&format!(
7785                    "Let {} be a new CNew with typeName \"Map\" and fieldNames {} and fields {}.\n",
7786                    var, names_var, vals_var
7787                ));
7788            } else if init_fields.is_empty() {
7789                let names_var = format!("nvNames_{}", *counter);
7790                *counter += 1;
7791                output.push_str(&format!("Let {} be a new Seq of Text.\n", names_var));
7792                let vals_var = format!("nvVals_{}", *counter);
7793                *counter += 1;
7794                output.push_str(&format!("Let {} be a new Seq of CExpr.\n", vals_var));
7795                output.push_str(&format!(
7796                    "Let {} be a new CNewVariant with tag \"{}\" and fnames {} and fvals {}.\n",
7797                    var, tn, names_var, vals_var
7798                ));
7799            } else {
7800                let names_var = format!("nvNames_{}", *counter);
7801                *counter += 1;
7802                output.push_str(&format!("Let {} be a new Seq of Text.\n", names_var));
7803                let vals_var = format!("nvVals_{}", *counter);
7804                *counter += 1;
7805                output.push_str(&format!("Let {} be a new Seq of CExpr.\n", vals_var));
7806                for (field_name, field_expr) in init_fields {
7807                    let fname = interner.resolve(*field_name);
7808                    output.push_str(&format!("Push \"{}\" to {}.\n", fname, names_var));
7809                    let field_var =
7810                        encode_expr_src(field_expr, counter, output, interner, variants);
7811                    output.push_str(&format!("Push {} to {}.\n", field_var, vals_var));
7812                }
7813                output.push_str(&format!(
7814                    "Let {} be a new CNewVariant with tag \"{}\" and fnames {} and fvals {}.\n",
7815                    var, tn, names_var, vals_var
7816                ));
7817            }
7818        }
7819        Expr::InterpolatedString(parts) => {
7820            if parts.is_empty() {
7821                output.push_str(&format!("Let {} be a new CText with value \"\".\n", var));
7822            } else {
7823                // Preserve the interpolation as a first-class CInterpolatedString — the IR,
7824                // PE (peExpr), decompiler, and self-interpreter (coreEval) all handle it and
7825                // coerce each part via valToText. Desugaring to a `+` chain was lossy: a
7826                // non-Text leading part produced `Int + Text`, which evalBinOp/applyBinOp do
7827                // not fold (→ VNothing → __unresolvable in the residual).
7828                let parts_var = format!("isparts_{}", *counter);
7829                *counter += 1;
7830                output.push_str(&format!("Let {} be a new Seq of CStringPart.\n", parts_var));
7831                for part in parts {
7832                    match part {
7833                        StringPart::Literal(sym) => {
7834                            let text = interner.resolve(*sym);
7835                            output.push_str(&format!(
7836                                "Push a new CLiteralPart with value \"{}\" to {}.\n",
7837                                text, parts_var
7838                            ));
7839                        }
7840                        StringPart::Expr { value, .. } => {
7841                            let pv = encode_expr_src(value, counter, output, interner, variants);
7842                            output.push_str(&format!(
7843                                "Push a new CExprPart with expr {} to {}.\n",
7844                                pv, parts_var
7845                            ));
7846                        }
7847                    }
7848                }
7849                output.push_str(&format!(
7850                    "Let {} be a new CInterpolatedString with parts {}.\n",
7851                    var, parts_var
7852                ));
7853            }
7854        }
7855        Expr::Range { start, end } => {
7856            let start_var = encode_expr_src(start, counter, output, interner, variants);
7857            let end_var = encode_expr_src(end, counter, output, interner, variants);
7858            output.push_str(&format!(
7859                "Let {} be a new CRange with start {} and end {}.\n",
7860                var, start_var, end_var
7861            ));
7862        }
7863        Expr::Slice {
7864            collection,
7865            start,
7866            end,
7867        } => {
7868            let coll_var = encode_expr_src(collection, counter, output, interner, variants);
7869            let start_var = encode_expr_src(start, counter, output, interner, variants);
7870            let end_var = encode_expr_src(end, counter, output, interner, variants);
7871            output.push_str(&format!(
7872                "Let {} be a new CSlice with coll {} and startIdx {} and endIdx {}.\n",
7873                var, coll_var, start_var, end_var
7874            ));
7875        }
7876        Expr::Copy { expr } => {
7877            let inner_var = encode_expr_src(expr, counter, output, interner, variants);
7878            output.push_str(&format!(
7879                "Let {} be a new CCopy with target {}.\n",
7880                var, inner_var
7881            ));
7882        }
7883        Expr::Contains { collection, value } => {
7884            let coll_var = encode_expr_src(collection, counter, output, interner, variants);
7885            let val_var = encode_expr_src(value, counter, output, interner, variants);
7886            output.push_str(&format!(
7887                "Let {} be a new CContains with coll {} and elem {}.\n",
7888                var, coll_var, val_var
7889            ));
7890        }
7891        Expr::Union { left, right } => {
7892            let left_var = encode_expr_src(left, counter, output, interner, variants);
7893            let right_var = encode_expr_src(right, counter, output, interner, variants);
7894            output.push_str(&format!(
7895                "Let {} be a new CUnion with left {} and right {}.\n",
7896                var, left_var, right_var
7897            ));
7898        }
7899        Expr::Intersection { left, right } => {
7900            let left_var = encode_expr_src(left, counter, output, interner, variants);
7901            let right_var = encode_expr_src(right, counter, output, interner, variants);
7902            output.push_str(&format!(
7903                "Let {} be a new CIntersection with left {} and right {}.\n",
7904                var, left_var, right_var
7905            ));
7906        }
7907        Expr::OptionSome { value } => {
7908            let inner_var = encode_expr_src(value, counter, output, interner, variants);
7909            output.push_str(&format!(
7910                "Let {} be a new COptionSome with inner {}.\n",
7911                var, inner_var
7912            ));
7913        }
7914        Expr::OptionNone => {
7915            output.push_str(&format!("Let {} be a new COptionNone.\n", var));
7916        }
7917        Expr::Tuple(elems) => {
7918            let items_var = format!("tupItems_{}", *counter);
7919            *counter += 1;
7920            output.push_str(&format!("Let {} be a new Seq of CExpr.\n", items_var));
7921            for elem in elems {
7922                let elem_var = encode_expr_src(elem, counter, output, interner, variants);
7923                output.push_str(&format!("Push {} to {}.\n", elem_var, items_var));
7924            }
7925            output.push_str(&format!(
7926                "Let {} be a new CTuple with items {}.\n",
7927                var, items_var
7928            ));
7929        }
7930        Expr::Closure { params, body, .. } => {
7931            let params_var = format!("clp_{}", *counter);
7932            *counter += 1;
7933            output.push_str(&format!("Let {} be a new Seq of Text.\n", params_var));
7934            let mut param_names = HashSet::new();
7935            for (sym, _) in params {
7936                let name = interner.resolve(*sym);
7937                param_names.insert(name.to_string());
7938                output.push_str(&format!("Push \"{}\" to {}.\n", name, params_var));
7939            }
7940            let body_var = format!("clb_{}", *counter);
7941            *counter += 1;
7942            output.push_str(&format!("Let {} be a new Seq of CStmt.\n", body_var));
7943            match body {
7944                ClosureBody::Expression(e) => {
7945                    let ret_expr = encode_expr_src(e, counter, output, interner, variants);
7946                    let ret_var = format!("s_{}", *counter);
7947                    *counter += 1;
7948                    output.push_str(&format!(
7949                        "Let {} be a new CReturn with expr {}.\n",
7950                        ret_var, ret_expr
7951                    ));
7952                    output.push_str(&format!("Push {} to {}.\n", ret_var, body_var));
7953                }
7954                ClosureBody::Block(stmts) => {
7955                    for s in stmts.iter() {
7956                        let sv = encode_stmt_src(s, counter, output, interner, variants);
7957                        output.push_str(&format!("Push {} to {}.\n", sv, body_var));
7958                    }
7959                }
7960            }
7961            let bound: HashSet<String> = param_names;
7962            // Sort the captured free variables for a DETERMINISTIC encoding — a `HashSet`'s random
7963            // iteration order would make the wire bytes vary run-to-run (breaking content-addressing
7964            // AND the fast native-builder byte-identity). The capture set is order-independent
7965            // semantically, so sorting is a pure improvement.
7966            let mut free: Vec<String> = collect_free_vars_expr(expr, interner, &bound)
7967                .into_iter()
7968                .collect();
7969            free.sort();
7970            let cap_var = format!("clc_{}", *counter);
7971            *counter += 1;
7972            output.push_str(&format!("Let {} be a new Seq of Text.\n", cap_var));
7973            for fv in &free {
7974                output.push_str(&format!("Push \"{}\" to {}.\n", fv, cap_var));
7975            }
7976            output.push_str(&format!(
7977                "Let {} be a new CClosure with params {} and body {} and captured {}.\n",
7978                var, params_var, body_var, cap_var
7979            ));
7980        }
7981        Expr::CallExpr { callee, args } => {
7982            let callee_var = encode_expr_src(callee, counter, output, interner, variants);
7983            let args_var = format!("cea_{}", *counter);
7984            *counter += 1;
7985            output.push_str(&format!("Let {} be a new Seq of CExpr.\n", args_var));
7986            for a in args {
7987                let av = encode_expr_src(a, counter, output, interner, variants);
7988                output.push_str(&format!("Push {} to {}.\n", av, args_var));
7989            }
7990            output.push_str(&format!(
7991                "Let {} be a new CCallExpr with target {} and args {}.\n",
7992                var, callee_var, args_var
7993            ));
7994        }
7995        Expr::Give { value } => {
7996            let inner_var = encode_expr_src(value, counter, output, interner, variants);
7997            output.push_str(&format!("Let {} be {}.\n", var, inner_var));
7998        }
7999        Expr::Escape { code, .. } => {
8000            let code_str = interner.resolve(*code);
8001            output.push_str(&format!(
8002                "Let {} be a new CEscExpr with code \"{}\".\n",
8003                var,
8004                code_str.replace('\"', "\\\"")
8005            ));
8006        }
8007        Expr::List(elems) => {
8008            let items_var = format!("litems_{}", *counter);
8009            *counter += 1;
8010            output.push_str(&format!("Let {} be a new Seq of CExpr.\n", items_var));
8011            for elem in elems {
8012                let elem_var = encode_expr_src(elem, counter, output, interner, variants);
8013                output.push_str(&format!("Push {} to {}.\n", elem_var, items_var));
8014            }
8015            output.push_str(&format!(
8016                "Let {} be a new CList with items {}.\n",
8017                var, items_var
8018            ));
8019        }
8020        Expr::ManifestOf { zone } => {
8021            let zone_var = encode_expr_src(zone, counter, output, interner, variants);
8022            output.push_str(&format!(
8023                "Let {} be a new CManifestOf with zn {}.\n",
8024                var, zone_var
8025            ));
8026        }
8027        Expr::ChunkAt { index, zone } => {
8028            let idx_var = encode_expr_src(index, counter, output, interner, variants);
8029            let zone_var = encode_expr_src(zone, counter, output, interner, variants);
8030            output.push_str(&format!(
8031                "Let {} be a new CChunkAt with idx {} and zn {}.\n",
8032                var, idx_var, zone_var
8033            ));
8034        }
8035        Expr::WithCapacity { value, .. } => {
8036            // Capacity is an allocation hint with no runtime semantics (the interpreter ignores
8037            // it). Encode the inner value directly so the residual carries the value, not the
8038            // erased hint — no Core-IR node needed.
8039            return encode_expr_src(value, counter, output, interner, variants);
8040        }
8041        _ => {
8042            output.push_str(&format!(
8043                "Let {} be a new CText with value \"unsupported\".\n",
8044                var
8045            ));
8046        }
8047    }
8048
8049    var
8050}
8051
8052fn encode_stmt_src(
8053    stmt: &Stmt,
8054    counter: &mut usize,
8055    output: &mut String,
8056    interner: &Interner,
8057    variants: &HashMap<String, Vec<String>>,
8058) -> String {
8059    let var = format!("s_{}", *counter);
8060    *counter += 1;
8061
8062    match stmt {
8063        Stmt::Let { var: name, value, .. } => {
8064            let name_str = interner.resolve(*name);
8065            let expr_var = encode_expr_src(value, counter, output, interner, variants);
8066            output.push_str(&format!(
8067                "Let {} be a new CLet with name \"{}\" and expr {}.\n",
8068                var, name_str, expr_var
8069            ));
8070        }
8071        Stmt::Set { target, value } => {
8072            let name_str = interner.resolve(*target);
8073            let expr_var = encode_expr_src(value, counter, output, interner, variants);
8074            output.push_str(&format!(
8075                "Let {} be a new CSet with name \"{}\" and expr {}.\n",
8076                var, name_str, expr_var
8077            ));
8078        }
8079        Stmt::Swap { a, b } => {
8080            // No dedicated CSwap in the PE self-representation; encode the observationally-equivalent
8081            // temp-mediated swap as a CIf-always-true block (the device the Splice arm uses): a fresh
8082            // `tmp := a; a := b; b := tmp`, all in existing CLet/CSet/CVar nodes.
8083            let (an, bn) = (interner.resolve(*a), interner.resolve(*b));
8084            output.push_str(&format!("Let swapBlock_{var} be a new Seq of CStmt.\n"));
8085            output.push_str(&format!("Let swapVarA_{var} be a new CVar with name \"{an}\".\n"));
8086            output.push_str(&format!("Let swapS1_{var} be a new CLet with name \"swaptmp_{var}\" and expr swapVarA_{var}.\n"));
8087            output.push_str(&format!("Push swapS1_{var} to swapBlock_{var}.\n"));
8088            output.push_str(&format!("Let swapVarB_{var} be a new CVar with name \"{bn}\".\n"));
8089            output.push_str(&format!("Let swapS2_{var} be a new CSet with name \"{an}\" and expr swapVarB_{var}.\n"));
8090            output.push_str(&format!("Push swapS2_{var} to swapBlock_{var}.\n"));
8091            output.push_str(&format!("Let swapVarT_{var} be a new CVar with name \"swaptmp_{var}\".\n"));
8092            output.push_str(&format!("Let swapS3_{var} be a new CSet with name \"{bn}\" and expr swapVarT_{var}.\n"));
8093            output.push_str(&format!("Push swapS3_{var} to swapBlock_{var}.\n"));
8094            output.push_str(&format!("Let swapCond_{var} be a new CBool with value true.\n"));
8095            output.push_str(&format!("Let swapEmpty_{var} be a new Seq of CStmt.\n"));
8096            output.push_str(&format!(
8097                "Let {var} be a new CIf with cond swapCond_{var} and thenBlock swapBlock_{var} and elseBlock swapEmpty_{var}.\n"
8098            ));
8099        }
8100        Stmt::If { cond, then_block, else_block } => {
8101            let cond_var = encode_expr_src(cond, counter, output, interner, variants);
8102            let then_stmts: Vec<&Stmt> = then_block.iter().collect();
8103            let then_var = encode_stmt_list_src(&then_stmts, counter, output, interner, variants);
8104            let else_var = if let Some(els) = else_block {
8105                let else_stmts: Vec<&Stmt> = els.iter().collect();
8106                encode_stmt_list_src(&else_stmts, counter, output, interner, variants)
8107            } else {
8108                let empty_var = format!("emptyBlock_{}", *counter);
8109                *counter += 1;
8110                output.push_str(&format!("Let {} be a new Seq of CStmt.\n", empty_var));
8111                empty_var
8112            };
8113            output.push_str(&format!(
8114                "Let {} be a new CIf with cond {} and thenBlock {} and elseBlock {}.\n",
8115                var, cond_var, then_var, else_var
8116            ));
8117        }
8118        Stmt::While { cond, body, .. } => {
8119            let cond_var = encode_expr_src(cond, counter, output, interner, variants);
8120            let body_stmts: Vec<&Stmt> = body.iter().collect();
8121            let body_var = encode_stmt_list_src(&body_stmts, counter, output, interner, variants);
8122            output.push_str(&format!(
8123                "Let {} be a new CWhile with cond {} and body {}.\n",
8124                var, cond_var, body_var
8125            ));
8126        }
8127        Stmt::Splice { body } | Stmt::Reversibly { body } => {
8128            // A Splice — and an output-transparent `Reversibly:` block — encodes as an always-taken
8129            // CIf: observationally equivalent, because the body runs in the enclosing scope and its
8130            // result is unchanged by the block wrapper (the reversible lowering is a VM-only concern
8131            // this self-representation does not model).
8132            let cond_var = format!("splice_cond_{}", *counter);
8133            *counter += 1;
8134            output.push_str(&format!("Let {} be a new CBool with value true.\n", cond_var));
8135            let body_stmts: Vec<&Stmt> = body.iter().collect();
8136            let body_var = encode_stmt_list_src(&body_stmts, counter, output, interner, variants);
8137            let empty_var = format!("emptyBlock_{}", *counter);
8138            *counter += 1;
8139            output.push_str(&format!("Let {} be a new Seq of CStmt.\n", empty_var));
8140            output.push_str(&format!(
8141                "Let {} be a new CIf with cond {} and thenBlock {} and elseBlock {}.\n",
8142                var, cond_var, body_var, empty_var
8143            ));
8144        }
8145        Stmt::Return { value } => {
8146            if let Some(expr) = value {
8147                let expr_var = encode_expr_src(expr, counter, output, interner, variants);
8148                output.push_str(&format!("Let {} be a new CReturn with expr {}.\n", var, expr_var));
8149            } else {
8150                let nothing_var = format!("e_{}", *counter);
8151                *counter += 1;
8152                output.push_str(&format!("Let {} be a new CInt with value 0.\n", nothing_var));
8153                output.push_str(&format!("Let {} be a new CReturn with expr {}.\n", var, nothing_var));
8154            }
8155        }
8156        Stmt::Show { object, .. } => {
8157            let expr_var = encode_expr_src(object, counter, output, interner, variants);
8158            output.push_str(&format!("Let {} be a new CShow with expr {}.\n", var, expr_var));
8159        }
8160        Stmt::Call { function, args } => {
8161            let fn_name = interner.resolve(*function);
8162            let args_var = format!("callSArgs_{}", *counter);
8163            *counter += 1;
8164            output.push_str(&format!("Let {} be a new Seq of CExpr.\n", args_var));
8165            for arg in args {
8166                let arg_var = encode_expr_src(arg, counter, output, interner, variants);
8167                output.push_str(&format!("Push {} to {}.\n", arg_var, args_var));
8168            }
8169            output.push_str(&format!(
8170                "Let {} be a new CCallS with name \"{}\" and args {}.\n",
8171                var, fn_name, args_var
8172            ));
8173        }
8174        Stmt::Push { value, collection } => {
8175            let val_var = encode_expr_src(value, counter, output, interner, variants);
8176            let coll_name = extract_ident_name(collection, interner);
8177            output.push_str(&format!(
8178                "Let {} be a new CPush with expr {} and target \"{}\".\n",
8179                var, val_var, coll_name
8180            ));
8181        }
8182        Stmt::SetIndex { collection, index, value } => {
8183            let coll_name = extract_ident_name(collection, interner);
8184            let idx_var = encode_expr_src(index, counter, output, interner, variants);
8185            let val_var = encode_expr_src(value, counter, output, interner, variants);
8186            output.push_str(&format!(
8187                "Let {} be a new CSetIdx with target \"{}\" and idx {} and val {}.\n",
8188                var, coll_name, idx_var, val_var
8189            ));
8190        }
8191        Stmt::SetField { object, field, value } => {
8192            let map_name = extract_ident_name(object, interner);
8193            let field_name = interner.resolve(*field);
8194            let key_var = format!("e_{}", *counter);
8195            *counter += 1;
8196            output.push_str(&format!("Let {} be a new CText with value \"{}\".\n", key_var, field_name));
8197            let val_var = encode_expr_src(value, counter, output, interner, variants);
8198            output.push_str(&format!(
8199                "Let {} be a new CMapSet with target \"{}\" and key {} and val {}.\n",
8200                var, map_name, key_var, val_var
8201            ));
8202        }
8203        Stmt::Pop { collection, .. } => {
8204            let coll_name = extract_ident_name(collection, interner);
8205            output.push_str(&format!(
8206                "Let {} be a new CPop with target \"{}\".\n",
8207                var, coll_name
8208            ));
8209        }
8210        Stmt::Add { value, collection } => {
8211            let val_var = encode_expr_src(value, counter, output, interner, variants);
8212            let coll_name = extract_ident_name(collection, interner);
8213            output.push_str(&format!(
8214                "Let {} be a new CAdd with elem {} and target \"{}\".\n",
8215                var, val_var, coll_name
8216            ));
8217        }
8218        Stmt::Remove { value, collection } => {
8219            let val_var = encode_expr_src(value, counter, output, interner, variants);
8220            let coll_name = extract_ident_name(collection, interner);
8221            output.push_str(&format!(
8222                "Let {} be a new CRemove with elem {} and target \"{}\".\n",
8223                var, val_var, coll_name
8224            ));
8225        }
8226        Stmt::Inspect { .. } => {
8227            return String::new(); // Handled by encode_stmts_src
8228        }
8229        Stmt::Repeat { .. } => {
8230            return String::new(); // Handled by encode_stmts_src
8231        }
8232        Stmt::Break => {
8233            output.push_str(&format!("Let {} be a new CBreak.\n", var));
8234        }
8235        Stmt::RuntimeAssert { condition, hard, dim: _, reason } => {
8236            let cond_var = encode_expr_src(condition, counter, output, interner, variants);
8237            let msg_var = match reason {
8238                Some(r) => encode_expr_src(r, counter, output, interner, variants),
8239                None => {
8240                    let msg_var = format!("e_{}", *counter);
8241                    *counter += 1;
8242                    output.push_str(&format!("Let {} be a new CText with value \"assertion failed\".\n", msg_var));
8243                    msg_var
8244                }
8245            };
8246            // `Require that` (hard) encodes as a distinct CStmt variant `CHardAssert`
8247            // (NOT `CRequire`, which is the `## Requires` dependency directive) so the
8248            // self-encoding round-trip preserves the enforced/dev distinction.
8249            let variant = if *hard { "CHardAssert" } else { "CRuntimeAssert" };
8250            output.push_str(&format!(
8251                "Let {} be a new {} with cond {} and msg {}.\n",
8252                var, variant, cond_var, msg_var
8253            ));
8254        }
8255        // `Fail with <reason>` is, in the core language, an enforced contract that never holds.
8256        Stmt::Fail { reason } => {
8257            let cond_var = format!("e_{}", *counter);
8258            *counter += 1;
8259            output.push_str(&format!("Let {} be a new CBool with value false.\n", cond_var));
8260            let msg_var = encode_expr_src(reason, counter, output, interner, variants);
8261            output.push_str(&format!("Let {} be a new CHardAssert with cond {} and msg {}.\n", var, cond_var, msg_var));
8262        }
8263        Stmt::Give { object, recipient } => {
8264            let expr_var = encode_expr_src(object, counter, output, interner, variants);
8265            let target_name = extract_ident_name(recipient, interner);
8266            output.push_str(&format!(
8267                "Let {} be a new CGive with expr {} and target \"{}\".\n",
8268                var, expr_var, target_name
8269            ));
8270        }
8271        Stmt::Escape { code, .. } => {
8272            let code_str = interner.resolve(*code);
8273            output.push_str(&format!(
8274                "Let {} be a new CEscStmt with code \"{}\".\n",
8275                var, code_str.replace('\"', "\\\"")
8276            ));
8277        }
8278        Stmt::Sleep { milliseconds } => {
8279            let dur_var = encode_expr_src(milliseconds, counter, output, interner, variants);
8280            output.push_str(&format!(
8281                "Let {} be a new CSleep with duration {}.\n",
8282                var, dur_var
8283            ));
8284        }
8285        Stmt::ReadFrom { var: read_var, source } => {
8286            let var_name = interner.resolve(*read_var);
8287            match source {
8288                ReadSource::Console => {
8289                    output.push_str(&format!(
8290                        "Let {} be a new CReadConsole with target \"{}\".\n",
8291                        var, var_name
8292                    ));
8293                }
8294                ReadSource::File(path_expr) => {
8295                    let path_var = encode_expr_src(path_expr, counter, output, interner, variants);
8296                    output.push_str(&format!(
8297                        "Let {} be a new CReadFile with path {} and target \"{}\".\n",
8298                        var, path_var, var_name
8299                    ));
8300                }
8301            }
8302        }
8303        Stmt::WriteFile { content, path } => {
8304            let path_var = encode_expr_src(path, counter, output, interner, variants);
8305            let content_var = encode_expr_src(content, counter, output, interner, variants);
8306            output.push_str(&format!(
8307                "Let {} be a new CWriteFile with path {} and content {}.\n",
8308                var, path_var, content_var
8309            ));
8310        }
8311        Stmt::Check { source_text, .. } => {
8312            let pred_var = format!("e_{}", *counter);
8313            *counter += 1;
8314            output.push_str(&format!("Let {} be a new CBool with value true.\n", pred_var));
8315            let msg_var = format!("e_{}", *counter);
8316            *counter += 1;
8317            output.push_str(&format!("Let {} be a new CText with value \"{}\".\n", msg_var, source_text.replace('\"', "\\\"")));
8318            output.push_str(&format!(
8319                "Let {} be a new CCheck with predicate {} and msg {}.\n",
8320                var, pred_var, msg_var
8321            ));
8322        }
8323        Stmt::Assert { .. } => {
8324            let prop_var = format!("e_{}", *counter);
8325            *counter += 1;
8326            output.push_str(&format!("Let {} be a new CBool with value true.\n", prop_var));
8327            output.push_str(&format!(
8328                "Let {} be a new CAssert with proposition {}.\n",
8329                var, prop_var
8330            ));
8331        }
8332        Stmt::Trust { justification, .. } => {
8333            let prop_var = format!("e_{}", *counter);
8334            *counter += 1;
8335            output.push_str(&format!("Let {} be a new CBool with value true.\n", prop_var));
8336            let just_str = interner.resolve(*justification);
8337            output.push_str(&format!(
8338                "Let {} be a new CTrust with proposition {} and justification \"{}\".\n",
8339                var, prop_var, just_str
8340            ));
8341        }
8342        Stmt::Require { crate_name, .. } => {
8343            let dep_name = interner.resolve(*crate_name);
8344            output.push_str(&format!(
8345                "Let {} be a new CRequire with dependency \"{}\".\n",
8346                var, dep_name
8347            ));
8348        }
8349        Stmt::MergeCrdt { source, target } => {
8350            let source_var = encode_expr_src(source, counter, output, interner, variants);
8351            // The target may be a struct (`a`) or a struct field (`local's active`); both
8352            // round-trip as surface syntax.
8353            let target_name = extract_ident_name(target, interner);
8354            output.push_str(&format!(
8355                "Let {} be a new CMerge with target \"{}\" and other {}.\n",
8356                var, target_name, source_var
8357            ));
8358        }
8359        // The IDEMPOTENT sibling of `Merge` — encoded as a distinct `CJoin` core node so the self-hosted PE
8360        // round-trips `Converge` back to `Converge` (an idempotent join), NOT to `Merge` (which double-counts).
8361        Stmt::JoinCrdt { source, target } => {
8362            let source_var = encode_expr_src(source, counter, output, interner, variants);
8363            let target_name = extract_ident_name(target, interner);
8364            output.push_str(&format!(
8365                "Let {} be a new CJoin with target \"{}\" and other {}.\n",
8366                var, target_name, source_var
8367            ));
8368        }
8369        Stmt::IncreaseCrdt { object, field, amount } => {
8370            let amount_var = encode_expr_src(amount, counter, output, interner, variants);
8371            // `Increase c's points` — the target is the FIELD, so carry both the object and
8372            // the field name (the residual must say `Increase c's points`, not `Increase c`).
8373            let target_name =
8374                format!("{}'s {}", extract_ident_name(object, interner), interner.resolve(*field));
8375            output.push_str(&format!(
8376                "Let {} be a new CIncrease with target \"{}\" and amount {}.\n",
8377                var, target_name, amount_var
8378            ));
8379        }
8380        Stmt::DecreaseCrdt { object, field, amount } => {
8381            let amount_var = encode_expr_src(amount, counter, output, interner, variants);
8382            let target_name =
8383                format!("{}'s {}", extract_ident_name(object, interner), interner.resolve(*field));
8384            output.push_str(&format!(
8385                "Let {} be a new CDecrease with target \"{}\" and amount {}.\n",
8386                var, target_name, amount_var
8387            ));
8388        }
8389        Stmt::AppendToSequence { sequence, value } => {
8390            let value_var = encode_expr_src(value, counter, output, interner, variants);
8391            let target_name = extract_ident_name(sequence, interner);
8392            output.push_str(&format!(
8393                "Let {} be a new CAppendToSeq with target \"{}\" and value {}.\n",
8394                var, target_name, value_var
8395            ));
8396        }
8397        Stmt::ResolveConflict { object, field, .. } => {
8398            let target_name =
8399                format!("{}'s {}", extract_ident_name(object, interner), interner.resolve(*field));
8400            output.push_str(&format!(
8401                "Let {} be a new CResolve with target \"{}\".\n",
8402                var, target_name
8403            ));
8404        }
8405        Stmt::Sync { var: sync_var, topic } => {
8406            let topic_var = encode_expr_src(topic, counter, output, interner, variants);
8407            let var_name = interner.resolve(*sync_var);
8408            output.push_str(&format!(
8409                "Let {} be a new CSync with target \"{}\" and channel {}.\n",
8410                var, var_name, topic_var
8411            ));
8412        }
8413        Stmt::Mount { var: mount_var, path } => {
8414            let path_var = encode_expr_src(path, counter, output, interner, variants);
8415            let var_name = interner.resolve(*mount_var);
8416            output.push_str(&format!(
8417                "Let {} be a new CMount with target \"{}\" and path {}.\n",
8418                var, var_name, path_var
8419            ));
8420        }
8421        Stmt::Concurrent { tasks } => {
8422            let branches_var = format!("e_{}", *counter);
8423            *counter += 1;
8424            output.push_str(&format!("Let {} be a new Seq of Seq of CStmt.\n", branches_var));
8425            // One inner branch per task — collapsing them loses the per-task
8426            // branch structure the executor / PE handlers iterate over.
8427            for stmt in tasks.iter() {
8428                let branch_var = format!("e_{}", *counter);
8429                *counter += 1;
8430                output.push_str(&format!("Let {} be a new Seq of CStmt.\n", branch_var));
8431                let sv = encode_stmt_src(stmt, counter, output, interner, variants);
8432                if !sv.is_empty() {
8433                    output.push_str(&format!("Push {} to {}.\n", sv, branch_var));
8434                }
8435                output.push_str(&format!("Push {} to {}.\n", branch_var, branches_var));
8436            }
8437            output.push_str(&format!(
8438                "Let {} be a new CConcurrent with branches {}.\n",
8439                var, branches_var
8440            ));
8441        }
8442        Stmt::Parallel { tasks } => {
8443            let branches_var = format!("e_{}", *counter);
8444            *counter += 1;
8445            output.push_str(&format!("Let {} be a new Seq of Seq of CStmt.\n", branches_var));
8446            // One inner branch per task (see Concurrent above).
8447            for stmt in tasks.iter() {
8448                let branch_var = format!("e_{}", *counter);
8449                *counter += 1;
8450                output.push_str(&format!("Let {} be a new Seq of CStmt.\n", branch_var));
8451                let sv = encode_stmt_src(stmt, counter, output, interner, variants);
8452                if !sv.is_empty() {
8453                    output.push_str(&format!("Push {} to {}.\n", sv, branch_var));
8454                }
8455                output.push_str(&format!("Push {} to {}.\n", branch_var, branches_var));
8456            }
8457            output.push_str(&format!(
8458                "Let {} be a new CParallel with branches {}.\n",
8459                var, branches_var
8460            ));
8461        }
8462        Stmt::LaunchTask { function, args } | Stmt::LaunchTaskWithHandle { function, args, .. } => {
8463            let func_name = interner.resolve(*function);
8464            let args_var = format!("e_{}", *counter);
8465            *counter += 1;
8466            output.push_str(&format!("Let {} be a new Seq of CExpr.\n", args_var));
8467            for arg in args {
8468                let av = encode_expr_src(arg, counter, output, interner, variants);
8469                output.push_str(&format!("Push {} to {}.\n", av, args_var));
8470            }
8471            let body_var = format!("e_{}", *counter);
8472            *counter += 1;
8473            output.push_str(&format!("Let {} be a new Seq of CStmt.\n", body_var));
8474            let call_var = format!("e_{}", *counter);
8475            *counter += 1;
8476            output.push_str(&format!(
8477                "Let {} be a new CCallS with name \"{}\" and args {}.\n",
8478                call_var, func_name, args_var
8479            ));
8480            output.push_str(&format!("Push {} to {}.\n", call_var, body_var));
8481            let handle_name = if let Stmt::LaunchTaskWithHandle { handle, .. } = stmt {
8482                interner.resolve(*handle).to_string()
8483            } else {
8484                "_task".to_string()
8485            };
8486            output.push_str(&format!(
8487                "Let {} be a new CLaunchTask with body {} and handle \"{}\".\n",
8488                var, body_var, handle_name
8489            ));
8490        }
8491        Stmt::StopTask { handle } => {
8492            let handle_var = encode_expr_src(handle, counter, output, interner, variants);
8493            output.push_str(&format!(
8494                "Let {} be a new CStopTask with handle {}.\n",
8495                var, handle_var
8496            ));
8497        }
8498        // `Close ch` and `Await h` are OPAQUE deterministic-scheduler concurrency statements the
8499        // partial-evaluator does not model beyond preserving them (the self-interpreter treats channel
8500        // close / task join as scheduling no-ops that never alter a specialized value). To keep the
8501        // Futamura projection COMPLETE — never silently dropping an executable statement, the invariant
8502        // this exhaustive match guards — each rides an existing catalog node that carries its read-set:
8503        // `Close ch` is a single-handle terminal control like `CStopTask`; `Await h into r` reads a handle
8504        // and binds a target exactly like `CReceivePipe`. Their dedicated on-chip/AOT lowering lives in the
8505        // real backends (VM `Op::ChanClose`/`Op::TaskAwait`, `codegen_c`), not in this meta-circular tier.
8506        Stmt::CloseChannel { channel } => {
8507            let chan_var = encode_expr_src(channel, counter, output, interner, variants);
8508            output.push_str(&format!(
8509                "Let {} be a new CStopTask with handle {}.\n",
8510                var, chan_var
8511            ));
8512        }
8513        Stmt::AwaitTask { handle, result } => {
8514            let chan_name = match handle {
8515                Expr::Identifier(sym) => interner.resolve(*sym).to_string(),
8516                _ => "task".to_string(),
8517            };
8518            let target_name = result.map(|r| interner.resolve(r).to_string()).unwrap_or_else(|| "_await".to_string());
8519            output.push_str(&format!(
8520                "Let {} be a new CReceivePipe with chan \"{}\" and target \"{}\".\n",
8521                var, chan_name, target_name
8522            ));
8523        }
8524        Stmt::CreatePipe { var: pipe_var, capacity, .. } => {
8525            let cap = capacity.unwrap_or(32);
8526            let cap_var = format!("e_{}", *counter);
8527            *counter += 1;
8528            output.push_str(&format!("Let {} be a new CInt with value {}.\n", cap_var, cap));
8529            let pipe_name = interner.resolve(*pipe_var);
8530            output.push_str(&format!(
8531                "Let {} be a new CCreatePipe with name \"{}\" and capacity {}.\n",
8532                var, pipe_name, cap_var
8533            ));
8534        }
8535        Stmt::SendPipe { value, pipe } => {
8536            let val_var = encode_expr_src(value, counter, output, interner, variants);
8537            let pipe_name = match pipe {
8538                Expr::Identifier(sym) => interner.resolve(*sym).to_string(),
8539                _ => "pipe".to_string(),
8540            };
8541            output.push_str(&format!(
8542                "Let {} be a new CSendPipe with chan \"{}\" and value {}.\n",
8543                var, pipe_name, val_var
8544            ));
8545        }
8546        Stmt::ReceivePipe { var: recv_var, pipe } => {
8547            let recv_name = interner.resolve(*recv_var);
8548            let pipe_name = match pipe {
8549                Expr::Identifier(sym) => interner.resolve(*sym).to_string(),
8550                _ => "pipe".to_string(),
8551            };
8552            output.push_str(&format!(
8553                "Let {} be a new CReceivePipe with chan \"{}\" and target \"{}\".\n",
8554                var, pipe_name, recv_name
8555            ));
8556        }
8557        Stmt::TrySendPipe { value, pipe, .. } => {
8558            let val_var = encode_expr_src(value, counter, output, interner, variants);
8559            let pipe_name = match pipe {
8560                Expr::Identifier(sym) => interner.resolve(*sym).to_string(),
8561                _ => "pipe".to_string(),
8562            };
8563            output.push_str(&format!(
8564                "Let {} be a new CTrySendPipe with chan \"{}\" and value {}.\n",
8565                var, pipe_name, val_var
8566            ));
8567        }
8568        Stmt::TryReceivePipe { var: recv_var, pipe } => {
8569            let recv_name = interner.resolve(*recv_var);
8570            let pipe_name = match pipe {
8571                Expr::Identifier(sym) => interner.resolve(*sym).to_string(),
8572                _ => "pipe".to_string(),
8573            };
8574            output.push_str(&format!(
8575                "Let {} be a new CTryReceivePipe with chan \"{}\" and target \"{}\".\n",
8576                var, pipe_name, recv_name
8577            ));
8578        }
8579        Stmt::Select { branches } => {
8580            let branches_var = format!("e_{}", *counter);
8581            *counter += 1;
8582            output.push_str(&format!("Let {} be a new Seq of CSelectBranch.\n", branches_var));
8583            for branch in branches {
8584                match branch {
8585                    SelectBranch::Receive { var: recv_var, pipe, body } => {
8586                        let recv_name = interner.resolve(*recv_var);
8587                        let pipe_name = match pipe {
8588                            Expr::Identifier(sym) => interner.resolve(*sym).to_string(),
8589                            _ => "pipe".to_string(),
8590                        };
8591                        let body_var = format!("e_{}", *counter);
8592                        *counter += 1;
8593                        output.push_str(&format!("Let {} be a new Seq of CStmt.\n", body_var));
8594                        for stmt in body.iter() {
8595                            let sv = encode_stmt_src(stmt, counter, output, interner, variants);
8596                            if !sv.is_empty() {
8597                                output.push_str(&format!("Push {} to {}.\n", sv, body_var));
8598                            }
8599                        }
8600                        let branch_var = format!("e_{}", *counter);
8601                        *counter += 1;
8602                        output.push_str(&format!(
8603                            "Let {} be a new CSelectRecv with chan \"{}\" and var \"{}\" and body {}.\n",
8604                            branch_var, pipe_name, recv_name, body_var
8605                        ));
8606                        output.push_str(&format!("Push {} to {}.\n", branch_var, branches_var));
8607                    }
8608                    SelectBranch::Timeout { milliseconds, body } => {
8609                        let dur_var = encode_expr_src(milliseconds, counter, output, interner, variants);
8610                        let body_var = format!("e_{}", *counter);
8611                        *counter += 1;
8612                        output.push_str(&format!("Let {} be a new Seq of CStmt.\n", body_var));
8613                        for stmt in body.iter() {
8614                            let sv = encode_stmt_src(stmt, counter, output, interner, variants);
8615                            if !sv.is_empty() {
8616                                output.push_str(&format!("Push {} to {}.\n", sv, body_var));
8617                            }
8618                        }
8619                        let branch_var = format!("e_{}", *counter);
8620                        *counter += 1;
8621                        output.push_str(&format!(
8622                            "Let {} be a new CSelectTimeout with duration {} and body {}.\n",
8623                            branch_var, dur_var, body_var
8624                        ));
8625                        output.push_str(&format!("Push {} to {}.\n", branch_var, branches_var));
8626                    }
8627                }
8628            }
8629            output.push_str(&format!(
8630                "Let {} be a new CSelect with branches {}.\n",
8631                var, branches_var
8632            ));
8633        }
8634        Stmt::Spawn { agent_type, name } => {
8635            let agent_name = interner.resolve(*agent_type);
8636            let target_name = interner.resolve(*name);
8637            output.push_str(&format!(
8638                "Let {} be a new CSpawn with agentType \"{}\" and target \"{}\".\n",
8639                var, agent_name, target_name
8640            ));
8641        }
8642        Stmt::SendMessage { message, destination, .. } => {
8643            let target_var = encode_expr_src(destination, counter, output, interner, variants);
8644            let msg_var = encode_expr_src(message, counter, output, interner, variants);
8645            output.push_str(&format!(
8646                "Let {} be a new CSendMessage with target {} and msg {}.\n",
8647                var, target_var, msg_var
8648            ));
8649        }
8650        // A batch stream send is encoded for the projection-1 self-interpreter exactly like a send,
8651        // so it is NEVER dropped from the residual (the catch-all would silently drop it). The PE
8652        // dialects pass it through unchanged — networking is opaque to specialization.
8653        Stmt::StreamMessage { values, destination } => {
8654            let target_var = encode_expr_src(destination, counter, output, interner, variants);
8655            let vals_var = encode_expr_src(values, counter, output, interner, variants);
8656            output.push_str(&format!(
8657                "Let {} be a new CStreamMessage with target {} and values {}.\n",
8658                var, target_var, vals_var
8659            ));
8660        }
8661        Stmt::AwaitMessage { into, .. } => {
8662            let await_name = interner.resolve(*into);
8663            output.push_str(&format!(
8664                "Let {} be a new CAwaitMessage with target \"{}\".\n",
8665                var, await_name
8666            ));
8667        }
8668        // The PNP `secure` binding is not modeled by the partial-evaluation self-interpreter (a
8669        // PNP program is a live-networking program, not a PE target); the address encoding is unchanged.
8670        Stmt::Listen { address, secure: _ } => {
8671            let addr_var = encode_expr_src(address, counter, output, interner, variants);
8672            output.push_str(&format!(
8673                "Let {} be a new CListen with addr {} and handler \"default\".\n",
8674                var, addr_var
8675            ));
8676        }
8677        // A `Serve` is a live-networking terminal, not a partial-evaluation target;
8678        // encode its port like a Listen address so no variable read is dropped.
8679        Stmt::Serve { port, handler: _ } => {
8680            let addr_var = encode_expr_src(port, counter, output, interner, variants);
8681            output.push_str(&format!(
8682                "Let {} be a new CListen with addr {} and handler \"default\".\n",
8683                var, addr_var
8684            ));
8685        }
8686        Stmt::ConnectTo { address, secure: _ } => {
8687            let addr_var = encode_expr_src(address, counter, output, interner, variants);
8688            output.push_str(&format!(
8689                "Let {} be a new CConnectTo with addr {} and target \"conn\".\n",
8690                var, addr_var
8691            ));
8692        }
8693        Stmt::Zone { name, body, .. } => {
8694            let zone_name = interner.resolve(*name);
8695            let body_var = format!("e_{}", *counter);
8696            *counter += 1;
8697            output.push_str(&format!("Let {} be a new Seq of CStmt.\n", body_var));
8698            for stmt in body.iter() {
8699                let sv = encode_stmt_src(stmt, counter, output, interner, variants);
8700                if !sv.is_empty() {
8701                    output.push_str(&format!("Push {} to {}.\n", sv, body_var));
8702                }
8703            }
8704            output.push_str(&format!(
8705                "Let {} be a new CZone with name \"{}\" and kind \"heap\" and body {}.\n",
8706                var, zone_name, body_var
8707            ));
8708        }
8709        Stmt::LetPeerAgent { var: pa_var, address } => {
8710            let addr_var = encode_expr_src(address, counter, output, interner, variants);
8711            let pa_name = interner.resolve(*pa_var);
8712            output.push_str(&format!(
8713                "Let {} be a new CConnectTo with addr {} and target \"{}\".\n",
8714                var, addr_var, pa_name
8715            ));
8716        }
8717        // ── DECLARATIONS — no projection-1 BODY encoding (intentionally empty) ──
8718        // These are handled at the PROGRAM level, not as body statements: functions are encoded into
8719        // `encodedFuncMap` as `CFuncDef`; struct/type declarations live in the type catalog; theorems
8720        // and definitions are proof-layer only, with no runtime effect to specialize. They contribute
8721        // nothing to a statement body.
8722        //
8723        // ⚠️  THIS MATCH IS EXHAUSTIVE ON PURPOSE — there is NO `_` wildcard. ⚠️  Every one of the 52
8724        // EXECUTABLE statements above has a real encoding arm, and these 4 declarations are the only
8725        // ones that encode to nothing. Adding a new statement to `Stmt` will FAIL TO COMPILE here
8726        // until it is given an explicit arm — so a statement can NEVER be silently dropped from the
8727        // Futamura projection again (this is exactly how the CStreamMessage drop hid). Do not "fix" a
8728        // build break here by re-adding a `_ =>` wildcard; add the statement's real encoding instead.
8729        Stmt::FunctionDef { .. }
8730        | Stmt::StructDef { .. }
8731        | Stmt::Ui(_)
8732        | Stmt::Fetch { .. }
8733        | Stmt::GivenFetch { .. }
8734        | Stmt::ServeFetches
8735        | Stmt::Replay { .. }
8736        | Stmt::ComponentDef(_)
8737        | Stmt::DirectiveDef { .. }
8738        | Stmt::RouteDef { .. }
8739        | Stmt::MiddlewareDef { .. }
8740        | Stmt::RedirectDef { .. }
8741        | Stmt::Theorem(_)
8742        | Stmt::Definition(_)
8743        | Stmt::Axiom(_)
8744        | Stmt::Theory(_)
8745        // A failure-site marker only ever appears inside an LGX action/handler body — the SAME
8746        // `FrontendSurface` corpus `Stmt::ComponentDef`/`Stmt::Ui` are already, correctly, excluded
8747        // from here: a program containing one is not a Jones corpus program at all
8748        // (`jones_whole_language_lock.rs`), so this arm is defensive, not reachable in practice.
8749        | Stmt::Site(_) => {
8750            return String::new();
8751        }
8752        // `## Test` blocks (and the test-only statements the parser confines to
8753        // their bodies) are declarations to the projection: the runner executes
8754        // them on the interpreter tier; a specialized program never runs them.
8755        Stmt::TestDef { .. }
8756        | Stmt::Expect { .. }
8757        | Stmt::ExpectFail { .. }
8758        | Stmt::ExpectOutput { .. }
8759        | Stmt::AdvanceTime { .. }
8760        | Stmt::GivenFile { .. }
8761        // Observation emission is not yet part of the projection (Wave 7/13);
8762        // `During` is scope-transparent and its body is encoded by the caller's
8763        // list walk, so both contribute no body encoding of their own.
8764        | Stmt::Observe { .. }
8765        | Stmt::During { .. }
8766        | Stmt::ForAll { .. } => {
8767            return String::new();
8768        }
8769    }
8770
8771    var
8772}
8773
8774fn encode_stmts_src(
8775    stmt: &Stmt,
8776    counter: &mut usize,
8777    output: &mut String,
8778    interner: &Interner,
8779    variants: &HashMap<String, Vec<String>>,
8780) -> Vec<String> {
8781    match stmt {
8782        Stmt::Inspect { target, arms, .. } => {
8783            let mut otherwise_stmts: Vec<&Stmt> = Vec::new();
8784            let mut variant_arms: Vec<(&MatchArm, Vec<&Stmt>)> = Vec::new();
8785
8786            for arm in arms {
8787                if arm.variant.is_none() {
8788                    otherwise_stmts = arm.body.iter().collect();
8789                } else {
8790                    let body_refs: Vec<&Stmt> = arm.body.iter().collect();
8791                    variant_arms.push((arm, body_refs));
8792                }
8793            }
8794
8795            if variant_arms.is_empty() {
8796                let mut result = Vec::new();
8797                for s in &otherwise_stmts {
8798                    for v in encode_stmts_src(s, counter, output, interner, variants) {
8799                        result.push(v);
8800                    }
8801                }
8802                return result;
8803            }
8804
8805            // Flat CIf encoding: each arm becomes an independent CIf with empty else.
8806            // Since Inspect arms are mutually exclusive (exactly one tag matches),
8807            // flat CIf is semantically equivalent to nested CIf chains but avoids
8808            // deep nesting that the interpreter's inline CIf handler can't navigate.
8809            let has_otherwise = !otherwise_stmts.is_empty();
8810            let mut result = Vec::new();
8811
8812            // If there's an Otherwise block, track whether any arm matched
8813            let matched_var_name = if has_otherwise {
8814                // The flag name uses the DETERMINISTIC per-program Inspect-Otherwise index (shared with
8815                // the native builder), NOT the global intermediate counter — so the fast builder can
8816                // reproduce this desugaring byte-for-byte. The `counter` bump is kept so every OTHER
8817                // (source-only, non-wire) intermediate name downstream is unchanged.
8818                let name = format!("__inspectMatched_{}", next_inspect_otherwise_idx());
8819                *counter += 1;
8820                let false_expr = format!("e_{}", *counter);
8821                *counter += 1;
8822                output.push_str(&format!(
8823                    "Let {} be a new CBool with value false.\n",
8824                    false_expr
8825                ));
8826                let let_stmt = format!("s_{}", *counter);
8827                *counter += 1;
8828                output.push_str(&format!(
8829                    "Let {} be a new CLet with name \"{}\" and expr {}.\n",
8830                    let_stmt, name, false_expr
8831                ));
8832                result.push(let_stmt);
8833                Some(name)
8834            } else {
8835                None
8836            };
8837
8838            // Each variant arm becomes: CIf(tag == "Variant", [bindings + body], [])
8839            for (arm, body_stmts) in &variant_arms {
8840                let variant_name = interner.resolve(arm.variant.unwrap());
8841
8842                // Condition: tag == "VariantName"
8843                let tag_target = encode_expr_src(target, counter, output, interner, variants);
8844                let tag_key = format!("e_{}", *counter);
8845                *counter += 1;
8846                output.push_str(&format!(
8847                    "Let {} be a new CText with value \"__tag\".\n",
8848                    tag_key
8849                ));
8850                let tag_get = format!("e_{}", *counter);
8851                *counter += 1;
8852                output.push_str(&format!(
8853                    "Let {} be a new CMapGet with target {} and key {}.\n",
8854                    tag_get, tag_target, tag_key
8855                ));
8856                let variant_text = format!("e_{}", *counter);
8857                *counter += 1;
8858                output.push_str(&format!(
8859                    "Let {} be a new CText with value \"{}\".\n",
8860                    variant_text, variant_name
8861                ));
8862                let cond_var = format!("e_{}", *counter);
8863                *counter += 1;
8864                output.push_str(&format!(
8865                    "Let {} be a new CBinOp with op \"==\" and left {} and right {}.\n",
8866                    cond_var, tag_get, variant_text
8867                ));
8868
8869                // Then-block: [optionally set matched flag, bindings, body]
8870                let then_list = format!("stmtList_{}", *counter);
8871                *counter += 1;
8872                output.push_str(&format!("Let {} be a new Seq of CStmt.\n", then_list));
8873
8874                // Set matched flag if needed
8875                if let Some(ref mname) = matched_var_name {
8876                    let true_expr = format!("e_{}", *counter);
8877                    *counter += 1;
8878                    output.push_str(&format!(
8879                        "Let {} be a new CBool with value true.\n",
8880                        true_expr
8881                    ));
8882                    let set_stmt = format!("s_{}", *counter);
8883                    *counter += 1;
8884                    output.push_str(&format!(
8885                        "Let {} be a new CSet with name \"{}\" and expr {}.\n",
8886                        set_stmt, mname, true_expr
8887                    ));
8888                    output.push_str(&format!("Push {} to {}.\n", set_stmt, then_list));
8889                }
8890
8891                // Bindings
8892                for (field_name, binding_name) in &arm.bindings {
8893                    let field_str = interner.resolve(*field_name);
8894                    let bind_str = interner.resolve(*binding_name);
8895                    let bind_target = encode_expr_src(target, counter, output, interner, variants);
8896                    let fkey = format!("e_{}", *counter);
8897                    *counter += 1;
8898                    output.push_str(&format!(
8899                        "Let {} be a new CText with value \"{}\".\n",
8900                        fkey, field_str
8901                    ));
8902                    let fget = format!("e_{}", *counter);
8903                    *counter += 1;
8904                    output.push_str(&format!(
8905                        "Let {} be a new CMapGet with target {} and key {}.\n",
8906                        fget, bind_target, fkey
8907                    ));
8908                    let bind_let = format!("s_{}", *counter);
8909                    *counter += 1;
8910                    output.push_str(&format!(
8911                        "Let {} be a new CLet with name \"{}\" and expr {}.\n",
8912                        bind_let, bind_str, fget
8913                    ));
8914                    output.push_str(&format!("Push {} to {}.\n", bind_let, then_list));
8915                }
8916
8917                // Body statements (use encode_stmts_src for Inspect/Repeat)
8918                for body_stmt in body_stmts {
8919                    match body_stmt {
8920                        Stmt::Inspect { .. } | Stmt::Repeat { .. } => {
8921                            let vars =
8922                                encode_stmts_src(body_stmt, counter, output, interner, variants);
8923                            for v in vars {
8924                                output.push_str(&format!("Push {} to {}.\n", v, then_list));
8925                            }
8926                        }
8927                        _ => {
8928                            let bvar =
8929                                encode_stmt_src(body_stmt, counter, output, interner, variants);
8930                            if !bvar.is_empty() {
8931                                output.push_str(&format!("Push {} to {}.\n", bvar, then_list));
8932                            }
8933                        }
8934                    }
8935                }
8936
8937                // Empty else block
8938                let empty_else = format!("stmtList_{}", *counter);
8939                *counter += 1;
8940                output.push_str(&format!("Let {} be a new Seq of CStmt.\n", empty_else));
8941
8942                // CIf node
8943                let if_var = format!("s_{}", *counter);
8944                *counter += 1;
8945                output.push_str(&format!(
8946                    "Let {} be a new CIf with cond {} and thenBlock {} and elseBlock {}.\n",
8947                    if_var, cond_var, then_list, empty_else
8948                ));
8949
8950                result.push(if_var);
8951            }
8952
8953            // Otherwise: CIf(CNot(__inspectMatched), otherwise_body, [])
8954            if let Some(ref mname) = matched_var_name {
8955                let matched_ref = format!("e_{}", *counter);
8956                *counter += 1;
8957                output.push_str(&format!(
8958                    "Let {} be a new CVar with name \"{}\".\n",
8959                    matched_ref, mname
8960                ));
8961                let not_matched = format!("e_{}", *counter);
8962                *counter += 1;
8963                output.push_str(&format!(
8964                    "Let {} be a new CNot with inner {}.\n",
8965                    not_matched, matched_ref
8966                ));
8967
8968                let otherwise_block =
8969                    encode_stmt_list_src(&otherwise_stmts, counter, output, interner, variants);
8970                let empty_else = format!("stmtList_{}", *counter);
8971                *counter += 1;
8972                output.push_str(&format!("Let {} be a new Seq of CStmt.\n", empty_else));
8973
8974                let otherwise_if = format!("s_{}", *counter);
8975                *counter += 1;
8976                output.push_str(&format!(
8977                    "Let {} be a new CIf with cond {} and thenBlock {} and elseBlock {}.\n",
8978                    otherwise_if, not_matched, otherwise_block, empty_else
8979                ));
8980                result.push(otherwise_if);
8981            }
8982
8983            result
8984        }
8985        Stmt::Repeat {
8986            pattern,
8987            iterable,
8988            body,
8989            ..
8990        } => {
8991            let loop_var_name = match pattern {
8992                Pattern::Identifier(sym) => interner.resolve(*sym).to_string(),
8993                Pattern::Tuple(syms) => {
8994                    if let Some(s) = syms.first() {
8995                        interner.resolve(*s).to_string()
8996                    } else {
8997                        "item".to_string()
8998                    }
8999                }
9000            };
9001
9002            // Range-based repeat: encode as CRepeatRange
9003            if let Expr::Range { start, end } = iterable {
9004                let start_var = encode_expr_src(start, counter, output, interner, variants);
9005                let end_var = encode_expr_src(end, counter, output, interner, variants);
9006                let body_stmts: Vec<&Stmt> = body.iter().collect();
9007                let body_var =
9008                    encode_stmt_list_src(&body_stmts, counter, output, interner, variants);
9009                let rr = format!("s_{}", *counter);
9010                *counter += 1;
9011                output.push_str(&format!(
9012                    "Let {} be a new CRepeatRange with var \"{}\" and start {} and end {} and body {}.\n",
9013                    rr, loop_var_name, start_var, end_var, body_var
9014                ));
9015                return vec![rr];
9016            }
9017
9018            // Collection-based repeat: encode as CRepeat
9019            let coll_var = encode_expr_src(iterable, counter, output, interner, variants);
9020            let body_stmts: Vec<&Stmt> = body.iter().collect();
9021            let body_var = encode_stmt_list_src(&body_stmts, counter, output, interner, variants);
9022            let rep = format!("s_{}", *counter);
9023            *counter += 1;
9024            output.push_str(&format!(
9025                "Let {} be a new CRepeat with var \"{}\" and coll {} and body {}.\n",
9026                rep, loop_var_name, coll_var, body_var
9027            ));
9028            vec![rep]
9029        }
9030        // A CRDT op through a struct field (`Add x to p's guests`, `Append x to d's lines`)
9031        // — force the base struct dynamic FIRST, so the PE doesn't statically fold a struct
9032        // it then mutates, then emit the op itself.
9033        Stmt::Add { collection, .. }
9034        | Stmt::Remove { collection, .. }
9035        | Stmt::AppendToSequence {
9036            sequence: collection,
9037            ..
9038        } => {
9039            let mut result = Vec::new();
9040            if let Some(fd) = emit_force_dynamic(collection, counter, output, interner) {
9041                result.push(fd);
9042            }
9043            let v = encode_stmt_src(stmt, counter, output, interner, variants);
9044            if !v.is_empty() {
9045                result.push(v);
9046            }
9047            result
9048        }
9049        // A CRDT op that mutates the WHOLE struct (`Increase c's score`, `Merge b into a`) —
9050        // force the struct's root variable dynamic first, so the PE doesn't fold a counter /
9051        // register it then mutates.
9052        Stmt::IncreaseCrdt { object, .. }
9053        | Stmt::DecreaseCrdt { object, .. }
9054        | Stmt::ResolveConflict { object, .. }
9055        | Stmt::MergeCrdt { target: object, .. }
9056        | Stmt::JoinCrdt { target: object, .. } => {
9057            let mut result = Vec::new();
9058            if let Some(fd) = emit_force_dynamic_struct(object, counter, output, interner) {
9059                result.push(fd);
9060            }
9061            let v = encode_stmt_src(stmt, counter, output, interner, variants);
9062            if !v.is_empty() {
9063                result.push(v);
9064            }
9065            result
9066        }
9067        _ => {
9068            let v = encode_stmt_src(stmt, counter, output, interner, variants);
9069            if v.is_empty() {
9070                vec![]
9071            } else {
9072                vec![v]
9073            }
9074        }
9075    }
9076}
9077
9078fn encode_stmt_list_src(
9079    stmts: &[&Stmt],
9080    counter: &mut usize,
9081    output: &mut String,
9082    interner: &Interner,
9083    variants: &HashMap<String, Vec<String>>,
9084) -> String {
9085    let list_var = format!("stmtList_{}", *counter);
9086    *counter += 1;
9087    output.push_str(&format!("Let {} be a new Seq of CStmt.\n", list_var));
9088
9089    for stmt in stmts {
9090        for stmt_var in encode_stmts_src(stmt, counter, output, interner, variants) {
9091            output.push_str(&format!("Push {} to {}.\n", stmt_var, list_var));
9092        }
9093    }
9094
9095    list_var
9096}
9097
9098fn extract_ident_name(expr: &Expr, interner: &Interner) -> String {
9099    match expr {
9100        Expr::Identifier(sym) => interner.resolve(*sym).to_string(),
9101        // A struct-field target (`p's guests`) round-trips as its LOGOS surface syntax, so
9102        // the PE residual decompiles back to a valid field access the tree-walker re-parses
9103        // — `Add x to p's guests`, `Append x to d's lines`. Without this the target collapsed
9104        // to "unknown" and the residual referenced an undefined variable.
9105        Expr::FieldAccess { object, field } => {
9106            format!(
9107                "{}'s {}",
9108                extract_ident_name(object, interner),
9109                interner.resolve(*field)
9110            )
9111        }
9112        _ => "unknown".to_string(),
9113    }
9114}
9115
9116/// The ROOT variable a CRDT target mutates: `p's guests` → `p`, a bare `s` → `s`. The PE
9117/// can't fold a struct it later mutates through a field, so when this differs from the
9118/// surface target (i.e. the target IS a struct field) the encoder emits a [`CForceDynamic`]
9119/// marker that forces `p` dynamic. Computed in Rust so the self-interpreter — which must
9120/// compile to statically-typed Rust for self-application — never parses the field path.
9121fn crdt_base_var(expr: &Expr, interner: &Interner) -> Option<String> {
9122    match expr {
9123        Expr::FieldAccess { object, .. } => Some(crdt_base_var_root(object, interner)),
9124        _ => None,
9125    }
9126}
9127
9128fn crdt_base_var_root(expr: &Expr, interner: &Interner) -> String {
9129    match expr {
9130        Expr::Identifier(sym) => interner.resolve(*sym).to_string(),
9131        Expr::FieldAccess { object, .. } => crdt_base_var_root(object, interner),
9132        _ => "unknown".to_string(),
9133    }
9134}
9135
9136/// Emit a `CForceDynamic` node binding `base` and return its node var. Prepended before a
9137/// CRDT op so the PE invalidates the (struct) binding before it can fold it.
9138fn emit_force_dynamic_named(base: &str, counter: &mut usize, output: &mut String) -> String {
9139    let v = format!("s_{}", *counter);
9140    *counter += 1;
9141    output.push_str(&format!(
9142        "Let {} be a new CForceDynamic with name \"{}\".\n",
9143        v, base
9144    ));
9145    v
9146}
9147
9148/// `CForceDynamic` for a COLLECTION op (`Add`/`Remove`/`Append`): only a struct-field target
9149/// needs it (a bare-variable collection is one the PE already tracks). `None` for bare vars.
9150fn emit_force_dynamic(
9151    collection: &Expr,
9152    counter: &mut usize,
9153    output: &mut String,
9154    interner: &Interner,
9155) -> Option<String> {
9156    let base = crdt_base_var(collection, interner)?;
9157    Some(emit_force_dynamic_named(&base, counter, output))
9158}
9159
9160/// `CForceDynamic` for a struct-MUTATING CRDT op (`Increase`/`Decrease`/`Resolve`/`Merge`):
9161/// the whole struct is mutated, so its root variable is ALWAYS forced dynamic.
9162fn emit_force_dynamic_struct(
9163    object: &Expr,
9164    counter: &mut usize,
9165    output: &mut String,
9166    interner: &Interner,
9167) -> Option<String> {
9168    match object {
9169        Expr::Identifier(_) | Expr::FieldAccess { .. } => Some(emit_force_dynamic_named(
9170            &crdt_base_var_root(object, interner),
9171            counter,
9172            output,
9173        )),
9174        _ => None,
9175    }
9176}
9177
9178/// First Futamura Projection: PE(interpreter, program) = compiled_program
9179///
9180/// Specializes the interpreter with respect to a fixed program, producing
9181/// a compiled version with no interpretive overhead. For a self-interpreter
9182/// (where source and target language are the same), this produces the
9183/// program itself, with static optimizations applied.
9184///
9185/// The pipeline:
9186/// 1. Parse the program source
9187/// 2. Run the optimizer (fold, propagate, PE, DCE)
9188/// 3. Decompile the optimized AST back to source
9189/// 4. Verify no interpretive overhead remains
9190pub fn projection1_source(
9191    _core_types: &str,
9192    _interpreter: &str,
9193    program: &str,
9194) -> Result<String, String> {
9195    let full_source = if program.contains("## Main") || program.contains("## To ") {
9196        program.to_string()
9197    } else {
9198        format!("## Main\n{}", program)
9199    };
9200
9201    let mut interner = Interner::new();
9202    let mut lexer = Lexer::new(&full_source, &mut interner);
9203    let tokens = lexer.tokenize();
9204
9205    let type_registry = {
9206        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
9207        let result = discovery.run_full();
9208        result.types
9209    };
9210
9211    let mut world_state = WorldState::new();
9212    let expr_arena = Arena::new();
9213    let term_arena = Arena::new();
9214    let np_arena = Arena::new();
9215    let sym_arena = Arena::new();
9216    let role_arena = Arena::new();
9217    let pp_arena = Arena::new();
9218    let stmt_arena: Arena<Stmt> = Arena::new();
9219    let _compile_facts = crate::optimize::facts::scope();
9220    let imperative_expr_arena: Arena<Expr> = Arena::new();
9221    let type_expr_arena: Arena<TypeExpr> = Arena::new();
9222
9223    let ast_ctx = AstContext::with_types(
9224        &expr_arena,
9225        &term_arena,
9226        &np_arena,
9227        &sym_arena,
9228        &role_arena,
9229        &pp_arena,
9230        &stmt_arena,
9231        &imperative_expr_arena,
9232        &type_expr_arena,
9233    );
9234
9235    let mut parser = crate::parser::Parser::new(
9236        tokens,
9237        &mut world_state,
9238        &mut interner,
9239        ast_ctx,
9240        type_registry,
9241    );
9242    let stmts = parser
9243        .parse_program()
9244        .map_err(|e| format!("Parse error: {}", describe_parse_error(&e)))?;
9245
9246    // Honor `## No <opt>` decorators here too — captured before the optimizer reuses
9247    // `&mut interner` (a bare `from_env()` would drop them).
9248    let opt_config = {
9249        let mut c =
9250            crate::optimization::OptimizationConfig::from_env().merged(&parser.program_opt_flags());
9251        c.normalize();
9252        c
9253    };
9254    let resolved = crate::resolve_program::resolve_program(
9255        &stmts,
9256        crate::ast_map::Arenas {
9257            exprs: &imperative_expr_arena,
9258            stmts: &stmt_arena,
9259            types: &type_expr_arena,
9260        },
9261        &mut interner,
9262        opt_config.is_on(crate::optimization::Opt::Comptime),
9263        &crate::loader::library_owned_functions(&full_source),
9264    );
9265    let stmts: Vec<Stmt> = match resolved {
9266        Some(rw) => rw.to_vec(),
9267        None => stmts,
9268    };
9269
9270    // First Futamura Projection: PE(interpreter, program) = compiled_program.
9271    // Use the projection-safe optimizer: fold + propagate + PE + CTFE.
9272    // This preserves control-flow structure (If/While) while still folding
9273    // constants, propagating values, and specializing function calls.
9274    let optimized = crate::optimize::optimize_for_projection(
9275        stmts,
9276        &imperative_expr_arena,
9277        &stmt_arena,
9278        &mut interner,
9279        &opt_config,
9280    );
9281
9282    let mut output = String::new();
9283
9284    for stmt in &optimized {
9285        if matches!(stmt, Stmt::FunctionDef { .. }) {
9286            decompile_stmt(stmt, &interner, &mut output, 0);
9287            output.push('\n');
9288        }
9289    }
9290
9291    output.push_str("## Main\n");
9292    for stmt in &optimized {
9293        if !matches!(stmt, Stmt::FunctionDef { .. }) {
9294            decompile_stmt(stmt, &interner, &mut output, 0);
9295        }
9296    }
9297
9298    // Re-attach the program's type / struct definitions so a `new <Shared struct>`
9299    // in the residual can default-fill its CRDT fields (matches the genuine PE's
9300    // `projection1_source_real_fast`). Without this the residual reads an unset
9301    // field → "Field 'guests' not found".
9302    Ok(prepend_type_definitions(&full_source, output))
9303}
9304
9305fn decompile_stmt(stmt: &Stmt, interner: &Interner, out: &mut String, indent: usize) {
9306    let pad = "    ".repeat(indent);
9307    match stmt {
9308        Stmt::ComponentDef(def) => decompile_component(def, interner, out),
9309        Stmt::DirectiveDef {
9310            name,
9311            params,
9312            body,
9313            removed,
9314        } => {
9315            out.push_str(&format!(
9316                "## Directive {} {}:\n",
9317                interner.resolve(*name),
9318                decompile_params(params, interner)
9319            ));
9320            for inner in body.iter() {
9321                decompile_stmt(inner, interner, out, 1);
9322            }
9323            if let Some(r) = removed {
9324                out.push_str("    When removed:\n");
9325                for inner in r.iter() {
9326                    decompile_stmt(inner, interner, out, 2);
9327                }
9328            }
9329        }
9330        Stmt::RouteDef {
9331            method,
9332            path,
9333            params,
9334            return_type,
9335            body,
9336            ..
9337        } => {
9338            let ret = return_type
9339                .map(|t| format!(" -> {}", decompile_type_expr(t, interner)))
9340                .unwrap_or_default();
9341            let ps = decompile_params(params, interner);
9342            out.push_str(&format!(
9343                "## Route {} {}{}{}:\n",
9344                interner.resolve(*method),
9345                interner.resolve(*path),
9346                if ps.is_empty() {
9347                    String::new()
9348                } else {
9349                    format!(" {ps}")
9350                },
9351                ret
9352            ));
9353            match &**body {
9354                logicaffeine_language::ast::component::RouteBody::Statements(b) => {
9355                    for inner in b.iter() {
9356                        decompile_stmt(inner, interner, out, 1);
9357                    }
9358                }
9359                logicaffeine_language::ast::component::RouteBody::View(view) => {
9360                    for line in decompile_view(view, interner).lines() {
9361                        out.push_str(&format!("    {line}\n"));
9362                    }
9363                }
9364            }
9365        }
9366        Stmt::MiddlewareDef { param, body } => {
9367            out.push_str(&format!(
9368                "## Before each request ({}: {}) -> Option of Response:\n",
9369                interner.resolve(param.0),
9370                decompile_type_expr(param.1, interner)
9371            ));
9372            for inner in body.iter() {
9373                decompile_stmt(inner, interner, out, 1);
9374            }
9375        }
9376        Stmt::RedirectDef { from, to } => {
9377            out.push_str(&format!(
9378                "## Redirect {} -> {}.\n",
9379                interner.resolve(*from),
9380                interner.resolve(*to)
9381            ));
9382        }
9383        Stmt::FunctionDef {
9384            name,
9385            params,
9386            body,
9387            return_type,
9388            ..
9389        } => {
9390            let fn_name = interner.resolve(*name);
9391            let param_strs: Vec<String> = params
9392                .iter()
9393                .map(|(name, ty)| {
9394                    let pname = interner.resolve(*name);
9395                    format!("{}: {}", pname, decompile_type_expr(ty, interner))
9396                })
9397                .collect();
9398            let ret_str = if let Some(rt) = return_type {
9399                format!(" -> {}", decompile_type_expr(rt, interner))
9400            } else {
9401                String::new()
9402            };
9403            out.push_str(&format!(
9404                "{}## To {} ({}){}:\n",
9405                pad,
9406                fn_name,
9407                param_strs.join(", "),
9408                ret_str
9409            ));
9410            for s in body.iter() {
9411                decompile_stmt(s, interner, out, indent + 1);
9412            }
9413        }
9414        Stmt::Let {
9415            var,
9416            ty,
9417            value,
9418            mutable,
9419        } => {
9420            let name = interner.resolve(*var);
9421            let declared = ty
9422                .map(|t| format!(": {}", decompile_type_expr(t, interner)))
9423                .unwrap_or_default();
9424            let expr_str = decompile_expr(value, interner);
9425            let mutable = if *mutable { "mutable " } else { "" };
9426            out.push_str(&format!("{pad}Let {mutable}{name}{declared} be {expr_str}.\n"));
9427        }
9428        Stmt::Set { target, value } => {
9429            let name = interner.resolve(*target);
9430            let expr_str = decompile_expr(value, interner);
9431            out.push_str(&format!("{}Set {} to {}.\n", pad, name, expr_str));
9432        }
9433        Stmt::Show { object, .. } => {
9434            let expr_str = decompile_expr(object, interner);
9435            out.push_str(&format!("{}Show {}.\n", pad, expr_str));
9436        }
9437        Stmt::Return { value } => {
9438            if let Some(expr) = value {
9439                let expr_str = decompile_expr(expr, interner);
9440                out.push_str(&format!("{}Return {}.\n", pad, expr_str));
9441            } else {
9442                out.push_str(&format!("{}Return.\n", pad));
9443            }
9444        }
9445        Stmt::If {
9446            cond,
9447            then_block,
9448            else_block,
9449        } => {
9450            let cond_str = decompile_expr(cond, interner);
9451            out.push_str(&format!("{}If {}:\n", pad, cond_str));
9452            for s in then_block.iter() {
9453                decompile_stmt(s, interner, out, indent + 1);
9454            }
9455            if let Some(els) = else_block {
9456                out.push_str(&format!("{}Otherwise:\n", pad));
9457                for s in els.iter() {
9458                    decompile_stmt(s, interner, out, indent + 1);
9459                }
9460            }
9461        }
9462        Stmt::While { cond, body, .. } => {
9463            let cond_str = decompile_expr(cond, interner);
9464            out.push_str(&format!("{}While {}:\n", pad, cond_str));
9465            for s in body.iter() {
9466                decompile_stmt(s, interner, out, indent + 1);
9467            }
9468        }
9469        Stmt::Call { function, args } => {
9470            let fn_name = interner.resolve(*function);
9471            let arg_strs: Vec<String> = args.iter().map(|a| decompile_expr(a, interner)).collect();
9472            if arg_strs.is_empty() {
9473                out.push_str(&format!("{}{}().\n", pad, fn_name));
9474            } else {
9475                out.push_str(&format!("{}{}({}).\n", pad, fn_name, arg_strs.join(", ")));
9476            }
9477        }
9478        Stmt::Push { value, collection } => {
9479            let val_str = decompile_expr(value, interner);
9480            let coll_str = decompile_expr(collection, interner);
9481            out.push_str(&format!("{}Push {} to {}.\n", pad, val_str, coll_str));
9482        }
9483        Stmt::SetIndex {
9484            collection,
9485            index,
9486            value,
9487        } => {
9488            let coll_str = decompile_expr(collection, interner);
9489            let idx_str = decompile_expr(index, interner);
9490            let val_str = decompile_expr(value, interner);
9491            out.push_str(&format!(
9492                "{}Set item {} of {} to {}.\n",
9493                pad, idx_str, coll_str, val_str
9494            ));
9495        }
9496        Stmt::SetField {
9497            object,
9498            field,
9499            value,
9500        } => {
9501            let obj_str = decompile_expr(object, interner);
9502            let field_name = interner.resolve(*field);
9503            let val_str = decompile_expr(value, interner);
9504            out.push_str(&format!(
9505                "{}Set {} of {} to {}.\n",
9506                pad, field_name, obj_str, val_str
9507            ));
9508        }
9509        Stmt::Repeat {
9510            pattern,
9511            iterable,
9512            body,
9513            ..
9514        } => {
9515            let var_name = match pattern {
9516                Pattern::Identifier(sym) => interner.resolve(*sym).to_string(),
9517                Pattern::Tuple(syms) => syms
9518                    .iter()
9519                    .map(|s| interner.resolve(*s).to_string())
9520                    .collect::<Vec<_>>()
9521                    .join(", "),
9522            };
9523            let iter_str = decompile_expr(iterable, interner);
9524            out.push_str(&format!(
9525                "{}Repeat for {} in {}:\n",
9526                pad, var_name, iter_str
9527            ));
9528            for s in body.iter() {
9529                decompile_stmt(s, interner, out, indent + 1);
9530            }
9531        }
9532        Stmt::Inspect { target, arms, .. } => {
9533            let target_str = decompile_expr(target, interner);
9534            out.push_str(&format!("{}Inspect {}:\n", pad, target_str));
9535            for arm in arms {
9536                if let Some(variant) = arm.variant {
9537                    let variant_name = interner.resolve(variant);
9538                    let bindings: Vec<String> = arm
9539                        .bindings
9540                        .iter()
9541                        .map(|(_, b)| interner.resolve(*b).to_string())
9542                        .collect();
9543                    if bindings.is_empty() {
9544                        out.push_str(&format!("{}    When {}:\n", pad, variant_name));
9545                    } else {
9546                        out.push_str(&format!(
9547                            "{}    When {}({}):\n",
9548                            pad,
9549                            variant_name,
9550                            bindings.join(", ")
9551                        ));
9552                    }
9553                } else {
9554                    out.push_str(&format!("{}    Otherwise:\n", pad));
9555                }
9556                for s in arm.body.iter() {
9557                    decompile_stmt(s, interner, out, indent + 2);
9558                }
9559            }
9560        }
9561        Stmt::Pop { collection, into } => {
9562            let coll_str = decompile_expr(collection, interner);
9563            if let Some(target) = into {
9564                let target_name = interner.resolve(*target);
9565                out.push_str(&format!(
9566                    "{}Pop from {} into {}.\n",
9567                    pad, coll_str, target_name
9568                ));
9569            } else {
9570                out.push_str(&format!("{}Pop from {}.\n", pad, coll_str));
9571            }
9572        }
9573        Stmt::Break => {
9574            out.push_str(&format!("{}Break.\n", pad));
9575        }
9576        Stmt::RuntimeAssert {
9577            condition,
9578            hard,
9579            dim: _,
9580            reason,
9581        } => {
9582            let cond_str = decompile_expr(condition, interner);
9583            // Preserve the enforced/dev distinction: `Require that` (hard) survives the
9584            // round-trip rather than silently becoming the dev-only `Assert that`.
9585            let kw = if *hard { "Require that" } else { "Assert that" };
9586            match reason {
9587                Some(r) => out.push_str(&format!(
9588                    "{}{} {}, otherwise {}.\n",
9589                    pad,
9590                    kw,
9591                    cond_str,
9592                    decompile_expr(r, interner)
9593                )),
9594                None => out.push_str(&format!("{}{} {}.\n", pad, kw, cond_str)),
9595            }
9596        }
9597        Stmt::Fail { reason } => {
9598            out.push_str(&format!(
9599                "{}Fail with {}.\n",
9600                pad,
9601                decompile_expr(reason, interner)
9602            ));
9603        }
9604        Stmt::Add { value, collection } => {
9605            let val_str = decompile_expr(value, interner);
9606            let coll_str = decompile_expr(collection, interner);
9607            out.push_str(&format!("{}Add {} to {}.\n", pad, val_str, coll_str));
9608        }
9609        Stmt::Remove { value, collection } => {
9610            let val_str = decompile_expr(value, interner);
9611            let coll_str = decompile_expr(collection, interner);
9612            out.push_str(&format!("{}Remove {} from {}.\n", pad, val_str, coll_str));
9613        }
9614        Stmt::Zone { name, body, .. } => {
9615            let zone_name = interner.resolve(*name);
9616            out.push_str(&format!(
9617                "{}Inside a new zone called \"{}\":\n",
9618                pad, zone_name
9619            ));
9620            for s in body.iter() {
9621                decompile_stmt(s, interner, out, indent + 1);
9622            }
9623        }
9624        Stmt::ReadFrom { var, .. } => {
9625            let var_name = interner.resolve(*var);
9626            out.push_str(&format!("{}Read {} from the console.\n", pad, var_name));
9627        }
9628        Stmt::WriteFile { content, path } => {
9629            let content_str = decompile_expr(content, interner);
9630            let path_str = decompile_expr(path, interner);
9631            out.push_str(&format!(
9632                "{}Write {} to file {}.\n",
9633                pad, content_str, path_str
9634            ));
9635        }
9636        Stmt::Sleep { milliseconds } => {
9637            let ms = decompile_expr(milliseconds, interner);
9638            out.push_str(&format!("{}Sleep {}.\n", pad, ms));
9639        }
9640        // CRDT mutations: a Shared struct the program mutates survives the
9641        // projection unfolded (the optimizer keeps the binding dynamic), so the
9642        // residual MUST re-emit these or it silently changes the program's value.
9643        Stmt::IncreaseCrdt {
9644            object,
9645            field,
9646            amount,
9647        } => {
9648            let obj = decompile_expr(object, interner);
9649            let fld = interner.resolve(*field);
9650            let amt = decompile_expr(amount, interner);
9651            out.push_str(&format!("{}Increase {}'s {} by {}.\n", pad, obj, fld, amt));
9652        }
9653        Stmt::DecreaseCrdt {
9654            object,
9655            field,
9656            amount,
9657        } => {
9658            let obj = decompile_expr(object, interner);
9659            let fld = interner.resolve(*field);
9660            let amt = decompile_expr(amount, interner);
9661            out.push_str(&format!("{}Decrease {}'s {} by {}.\n", pad, obj, fld, amt));
9662        }
9663        Stmt::MergeCrdt { source, target } => {
9664            let src = decompile_expr(source, interner);
9665            let tgt = decompile_expr(target, interner);
9666            out.push_str(&format!("{}Merge {} into {}.\n", pad, src, tgt));
9667        }
9668        Stmt::JoinCrdt { source, target } => {
9669            let src = decompile_expr(source, interner);
9670            let tgt = decompile_expr(target, interner);
9671            out.push_str(&format!("{}Converge {} into {}.\n", pad, src, tgt));
9672        }
9673        Stmt::AppendToSequence { sequence, value } => {
9674            let seq = decompile_expr(sequence, interner);
9675            let val = decompile_expr(value, interner);
9676            out.push_str(&format!("{}Append {} to {}.\n", pad, val, seq));
9677        }
9678        Stmt::ResolveConflict {
9679            object,
9680            field,
9681            value,
9682        } => {
9683            let obj = decompile_expr(object, interner);
9684            let fld = interner.resolve(*field);
9685            let val = decompile_expr(value, interner);
9686            out.push_str(&format!("{}Resolve {}'s {} to {}.\n", pad, obj, fld, val));
9687        }
9688        _ => {
9689            // Remaining system-level statements (networking, concurrency) are not
9690            // produced by the optimizer and don't appear in P1 residuals.
9691        }
9692    }
9693}
9694
9695fn decompile_expr(expr: &Expr, interner: &Interner) -> String {
9696    match expr {
9697        Expr::Dom(q) => match q.selector() {
9698            Some(sel) => format!("the {} of {}", q.noun(), decompile_expr(sel, interner)),
9699            None => format!("the {}", q.noun()),
9700        },
9701        Expr::View(v) => decompile_view(v, interner),
9702        Expr::Literal(lit) => match lit {
9703            Literal::Number(n) => n.to_string(),
9704            Literal::Float(f) => format!("{}", f),
9705            Literal::Boolean(b) => {
9706                if *b {
9707                    "true".to_string()
9708                } else {
9709                    "false".to_string()
9710                }
9711            }
9712            Literal::Text(s) => format!("\"{}\"", interner.resolve(*s)),
9713            Literal::Nothing => "nothing".to_string(),
9714            Literal::Char(c) => format!("'{}'", c),
9715            Literal::Duration(ns) => format!("{}", ns),
9716            Literal::Date(days) => format!("{}", days),
9717            Literal::Moment(ns) => format!("{}", ns),
9718            Literal::Span { months, days } => format!("{} months {} days", months, days),
9719            Literal::Time(ns) => format!("{}", ns),
9720        },
9721        Expr::Identifier(sym) => interner.resolve(*sym).to_string(),
9722        Expr::BinaryOp { op, left, right } => {
9723            let l = if matches!(left, Expr::BinaryOp { .. }) {
9724                format!("({})", decompile_expr(left, interner))
9725            } else {
9726                decompile_expr(left, interner)
9727            };
9728            let r = if matches!(right, Expr::BinaryOp { .. }) {
9729                format!("({})", decompile_expr(right, interner))
9730            } else {
9731                decompile_expr(right, interner)
9732            };
9733            // Shift operations are introduced by bit-strength optimization.
9734            // Map back to equivalent multiply/divide for LOGOS source.
9735            if matches!(op, BinaryOpKind::Shl) {
9736                // n << k = n * 2^k
9737                if let Expr::Literal(Literal::Number(k)) = right {
9738                    let multiplier = 1i64 << k;
9739                    return format!("{} * {}", l, multiplier);
9740                }
9741            }
9742            if matches!(op, BinaryOpKind::Shr) {
9743                // n >> k = n / 2^k
9744                if let Expr::Literal(Literal::Number(k)) = right {
9745                    let divisor = 1i64 << k;
9746                    return format!("{} / {}", l, divisor);
9747                }
9748            }
9749            let op_str = match op {
9750                BinaryOpKind::Add => "+",
9751                BinaryOpKind::Subtract => "-",
9752                BinaryOpKind::Multiply => "*",
9753                BinaryOpKind::Divide | BinaryOpKind::ExactDivide => "/",
9754                BinaryOpKind::FloorDivide => "//",
9755                BinaryOpKind::Modulo => "%",
9756                BinaryOpKind::Eq => "equals",
9757                BinaryOpKind::NotEq => "is not",
9758                BinaryOpKind::Lt => "is less than",
9759                BinaryOpKind::Gt => "is greater than",
9760                BinaryOpKind::LtEq => "is at most",
9761                BinaryOpKind::GtEq => "is at least",
9762                BinaryOpKind::And => "and",
9763                BinaryOpKind::Or => "or",
9764                BinaryOpKind::Concat => "+",
9765                BinaryOpKind::SeqConcat => "followed by",
9766                BinaryOpKind::ApproxEq => "is approximately",
9767                BinaryOpKind::Pow => "**",
9768                BinaryOpKind::BitXor => "+",
9769                BinaryOpKind::BitAnd => "&",
9770                BinaryOpKind::BitOr => "|",
9771                BinaryOpKind::Shl => "*",
9772                BinaryOpKind::Shr => "/",
9773            };
9774            format!("{} {} {}", l, op_str, r)
9775        }
9776        Expr::Not { operand } => {
9777            // Parenthesize the operand so the negation's scope survives a
9778            // re-parse of the residual: `not (a and b)` must NOT become
9779            // `(not a) and b`.
9780            let inner = decompile_expr(operand, interner);
9781            format!("not ({})", inner)
9782        }
9783        Expr::Call { function, args } => {
9784            let fn_name = interner.resolve(*function);
9785            let arg_strs: Vec<String> = args.iter().map(|a| decompile_expr(a, interner)).collect();
9786            if arg_strs.is_empty() {
9787                format!("{}()", fn_name)
9788            } else {
9789                format!("{}({})", fn_name, arg_strs.join(", "))
9790            }
9791        }
9792        Expr::Index { collection, index } => {
9793            let coll = decompile_expr(collection, interner);
9794            let idx = decompile_expr(index, interner);
9795            format!("item {} of {}", idx, coll)
9796        }
9797        Expr::Length { collection } => {
9798            let coll = decompile_expr(collection, interner);
9799            format!("length of {}", coll)
9800        }
9801        Expr::FieldAccess { object, field } => {
9802            let obj = decompile_expr(object, interner);
9803            let field_name = interner.resolve(*field);
9804            // Possessive `obj's field` is the canonical, universally-parseable
9805            // field-read surface form (the parsers produce FieldAccess only from
9806            // it). `field of obj` does not round-trip (e.g. after `Show`/`Add`).
9807            format!("{}'s {}", obj, field_name)
9808        }
9809        Expr::New {
9810            type_name,
9811            type_args,
9812            init_fields,
9813        } => {
9814            let name = interner.resolve(*type_name);
9815            let mut out = format!("a new {name}");
9816            if !type_args.is_empty() {
9817                let args: Vec<String> = type_args
9818                    .iter()
9819                    .map(|t| decompile_type_expr(t, interner))
9820                    .collect();
9821                out.push_str(&format!(" of {}", args.join(generic_separator(name))));
9822            }
9823            if !init_fields.is_empty() {
9824                let fields: Vec<String> = init_fields
9825                    .iter()
9826                    .map(|(name, value)| {
9827                        format!("{} {}", interner.resolve(*name), decompile_expr(value, interner))
9828                    })
9829                    .collect();
9830                out.push_str(&format!(" with {}", fields.join(" and ")));
9831            }
9832            out
9833        }
9834        Expr::NewVariant {
9835            variant, fields, ..
9836        } => {
9837            let vn = interner.resolve(*variant);
9838            if fields.is_empty() {
9839                format!("a new {}", vn)
9840            } else {
9841                let parts: Vec<String> = fields
9842                    .iter()
9843                    .map(|(name, val)| {
9844                        let n = interner.resolve(*name);
9845                        let v = decompile_expr(val, interner);
9846                        format!("{} {}", n, v)
9847                    })
9848                    .collect();
9849                format!("a new {} with {}", vn, parts.join(" and "))
9850            }
9851        }
9852        Expr::InterpolatedString(parts) => {
9853            let mut result = String::new();
9854            for part in parts {
9855                match part {
9856                    StringPart::Literal(sym) => {
9857                        result.push_str(&interner.resolve(*sym));
9858                    }
9859                    StringPart::Expr { value, debug, .. } => {
9860                        let expr_str = decompile_expr(value, interner);
9861                        if *debug {
9862                            result.push_str(&format!("{{{}=}}", expr_str));
9863                        } else {
9864                            result.push_str(&format!("{{{}}}", expr_str));
9865                        }
9866                    }
9867                }
9868            }
9869            format!("\"{}\"", result)
9870        }
9871        Expr::Slice {
9872            collection,
9873            start,
9874            end,
9875        } => {
9876            let coll = decompile_expr(collection, interner);
9877            let s = decompile_expr(start, interner);
9878            let e = decompile_expr(end, interner);
9879            format!("{} {} through {}", coll, s, e)
9880        }
9881        Expr::Copy { expr } => {
9882            let inner = decompile_expr(expr, interner);
9883            format!("copy of {}", inner)
9884        }
9885        Expr::Give { value } => {
9886            let inner = decompile_expr(value, interner);
9887            format!("Give {}", inner)
9888        }
9889        Expr::Contains { collection, value } => {
9890            let coll = decompile_expr(collection, interner);
9891            let val = decompile_expr(value, interner);
9892            format!("{} contains {}", coll, val)
9893        }
9894        Expr::Union { left, right } => {
9895            let l = decompile_expr(left, interner);
9896            let r = decompile_expr(right, interner);
9897            format!("{} union {}", l, r)
9898        }
9899        Expr::Intersection { left, right } => {
9900            let l = decompile_expr(left, interner);
9901            let r = decompile_expr(right, interner);
9902            format!("{} intersection {}", l, r)
9903        }
9904        Expr::List(elems) => {
9905            let parts: Vec<String> = elems.iter().map(|e| decompile_expr(e, interner)).collect();
9906            format!("[{}]", parts.join(", "))
9907        }
9908        Expr::Tuple(elems) => {
9909            let parts: Vec<String> = elems.iter().map(|e| decompile_expr(e, interner)).collect();
9910            format!("({})", parts.join(", "))
9911        }
9912        Expr::Range { start, end } => {
9913            let s = decompile_expr(start, interner);
9914            let e = decompile_expr(end, interner);
9915            format!("{} to {}", s, e)
9916        }
9917        Expr::OptionSome { value } => {
9918            let inner = decompile_expr(value, interner);
9919            format!("some {}", inner)
9920        }
9921        Expr::OptionNone => "none".to_string(),
9922        Expr::WithCapacity { value, capacity } => {
9923            let val = decompile_expr(value, interner);
9924            let cap = decompile_expr(capacity, interner);
9925            format!("{} with capacity {}", val, cap)
9926        }
9927        Expr::Escape { language, code } => {
9928            let lang = interner.resolve(*language);
9929            let src = interner.resolve(*code);
9930            format!("Escape to {}:\n{}", lang, src)
9931        }
9932        Expr::ManifestOf { zone } => {
9933            let z = decompile_expr(zone, interner);
9934            format!("the manifest of {}", z)
9935        }
9936        Expr::ChunkAt { index, zone } => {
9937            let idx = decompile_expr(index, interner);
9938            let z = decompile_expr(zone, interner);
9939            format!("the chunk at {} in {}", idx, z)
9940        }
9941        Expr::Closure {
9942            params,
9943            body,
9944            return_type,
9945        } => {
9946            let param_strs: Vec<String> = params
9947                .iter()
9948                .map(|(name, ty)| {
9949                    let n = interner.resolve(*name);
9950                    let t = decompile_type_expr(ty, interner);
9951                    format!("{}: {}", n, t)
9952                })
9953                .collect();
9954            let ret = if let Some(rt) = return_type {
9955                format!(" -> {}", decompile_type_expr(rt, interner))
9956            } else {
9957                String::new()
9958            };
9959            match body {
9960                ClosureBody::Expression(expr) => {
9961                    let e = decompile_expr(expr, interner);
9962                    format!("({}){} -> {}", param_strs.join(", "), ret, e)
9963                }
9964                ClosureBody::Block(_) => {
9965                    format!("({}){} -> [block]", param_strs.join(", "), ret)
9966                }
9967            }
9968        }
9969        Expr::CallExpr { callee, args } => {
9970            let c = decompile_expr(callee, interner);
9971            let arg_strs: Vec<String> = args.iter().map(|a| decompile_expr(a, interner)).collect();
9972            format!("{}({})", c, arg_strs.join(", "))
9973        }
9974    }
9975}
9976
9977/// What separates a generic type's parameters as the language writes them: a map's key `to` its
9978/// value (`Map of Text to Int`), any other pair `and` (`Result of Int and Text`).
9979fn generic_separator(base: &str) -> &'static str {
9980    match base {
9981        "Map" | "HashMap" | "SharedMap" | "ORMap" => " to ",
9982        _ => " and ",
9983    }
9984}
9985
9986fn decompile_type_expr(ty: &TypeExpr, interner: &Interner) -> String {
9987    match ty {
9988        TypeExpr::Primitive(sym) => interner.resolve(*sym).to_string(),
9989        TypeExpr::Named(sym) => interner.resolve(*sym).to_string(),
9990        TypeExpr::Generic { base, params } => {
9991            let base_str = interner.resolve(*base);
9992            let param_strs: Vec<String> = params
9993                .iter()
9994                .map(|p| decompile_type_expr(p, interner))
9995                .collect();
9996            format!("{} of {}", base_str, param_strs.join(generic_separator(base_str)))
9997        }
9998        TypeExpr::Tuple(params) => {
9999            let elems: Vec<String> = params
10000                .iter()
10001                .map(|p| decompile_type_expr(p, interner))
10002                .collect();
10003            format!("({})", elems.join(", "))
10004        }
10005        TypeExpr::Record {
10006            field_names,
10007            field_types,
10008        } => {
10009            let elems: Vec<String> = field_names
10010                .iter()
10011                .zip(field_types.iter())
10012                .map(|(n, t)| {
10013                    format!(
10014                        "{}: {}",
10015                        interner.resolve(*n),
10016                        decompile_type_expr(t, interner)
10017                    )
10018                })
10019                .collect();
10020            format!("({})", elems.join(", "))
10021        }
10022        TypeExpr::Function { inputs, output } => {
10023            let in_strs: Vec<String> = inputs
10024                .iter()
10025                .map(|t| decompile_type_expr(t, interner))
10026                .collect();
10027            let out_str = decompile_type_expr(output, interner);
10028            format!("fn({}) -> {}", in_strs.join(", "), out_str)
10029        }
10030        TypeExpr::Refinement { base, .. } => decompile_type_expr(base, interner),
10031        TypeExpr::Persistent { inner } => {
10032            format!("Persistent {}", decompile_type_expr(inner, interner))
10033        }
10034        TypeExpr::Mutable { inner } => {
10035            format!("mutable {}", decompile_type_expr(inner, interner))
10036        }
10037    }
10038}
10039
10040/// Verify that a LOGOS program has no interpretive overhead.
10041///
10042/// Checks the AST for patterns that indicate unresolved interpreter dispatch:
10043/// - Inspect on CStmt/CExpr/CVal variants
10044/// - References to Core constructor types (CInt, CShow, etc.)
10045/// - Environment lookups on literal strings
10046pub fn verify_no_overhead_source(source: &str) -> Result<(), String> {
10047    let mut interner = Interner::new();
10048    let mut lexer = Lexer::new(source, &mut interner);
10049    let tokens = lexer.tokenize();
10050
10051    let type_registry = {
10052        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
10053        let result = discovery.run_full();
10054        result.types
10055    };
10056
10057    let mut world_state = WorldState::new();
10058    let expr_arena = Arena::new();
10059    let term_arena = Arena::new();
10060    let np_arena = Arena::new();
10061    let sym_arena = Arena::new();
10062    let role_arena = Arena::new();
10063    let pp_arena = Arena::new();
10064    let stmt_arena: Arena<Stmt> = Arena::new();
10065    let _compile_facts = crate::optimize::facts::scope();
10066    let imperative_expr_arena: Arena<Expr> = Arena::new();
10067    let type_expr_arena: Arena<TypeExpr> = Arena::new();
10068
10069    let ast_ctx = AstContext::with_types(
10070        &expr_arena,
10071        &term_arena,
10072        &np_arena,
10073        &sym_arena,
10074        &role_arena,
10075        &pp_arena,
10076        &stmt_arena,
10077        &imperative_expr_arena,
10078        &type_expr_arena,
10079    );
10080
10081    let mut parser = crate::parser::Parser::new(
10082        tokens,
10083        &mut world_state,
10084        &mut interner,
10085        ast_ctx,
10086        type_registry,
10087    );
10088    let stmts = parser
10089        .parse_program()
10090        .map_err(|e| format!("Parse error: {}", describe_parse_error(&e)))?;
10091
10092    verify_no_overhead_stmts(&stmts, &interner)
10093}
10094
10095const CORE_VARIANT_NAMES: &[&str] = &[
10096    "CInt",
10097    "CBool",
10098    "CText",
10099    "CVar",
10100    "CBinOp",
10101    "CNot",
10102    "CCall",
10103    "CIndex",
10104    "CLen",
10105    "CMapGet",
10106    "CLet",
10107    "CSet",
10108    "CIf",
10109    "CWhile",
10110    "CReturn",
10111    "CShow",
10112    "CCallS",
10113    "CPush",
10114    "CSetIdx",
10115    "CMapSet",
10116    "CFuncDef",
10117    "CProg",
10118    "CManifestOf",
10119    "CChunkAt",
10120    "VInt",
10121    "VBool",
10122    "VText",
10123    "VSeq",
10124    "VMap",
10125    "VError",
10126    "VNothing",
10127];
10128
10129/// Interpreter *carrier* type names — the umbrella data types the self-interpreter/PE thread
10130/// through their state. A Jones-optimal residual holds none of them: constructing
10131/// `a new Map of Text to CVal` (the environment), or binding a `CExpr`-typed variable, is
10132/// surviving interpreter state, not dissolved computation.
10133const CORE_TYPE_NAMES: &[&str] = &[
10134    "CVal",
10135    "CExpr",
10136    "CStmt",
10137    "CFunc",
10138    "CFuncDef",
10139    "CProgram",
10140    "CProg",
10141    "CoreOut",
10142    "CoreOutR",
10143    "PEState",
10144    "PEStateR",
10145    "PEMiniState",
10146    "PEMiniR",
10147];
10148
10149fn verify_no_overhead_stmts(stmts: &[Stmt], interner: &Interner) -> Result<(), String> {
10150    for stmt in stmts {
10151        check_stmt_overhead(stmt, interner)?;
10152    }
10153    Ok(())
10154}
10155
10156fn check_stmt_overhead(stmt: &Stmt, interner: &Interner) -> Result<(), String> {
10157    match stmt {
10158        Stmt::Inspect { arms, .. } => {
10159            for arm in arms {
10160                if let Some(variant) = arm.variant {
10161                    let variant_name = interner.resolve(variant);
10162                    if CORE_VARIANT_NAMES.contains(&variant_name) {
10163                        return Err(format!(
10164                            "Interpretive overhead: Inspect dispatches on Core variant '{}'",
10165                            variant_name
10166                        ));
10167                    }
10168                }
10169                for s in arm.body.iter() {
10170                    check_stmt_overhead(s, interner)?;
10171                }
10172            }
10173        }
10174        Stmt::If {
10175            cond,
10176            then_block,
10177            else_block,
10178        } => {
10179            check_expr_overhead(cond, interner)?;
10180            for s in then_block.iter() {
10181                check_stmt_overhead(s, interner)?;
10182            }
10183            if let Some(els) = else_block {
10184                for s in els.iter() {
10185                    check_stmt_overhead(s, interner)?;
10186                }
10187            }
10188        }
10189        Stmt::While { cond, body, .. } => {
10190            check_expr_overhead(cond, interner)?;
10191            for s in body.iter() {
10192                check_stmt_overhead(s, interner)?;
10193            }
10194        }
10195        Stmt::FunctionDef { body, .. } => {
10196            for s in body.iter() {
10197                check_stmt_overhead(s, interner)?;
10198            }
10199        }
10200        Stmt::Repeat { body, .. } => {
10201            for s in body.iter() {
10202                check_stmt_overhead(s, interner)?;
10203            }
10204        }
10205        Stmt::Let { value, .. } | Stmt::Set { value, .. } | Stmt::Show { object: value, .. } => {
10206            check_expr_overhead(value, interner)?;
10207        }
10208        Stmt::Return { value } => {
10209            if let Some(v) = value {
10210                check_expr_overhead(v, interner)?;
10211            }
10212        }
10213        _ => {}
10214    }
10215    Ok(())
10216}
10217
10218fn check_expr_overhead(expr: &Expr, interner: &Interner) -> Result<(), String> {
10219    match expr {
10220        Expr::Index { collection, index } => {
10221            // Check for `item X of env` where X is a literal string (env lookup overhead)
10222            if let Expr::Identifier(coll_sym) = collection {
10223                let coll_name = interner.resolve(*coll_sym);
10224                if coll_name == "env" {
10225                    if let Expr::Literal(Literal::Text(_)) = index {
10226                        return Err(
10227                            "Interpretive overhead: environment lookup 'item ... of env' on literal key".to_string()
10228                        );
10229                    }
10230                }
10231            }
10232            check_expr_overhead(collection, interner)?;
10233            check_expr_overhead(index, interner)?;
10234        }
10235        Expr::New { type_name, .. } => {
10236            let tn = interner.resolve(*type_name);
10237            if CORE_VARIANT_NAMES.contains(&tn) {
10238                return Err(format!(
10239                    "Interpretive overhead: Core type constructor 'new {}'",
10240                    tn
10241                ));
10242            }
10243        }
10244        Expr::NewVariant { variant, .. } => {
10245            let vn = interner.resolve(*variant);
10246            if CORE_VARIANT_NAMES.contains(&vn) {
10247                return Err(format!(
10248                    "Interpretive overhead: Core variant constructor '{}'",
10249                    vn
10250                ));
10251            }
10252        }
10253        Expr::Call { function, args } => {
10254            let fn_name = interner.resolve(*function);
10255            if CORE_VARIANT_NAMES.contains(&fn_name) {
10256                return Err(format!(
10257                    "Interpretive overhead: Core variant call '{}'",
10258                    fn_name
10259                ));
10260            }
10261            for a in args {
10262                check_expr_overhead(a, interner)?;
10263            }
10264        }
10265        Expr::BinaryOp { left, right, .. } => {
10266            check_expr_overhead(left, interner)?;
10267            check_expr_overhead(right, interner)?;
10268        }
10269        Expr::Not { operand } => {
10270            check_expr_overhead(operand, interner)?;
10271        }
10272        Expr::Length { collection } => {
10273            check_expr_overhead(collection, interner)?;
10274        }
10275        Expr::FieldAccess { object, .. } => {
10276            check_expr_overhead(object, interner)?;
10277        }
10278        _ => {}
10279    }
10280    Ok(())
10281}
10282
10283/// Names whose appearance as a call function in a residual betrays surviving
10284/// interpreter dispatch — the residual is still threading through the PE or the
10285/// self-interpreter instead of having been specialized away.
10286const DISPATCH_FN_NAMES: &[&str] = &[
10287    "peExpr",
10288    "peBlock",
10289    "coreEval",
10290    "coreExecBlock",
10291    "applyBinOp",
10292];
10293
10294/// The Jones-optimality oracle: count the units of interpreter dispatch remaining
10295/// in a residual program.
10296///
10297/// A residual that is genuinely Jones-optimal has dissolved the interpreter entirely
10298/// and returns zero. One unit is counted for each of:
10299/// - an `Inspect` arm dispatching on a Core IR variant (`CInt`, `CIf`, …);
10300/// - an environment/function-map lookup `item <literal> of env` / `... of funcs`;
10301/// - a Core IR constructor (`new CInt`, a `CInt(...)` call, a `VInt` variant, …);
10302/// - a call to a known dispatch function (`DISPATCH_FN_NAMES`).
10303///
10304/// Unlike [`verify_no_overhead_source`], this walks the whole tree and accumulates a
10305/// count rather than short-circuiting on the first violation.
10306pub fn count_dispatch(source: &str) -> usize {
10307    let mut interner = Interner::new();
10308    let mut lexer = Lexer::new(source, &mut interner);
10309    let tokens = lexer.tokenize();
10310
10311    let type_registry = {
10312        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
10313        let result = discovery.run_full();
10314        result.types
10315    };
10316
10317    let mut world_state = WorldState::new();
10318    let expr_arena = Arena::new();
10319    let term_arena = Arena::new();
10320    let np_arena = Arena::new();
10321    let sym_arena = Arena::new();
10322    let role_arena = Arena::new();
10323    let pp_arena = Arena::new();
10324    let stmt_arena: Arena<Stmt> = Arena::new();
10325    let _compile_facts = crate::optimize::facts::scope();
10326    let imperative_expr_arena: Arena<Expr> = Arena::new();
10327    let type_expr_arena: Arena<TypeExpr> = Arena::new();
10328
10329    let ast_ctx = AstContext::with_types(
10330        &expr_arena,
10331        &term_arena,
10332        &np_arena,
10333        &sym_arena,
10334        &role_arena,
10335        &pp_arena,
10336        &stmt_arena,
10337        &imperative_expr_arena,
10338        &type_expr_arena,
10339    );
10340
10341    let mut parser = crate::parser::Parser::new(
10342        tokens,
10343        &mut world_state,
10344        &mut interner,
10345        ast_ctx,
10346        type_registry,
10347    );
10348    let stmts = match parser.parse_program() {
10349        Ok(s) => s,
10350        // A residual we cannot parse cannot be asserted Jones-optimal; surface that as
10351        // a non-zero count rather than a false clean bill of health.
10352        Err(_) => return usize::MAX,
10353    };
10354
10355    let mut count = 0usize;
10356    for stmt in &stmts {
10357        count_stmt_dispatch(stmt, &interner, &mut count);
10358    }
10359    count
10360}
10361
10362fn count_block_dispatch(block: &[Stmt], interner: &Interner, count: &mut usize) {
10363    for s in block {
10364        count_stmt_dispatch(s, interner, count);
10365    }
10366}
10367
10368/// Does a type expression name any interpreter carrier type ([`CORE_TYPE_NAMES`]) or Core
10369/// variant? Exhaustive over `TypeExpr` — a new type form stops the build until handled.
10370/// `(a: T) and (b: U)` for a parameter list, or the empty string.
10371fn decompile_params(
10372    params: &[(logicaffeine_base::Symbol, &TypeExpr)],
10373    interner: &Interner,
10374) -> String {
10375    params
10376        .iter()
10377        .map(|(n, t)| {
10378            format!(
10379                "({}: {})",
10380                interner.resolve(*n),
10381                decompile_type_expr(t, interner)
10382            )
10383        })
10384        .collect::<Vec<_>>()
10385        .join(" and ")
10386}
10387
10388/// The source spelling of a type expression (the common shapes; anything else prints its
10389/// debug form so a decompile never silently drops a type).
10390/// A component, page, store or error page back to its LGX source: header, `Use`, and the
10391/// `State:` / `Actions:` / `View:` / `Style:` sections it carries.
10392fn decompile_component(
10393    def: &logicaffeine_language::ast::component::ComponentDef,
10394    interner: &Interner,
10395    out: &mut String,
10396) {
10397    use logicaffeine_language::ast::component::{ComponentKind, StoreMode, Trigger};
10398    let props = decompile_params(&def.props, interner);
10399    match &def.kind {
10400        ComponentKind::Component => out.push_str(&format!(
10401            "## Component {}{}\n",
10402            interner.resolve(def.name),
10403            if props.is_empty() {
10404                String::new()
10405            } else {
10406                format!(" {props}")
10407            }
10408        )),
10409        ComponentKind::Page { path, params } => {
10410            let ps = decompile_params(params, interner);
10411            out.push_str(&format!(
10412                "## Page {}{}\n",
10413                interner.resolve(*path),
10414                if ps.is_empty() {
10415                    String::new()
10416                } else {
10417                    format!(" {ps}")
10418                }
10419            ));
10420        }
10421        ComponentKind::Store { mode } => {
10422            let tail = match mode {
10423                StoreMode::Local => String::new(),
10424                StoreMode::Persisted { key } => {
10425                    format!(" persisted as {}", decompile_expr(key, interner))
10426                }
10427                StoreMode::Shared { topic } => {
10428                    format!(" shared on {}", decompile_expr(topic, interner))
10429                }
10430                StoreMode::Preserved => " preserved across reloads".to_string(),
10431            };
10432            out.push_str(&format!(
10433                "## Store {}{}\n",
10434                interner.resolve(def.name),
10435                tail
10436            ));
10437        }
10438        ComponentKind::ErrorPage { status } => out.push_str(&format!("## Error page {status}\n")),
10439    }
10440    for u in &def.uses {
10441        out.push_str(&format!("Use {}.\n", interner.resolve(*u)));
10442    }
10443    if !def.state.is_empty() {
10444        out.push_str("State:\n");
10445        for f in &def.state {
10446            let ty =
10447                f.ty.map(|t| format!(": {}", decompile_type_expr(t, interner)))
10448                    .unwrap_or_default();
10449            let verb = if f.derived { "always be" } else { "be" };
10450            out.push_str(&format!(
10451                "    Let {}{} {} {}.\n",
10452                interner.resolve(f.name),
10453                ty,
10454                verb,
10455                decompile_expr(f.init, interner)
10456            ));
10457        }
10458    }
10459    if !def.events.is_empty() || !def.actions.is_empty() {
10460        out.push_str("Actions:\n");
10461        for ev in &def.events {
10462            let head = match &ev.trigger {
10463                Trigger::PageLoads => "When the page loads".to_string(),
10464                Trigger::Appears => "When this component appears".to_string(),
10465                Trigger::Disappears => "When this component disappears".to_string(),
10466                Trigger::RouteChanges => "When the route changes".to_string(),
10467                Trigger::Online => "When the app comes back online".to_string(),
10468                Trigger::Offline => "When the app goes offline".to_string(),
10469                Trigger::Selector {
10470                    selector,
10471                    event,
10472                    key: None,
10473                } => format!(
10474                    "When {} is {}",
10475                    decompile_expr(selector, interner),
10476                    interner.resolve(*event)
10477                ),
10478                Trigger::Selector {
10479                    selector,
10480                    event: _,
10481                    key: Some(k),
10482                } => format!(
10483                    "When the user presses {} in {}",
10484                    interner.resolve(*k),
10485                    decompile_expr(selector, interner)
10486                ),
10487                Trigger::Key { key } => format!("When the user presses {}", interner.resolve(*key)),
10488                Trigger::FieldChanges { store: None, field } => {
10489                    format!("When {} changes", interner.resolve(*field))
10490                }
10491                Trigger::FieldChanges {
10492                    store: Some(st),
10493                    field,
10494                } => format!(
10495                    "When {}'s {} changes",
10496                    interner.resolve(*st),
10497                    interner.resolve(*field)
10498                ),
10499                Trigger::Every {
10500                    seconds,
10501                    name: None,
10502                } => format!("Every {} seconds", decompile_expr(seconds, interner)),
10503                Trigger::Every {
10504                    seconds,
10505                    name: Some(n),
10506                } => format!(
10507                    "Every {} seconds as {}",
10508                    decompile_expr(seconds, interner),
10509                    interner.resolve(*n)
10510                ),
10511                Trigger::After {
10512                    seconds,
10513                    name: None,
10514                } => format!("After {} seconds", decompile_expr(seconds, interner)),
10515                Trigger::After {
10516                    seconds,
10517                    name: Some(n),
10518                } => format!(
10519                    "After {} seconds as {}",
10520                    decompile_expr(seconds, interner),
10521                    interner.resolve(*n)
10522                ),
10523                Trigger::Message { topic, param } => format!(
10524                    "When a message arrives on {} ({}: {})",
10525                    decompile_expr(topic, interner),
10526                    interner.resolve(param.0),
10527                    decompile_type_expr(param.1, interner)
10528                ),
10529                Trigger::ActionFails { param } => {
10530                    format!("When an action fails ({}: Text)", interner.resolve(*param))
10531                }
10532                Trigger::FetchFails { url, error } => format!(
10533                    "When a fetch fails ({}: Text) and ({}: Text)",
10534                    interner.resolve(*url),
10535                    interner.resolve(*error)
10536                ),
10537                Trigger::WindowResizes => "When the window resizes".to_string(),
10538                Trigger::ScrollsToBottom { selector: None } => {
10539                    "When the user scrolls to the bottom".to_string()
10540                }
10541                Trigger::ScrollsToBottom {
10542                    selector: Some(sel),
10543                } => format!(
10544                    "When the user scrolls to the bottom of {}",
10545                    decompile_expr(sel, interner)
10546                ),
10547                Trigger::FileDropped { selector, param } => format!(
10548                    "When a file is dropped on {} ({}: {})",
10549                    decompile_expr(selector, interner),
10550                    interner.resolve(param.0),
10551                    decompile_type_expr(param.1, interner)
10552                ),
10553            };
10554            out.push_str(&format!("    {head}:\n"));
10555            for inner in ev.body.iter() {
10556                decompile_stmt(inner, interner, out, 2);
10557            }
10558        }
10559        for a in &def.actions {
10560            let ps = decompile_params(&a.params, interner);
10561            out.push_str(&format!(
10562                "    To {}{}:\n",
10563                interner.resolve(a.name),
10564                if ps.is_empty() {
10565                    String::new()
10566                } else {
10567                    format!(" {ps}")
10568                }
10569            ));
10570            for inner in a.body.iter() {
10571                decompile_stmt(inner, interner, out, 2);
10572            }
10573        }
10574    }
10575    if let Some(view) = &def.view {
10576        out.push_str("View:\n");
10577        for line in decompile_view(view, interner).lines() {
10578            out.push_str(&format!("    {line}\n"));
10579        }
10580    }
10581    if let Some(style) = &def.style {
10582        out.push_str("Style:\n");
10583        for line in interner.resolve(style.css).lines() {
10584            out.push_str(&format!("    {line}\n"));
10585        }
10586    }
10587}
10588
10589/// A view tree back to LGX template source (holes through `decompile_expr`).
10590fn decompile_view(view: &logicaffeine_language::ast::view::ViewDef, interner: &Interner) -> String {
10591    use logicaffeine_language::ast::view::{Attr, ViewNode};
10592    fn esc(s: &str, out: &mut String) {
10593        for c in s.chars() {
10594            match c {
10595                '&' => out.push_str("&amp;"),
10596                '<' => out.push_str("&lt;"),
10597                '>' => out.push_str("&gt;"),
10598                '{' => out.push_str("&#123;"),
10599                '}' => out.push_str("&#125;"),
10600                _ => out.push(c),
10601            }
10602        }
10603    }
10604    fn go(nodes: &[ViewNode], interner: &Interner, out: &mut String) {
10605        for n in nodes {
10606            match n {
10607                ViewNode::Element {
10608                    tag,
10609                    attrs,
10610                    children,
10611                    ..
10612                } => {
10613                    out.push('<');
10614                    out.push_str(interner.resolve(*tag));
10615                    for a in attrs {
10616                        match a {
10617                            Attr::Plain { name, value } => {
10618                                out.push(' ');
10619                                out.push_str(interner.resolve(*name));
10620                                out.push_str("={");
10621                                out.push_str(&decompile_expr(value, interner));
10622                                out.push('}');
10623                            }
10624                            Attr::Bind { field } => {
10625                                out.push_str(" bind={");
10626                                out.push_str(interner.resolve(*field));
10627                                out.push('}');
10628                            }
10629                            Attr::Class { name, cond } => {
10630                                out.push_str(&format!(
10631                                    " class:{}={{{}}}",
10632                                    interner.resolve(*name),
10633                                    decompile_expr(cond, interner)
10634                                ));
10635                            }
10636                            Attr::Directive { name, value } => {
10637                                out.push_str(&format!(
10638                                    " {}={{{}}}",
10639                                    interner.resolve(*name),
10640                                    decompile_expr(value, interner)
10641                                ));
10642                            }
10643                        }
10644                    }
10645                    out.push('>');
10646                    if logicaffeine_language::lgx::html::is_void(interner.resolve(*tag)) {
10647                        continue;
10648                    }
10649                    go(children, interner, out);
10650                    out.push_str("</");
10651                    out.push_str(interner.resolve(*tag));
10652                    out.push('>');
10653                }
10654                ViewNode::Text { text, .. } => {
10655                    out.push('{');
10656                    out.push_str(&decompile_expr(text, interner));
10657                    out.push('}');
10658                }
10659                ViewNode::Component {
10660                    name,
10661                    props,
10662                    children,
10663                    ..
10664                } => {
10665                    out.push('<');
10666                    out.push_str(interner.resolve(*name));
10667                    for (k, v) in props {
10668                        out.push(' ');
10669                        out.push_str(interner.resolve(*k));
10670                        out.push_str("={");
10671                        out.push_str(&decompile_expr(v, interner));
10672                        out.push('}');
10673                    }
10674                    if children.is_empty() {
10675                        out.push_str("/>");
10676                    } else {
10677                        out.push('>');
10678                        go(children, interner, out);
10679                        out.push_str("</");
10680                        out.push_str(interner.resolve(*name));
10681                        out.push('>');
10682                    }
10683                }
10684                ViewNode::Each {
10685                    pattern,
10686                    iterable,
10687                    key,
10688                    index,
10689                    body,
10690                    empty,
10691                    ..
10692                } => {
10693                    let pat = match pattern {
10694                        logicaffeine_language::ast::stmt::Pattern::Identifier(s) => {
10695                            interner.resolve(*s).to_string()
10696                        }
10697                        logicaffeine_language::ast::stmt::Pattern::Tuple(items) => format!(
10698                            "({})",
10699                            items
10700                                .iter()
10701                                .map(|s| interner.resolve(*s))
10702                                .collect::<Vec<_>>()
10703                                .join(", ")
10704                        ),
10705                    };
10706                    out.push_str(&format!(
10707                        "{{for each {pat} in {}",
10708                        decompile_expr(iterable, interner)
10709                    ));
10710                    if let Some(k) = key {
10711                        out.push_str(&format!(", keyed by {}", decompile_expr(k, interner)));
10712                    }
10713                    if let Some(i) = index {
10714                        out.push_str(&format!(", at index {}", interner.resolve(*i)));
10715                    }
10716                    out.push_str(":}");
10717                    go(body, interner, out);
10718                    if !empty.is_empty() {
10719                        out.push_str("{else:}");
10720                        go(empty, interner, out);
10721                    }
10722                    out.push_str("{end}");
10723                }
10724                ViewNode::If {
10725                    arms, otherwise, ..
10726                } => {
10727                    for (i, (c, b)) in arms.iter().enumerate() {
10728                        out.push_str(if i == 0 { "{if " } else { "{else if " });
10729                        out.push_str(&decompile_expr(c, interner));
10730                        out.push_str(":}");
10731                        go(b, interner, out);
10732                    }
10733                    if let Some(o) = otherwise {
10734                        out.push_str("{else:}");
10735                        go(o, interner, out);
10736                    }
10737                    out.push_str("{end}");
10738                }
10739                ViewNode::Handler {
10740                    event,
10741                    modifiers,
10742                    body,
10743                    ..
10744                } => {
10745                    let _ = modifiers;
10746                    // Legacy positional handler (the indentation DSL): its statements have no
10747                    // attribute form; render the intent as a template comment.
10748                    out.push_str(&format!(
10749                        "{{# on {}: {} statement(s) #}}",
10750                        interner.resolve(*event),
10751                        body.len()
10752                    ));
10753                }
10754                ViewNode::Raw { html, .. } => {
10755                    out.push_str("{raw ");
10756                    out.push_str(&decompile_expr(html, interner));
10757                    out.push('}');
10758                }
10759                ViewNode::Inspect {
10760                    scrutinee, arms, ..
10761                } => {
10762                    out.push_str(&format!(
10763                        "{{inspect {}:}}",
10764                        decompile_expr(scrutinee, interner)
10765                    ));
10766                    for arm in arms {
10767                        let head = match arm.variant {
10768                            None => "Otherwise".to_string(),
10769                            Some(v) => {
10770                                let bs: Vec<&str> = arm
10771                                    .bindings
10772                                    .iter()
10773                                    .map(|(_, b)| interner.resolve(*b))
10774                                    .collect();
10775                                if bs.is_empty() {
10776                                    interner.resolve(v).to_string()
10777                                } else {
10778                                    format!("{} ({})", interner.resolve(v), bs.join(", "))
10779                                }
10780                            }
10781                        };
10782                        out.push_str(&format!("{{when {head}:}}"));
10783                        go(&arm.body, interner, out);
10784                    }
10785                    out.push_str("{end}");
10786                }
10787                ViewNode::Let { var, value, .. } => {
10788                    out.push_str(&format!(
10789                        "{{let {} be {}}}",
10790                        interner.resolve(*var),
10791                        decompile_expr(value, interner)
10792                    ));
10793                }
10794                ViewNode::Extends { layout, .. } => {
10795                    out.push_str(&format!("{{extends {}}}", interner.resolve(*layout)));
10796                }
10797                ViewNode::Block { name, default, .. } => match default {
10798                    None => out.push_str(&format!("{{block {}}}", interner.resolve(*name))),
10799                    Some(d) => {
10800                        out.push_str(&format!("{{block {}:}}", interner.resolve(*name)));
10801                        go(d, interner, out);
10802                        out.push_str("{end}");
10803                    }
10804                },
10805                ViewNode::Children { .. } => out.push_str("{children}"),
10806            }
10807        }
10808    }
10809    let mut out = String::new();
10810    go(&view.nodes, interner, &mut out);
10811    out
10812}
10813
10814fn type_expr_mentions_core(t: &TypeExpr, interner: &Interner) -> bool {
10815    let is_core = |s| {
10816        let n = interner.resolve(s);
10817        CORE_TYPE_NAMES.contains(&n) || CORE_VARIANT_NAMES.contains(&n)
10818    };
10819    match t {
10820        TypeExpr::Primitive(s) | TypeExpr::Named(s) => is_core(*s),
10821        TypeExpr::Generic { base, params } => {
10822            is_core(*base) || params.iter().any(|p| type_expr_mentions_core(p, interner))
10823        }
10824        TypeExpr::Tuple(params) => params.iter().any(|p| type_expr_mentions_core(p, interner)),
10825        TypeExpr::Record { field_types, .. } => field_types
10826            .iter()
10827            .any(|p| type_expr_mentions_core(p, interner)),
10828        TypeExpr::Function { inputs, output } => {
10829            inputs.iter().any(|p| type_expr_mentions_core(p, interner))
10830                || type_expr_mentions_core(output, interner)
10831        }
10832        TypeExpr::Refinement { base, .. } => type_expr_mentions_core(base, interner),
10833        TypeExpr::Persistent { inner } | TypeExpr::Mutable { inner } => {
10834            type_expr_mentions_core(inner, interner)
10835        }
10836    }
10837}
10838
10839/// Scan raw escaped foreign code for whole-word Core-IR / dispatch names. An `Escape`
10840/// block embedding `CInt(..)` or `coreEval(..)` is interpreter overhead the AST walk
10841/// cannot see inside, so it is flagged lexically.
10842fn count_escape_code_dispatch(text: &str, count: &mut usize) {
10843    for word in text.split(|c: char| !c.is_alphanumeric() && c != '_') {
10844        if !word.is_empty()
10845            && (CORE_VARIANT_NAMES.contains(&word) || DISPATCH_FN_NAMES.contains(&word))
10846        {
10847            *count += 1;
10848        }
10849    }
10850}
10851
10852/// Exhaustive by construction — NO `_` arm. A new `Stmt` variant stops the build here
10853/// until it is classified, so the language cannot grow a statement that hides interpreter
10854/// dispatch from the Jones oracle.
10855fn count_stmt_dispatch(stmt: &Stmt, interner: &Interner, count: &mut usize) {
10856    match stmt {
10857        Stmt::ComponentDef(def) => {
10858            for f in &def.state {
10859                count_expr_dispatch(f.init, interner, count);
10860            }
10861            for ev in &def.events {
10862                for inner in ev.body.iter() {
10863                    count_stmt_dispatch(inner, interner, count);
10864                }
10865            }
10866            for a in &def.actions {
10867                for inner in a.body.iter() {
10868                    count_stmt_dispatch(inner, interner, count);
10869                }
10870            }
10871            if let Some(view) = &def.view {
10872                let (view_exprs, view_blocks) = view.exprs_and_blocks();
10873                for e in view_exprs {
10874                    count_expr_dispatch(e, interner, count);
10875                }
10876                for b in view_blocks {
10877                    for inner in b.iter() {
10878                        count_stmt_dispatch(inner, interner, count);
10879                    }
10880                }
10881            }
10882        }
10883        Stmt::DirectiveDef { body, removed, .. } => {
10884            for inner in body.iter() {
10885                count_stmt_dispatch(inner, interner, count);
10886            }
10887            if let Some(r) = removed {
10888                for inner in r.iter() {
10889                    count_stmt_dispatch(inner, interner, count);
10890                }
10891            }
10892        }
10893        Stmt::RouteDef { body, .. } => match &**body {
10894            logicaffeine_language::ast::component::RouteBody::Statements(b) => {
10895                for inner in b.iter() {
10896                    count_stmt_dispatch(inner, interner, count);
10897                }
10898            }
10899            logicaffeine_language::ast::component::RouteBody::View(view) => {
10900                let (view_exprs, view_blocks) = view.exprs_and_blocks();
10901                for e in view_exprs {
10902                    count_expr_dispatch(e, interner, count);
10903                }
10904                for b in view_blocks {
10905                    for inner in b.iter() {
10906                        count_stmt_dispatch(inner, interner, count);
10907                    }
10908                }
10909            }
10910        },
10911        Stmt::MiddlewareDef { body, .. } => {
10912            for inner in body.iter() {
10913                count_stmt_dispatch(inner, interner, count);
10914            }
10915        }
10916        Stmt::RedirectDef { .. } => {}
10917        Stmt::ServeFetches | Stmt::Replay { .. } => {}
10918        Stmt::GivenFetch { url, status, body, .. } => {
10919            count_expr_dispatch(url, interner, count);
10920            count_expr_dispatch(status, interner, count);
10921            count_expr_dispatch(body, interner, count);
10922        }
10923        Stmt::Fetch { url, body, .. } => {
10924            count_expr_dispatch(url, interner, count);
10925            if let Some(b) = body {
10926                count_expr_dispatch(b, interner, count);
10927            }
10928        }
10929        Stmt::Ui(u) => {
10930            for x in u.exprs() {
10931                count_expr_dispatch(x, interner, count);
10932            }
10933        }
10934        Stmt::Splice { body } | Stmt::Reversibly { body } => {
10935            for inner in body.iter() {
10936                count_stmt_dispatch(inner, interner, count);
10937            }
10938        }
10939        Stmt::Let { value, ty, .. } => {
10940            if let Some(t) = ty {
10941                if type_expr_mentions_core(t, interner) {
10942                    *count += 1;
10943                }
10944            }
10945            count_expr_dispatch(value, interner, count);
10946        }
10947        Stmt::Set { value, .. } => count_expr_dispatch(value, interner, count),
10948        // `Swap a and b` reads two bare variables — no interpreted sub-expression, no dispatch.
10949        Stmt::Swap { .. } => {}
10950        Stmt::Call { function, args } => {
10951            let fn_name = interner.resolve(*function);
10952            if CORE_VARIANT_NAMES.contains(&fn_name) || DISPATCH_FN_NAMES.contains(&fn_name) {
10953                *count += 1;
10954            }
10955            for a in args {
10956                count_expr_dispatch(a, interner, count);
10957            }
10958        }
10959        Stmt::If { cond, then_block, else_block } => {
10960            count_expr_dispatch(cond, interner, count);
10961            count_block_dispatch(then_block, interner, count);
10962            if let Some(els) = else_block {
10963                count_block_dispatch(els, interner, count);
10964            }
10965        }
10966        Stmt::While { cond, body, decreasing } => {
10967            count_expr_dispatch(cond, interner, count);
10968            count_block_dispatch(body, interner, count);
10969            if let Some(d) = decreasing {
10970                count_expr_dispatch(d, interner, count);
10971            }
10972        }
10973        Stmt::Repeat { iterable, body, .. } => {
10974            count_expr_dispatch(iterable, interner, count);
10975            count_block_dispatch(body, interner, count);
10976        }
10977        Stmt::Return { value } => {
10978            if let Some(v) = value {
10979                count_expr_dispatch(v, interner, count);
10980            }
10981        }
10982        Stmt::RuntimeAssert { condition, reason, .. } => {
10983            count_expr_dispatch(condition, interner, count);
10984            if let Some(r) = reason {
10985                count_expr_dispatch(r, interner, count);
10986            }
10987        }
10988        Stmt::Fail { reason } => count_expr_dispatch(reason, interner, count),
10989        Stmt::Give { object, recipient } | Stmt::Show { object, recipient } => {
10990            count_expr_dispatch(object, interner, count);
10991            count_expr_dispatch(recipient, interner, count);
10992        }
10993        Stmt::SetField { object, value, .. } => {
10994            count_expr_dispatch(object, interner, count);
10995            count_expr_dispatch(value, interner, count);
10996        }
10997        Stmt::FunctionDef { body, .. } => count_block_dispatch(body, interner, count),
10998        Stmt::TestDef { body, .. } => count_block_dispatch(body, interner, count),
10999        Stmt::During { body, .. } => count_block_dispatch(body, interner, count),
11000        Stmt::ForAll { body, constraint, .. } => {
11001            if let Some(c) = constraint {
11002                count_expr_dispatch(c, interner, count);
11003            }
11004            count_block_dispatch(body, interner, count);
11005        }
11006        Stmt::Observe { payloads, .. } => {
11007            for (_, e) in payloads {
11008                count_expr_dispatch(e, interner, count);
11009            }
11010        }
11011        Stmt::Expect { condition } => count_expr_dispatch(condition, interner, count),
11012        Stmt::ExpectFail { body, .. } => count_block_dispatch(body, interner, count),
11013        Stmt::ExpectOutput { .. } | Stmt::GivenFile { .. } => {}
11014        Stmt::AdvanceTime { millis } => count_expr_dispatch(millis, interner, count),
11015        Stmt::Inspect { target, arms, .. } => {
11016            count_expr_dispatch(target, interner, count);
11017            for arm in arms {
11018                if let Some(variant) = arm.variant {
11019                    if CORE_VARIANT_NAMES.contains(&interner.resolve(variant)) {
11020                        *count += 1;
11021                    }
11022                }
11023                count_block_dispatch(arm.body, interner, count);
11024            }
11025        }
11026        Stmt::Push { value, collection }
11027        | Stmt::Add { value, collection }
11028        | Stmt::Remove { value, collection } => {
11029            count_expr_dispatch(value, interner, count);
11030            count_expr_dispatch(collection, interner, count);
11031        }
11032        Stmt::Pop { collection, .. } => count_expr_dispatch(collection, interner, count),
11033        Stmt::SetIndex { collection, index, value } => {
11034            count_expr_dispatch(collection, interner, count);
11035            count_expr_dispatch(index, interner, count);
11036            count_expr_dispatch(value, interner, count);
11037        }
11038        Stmt::Zone { body, .. } => count_block_dispatch(body, interner, count),
11039        Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => {
11040            count_block_dispatch(tasks, interner, count)
11041        }
11042        Stmt::ReadFrom { source, .. } => {
11043            if let ReadSource::File(path) = source {
11044                count_expr_dispatch(path, interner, count);
11045            }
11046        }
11047        Stmt::WriteFile { content, path } => {
11048            count_expr_dispatch(content, interner, count);
11049            count_expr_dispatch(path, interner, count);
11050        }
11051        Stmt::SendMessage { message, destination, .. } => {
11052            count_expr_dispatch(message, interner, count);
11053            count_expr_dispatch(destination, interner, count);
11054        }
11055        Stmt::AwaitMessage { source, .. } => count_expr_dispatch(source, interner, count),
11056        Stmt::StreamMessage { values, destination } => {
11057            count_expr_dispatch(values, interner, count);
11058            count_expr_dispatch(destination, interner, count);
11059        }
11060        Stmt::MergeCrdt { source, target } | Stmt::JoinCrdt { source, target } => {
11061            count_expr_dispatch(source, interner, count);
11062            count_expr_dispatch(target, interner, count);
11063        }
11064        Stmt::IncreaseCrdt { object, amount, .. } | Stmt::DecreaseCrdt { object, amount, .. } => {
11065            count_expr_dispatch(object, interner, count);
11066            count_expr_dispatch(amount, interner, count);
11067        }
11068        Stmt::AppendToSequence { sequence, value } => {
11069            count_expr_dispatch(sequence, interner, count);
11070            count_expr_dispatch(value, interner, count);
11071        }
11072        Stmt::ResolveConflict { object, value, .. } => {
11073            count_expr_dispatch(object, interner, count);
11074            count_expr_dispatch(value, interner, count);
11075        }
11076        Stmt::Listen { address, .. } | Stmt::ConnectTo { address, .. } | Stmt::LetPeerAgent { address, .. } => {
11077            count_expr_dispatch(address, interner, count)
11078        }
11079        Stmt::Serve { port, handler } => {
11080            count_expr_dispatch(port, interner, count);
11081            count_expr_dispatch(handler, interner, count);
11082        }
11083        Stmt::Sleep { milliseconds } => count_expr_dispatch(milliseconds, interner, count),
11084        Stmt::Sync { topic, .. } => count_expr_dispatch(topic, interner, count),
11085        Stmt::Mount { path, .. } => count_expr_dispatch(path, interner, count),
11086        Stmt::LaunchTask { function, args } | Stmt::LaunchTaskWithHandle { function, args, .. } => {
11087            let fn_name = interner.resolve(*function);
11088            if CORE_VARIANT_NAMES.contains(&fn_name) || DISPATCH_FN_NAMES.contains(&fn_name) {
11089                *count += 1;
11090            }
11091            for a in args {
11092                count_expr_dispatch(a, interner, count);
11093            }
11094        }
11095        Stmt::SendPipe { value, pipe } | Stmt::TrySendPipe { value, pipe, .. } => {
11096            count_expr_dispatch(value, interner, count);
11097            count_expr_dispatch(pipe, interner, count);
11098        }
11099        Stmt::ReceivePipe { pipe, .. } | Stmt::TryReceivePipe { pipe, .. } => {
11100            count_expr_dispatch(pipe, interner, count)
11101        }
11102        Stmt::StopTask { handle } => count_expr_dispatch(handle, interner, count),
11103        Stmt::CloseChannel { channel } => count_expr_dispatch(channel, interner, count),
11104        Stmt::AwaitTask { handle, .. } => count_expr_dispatch(handle, interner, count),
11105        Stmt::Select { branches } => {
11106            for b in branches {
11107                match b {
11108                    SelectBranch::Receive { pipe, body, .. } => {
11109                        count_expr_dispatch(pipe, interner, count);
11110                        count_block_dispatch(body, interner, count);
11111                    }
11112                    SelectBranch::Timeout { milliseconds, body } => {
11113                        count_expr_dispatch(milliseconds, interner, count);
11114                        count_block_dispatch(body, interner, count);
11115                    }
11116                }
11117            }
11118        }
11119        Stmt::Escape { code, .. } => count_escape_code_dispatch(interner.resolve(*code), count),
11120        // Leaves and declarations: no executable `Expr` children reach the oracle.
11121        // `Assert`/`Trust` carry a `LogicExpr` (proof layer), not an executable `Expr`.
11122        Stmt::Break
11123        | Stmt::Assert { .. }
11124        | Stmt::Trust { .. }
11125        | Stmt::StructDef { .. }
11126        | Stmt::Spawn { .. }
11127        | Stmt::Check { .. }
11128        | Stmt::CreatePipe { .. }
11129        | Stmt::Theorem(_)
11130        | Stmt::Definition(_)
11131        | Stmt::Axiom(_)
11132        | Stmt::Theory(_)
11133        | Stmt::Require { .. }
11134        // An opaque failure-site marker: an id, no interpreted sub-expression — same shape as
11135        // `Swap` above, no dispatch.
11136        | Stmt::Site(_) => {}
11137    }
11138}
11139
11140/// Exhaustive by construction — NO `_` arm. Every sub-expression is recursed, so a Core
11141/// constructor or dispatch call cannot hide inside a container (`List`/`Tuple`), an
11142/// operator, a constructor field, an interpolant, or a closure body.
11143fn count_expr_dispatch(expr: &Expr, interner: &Interner, count: &mut usize) {
11144    match expr {
11145        Expr::Dom(q) => {
11146            if let Some(sel) = q.selector() {
11147                count_expr_dispatch(sel, interner, count);
11148            }
11149        }
11150        Expr::View(v) => {
11151            let (view_exprs, view_blocks) = v.exprs_and_blocks();
11152            for e in view_exprs {
11153                count_expr_dispatch(e, interner, count);
11154            }
11155            for b in view_blocks {
11156                for inner in b.iter() {
11157                    count_stmt_dispatch(inner, interner, count);
11158                }
11159            }
11160        }
11161        Expr::Literal(_) | Expr::Identifier(_) | Expr::OptionNone => {}
11162        Expr::BinaryOp { left, right, .. }
11163        | Expr::Union { left, right }
11164        | Expr::Intersection { left, right } => {
11165            count_expr_dispatch(left, interner, count);
11166            count_expr_dispatch(right, interner, count);
11167        }
11168        Expr::Not { operand } => count_expr_dispatch(operand, interner, count),
11169        Expr::Call { function, args } => {
11170            let fn_name = interner.resolve(*function);
11171            if CORE_VARIANT_NAMES.contains(&fn_name) || DISPATCH_FN_NAMES.contains(&fn_name) {
11172                *count += 1;
11173            }
11174            for a in args {
11175                count_expr_dispatch(a, interner, count);
11176            }
11177        }
11178        Expr::Index { collection, index } => {
11179            // Any `item ... of env|funcs` is surviving interpreter-state threading, whatever
11180            // the key: a Jones-optimal residual holds no environment/function map at all.
11181            if let Expr::Identifier(coll_sym) = collection {
11182                let coll_name = interner.resolve(*coll_sym);
11183                if coll_name == "env" || coll_name == "funcs" {
11184                    *count += 1;
11185                }
11186            }
11187            count_expr_dispatch(collection, interner, count);
11188            count_expr_dispatch(index, interner, count);
11189        }
11190        Expr::Slice {
11191            collection,
11192            start,
11193            end,
11194        } => {
11195            count_expr_dispatch(collection, interner, count);
11196            count_expr_dispatch(start, interner, count);
11197            count_expr_dispatch(end, interner, count);
11198        }
11199        Expr::Copy { expr: inner } => count_expr_dispatch(inner, interner, count),
11200        Expr::Give { value } => count_expr_dispatch(value, interner, count),
11201        Expr::Length { collection } => count_expr_dispatch(collection, interner, count),
11202        Expr::Contains { collection, value } => {
11203            count_expr_dispatch(collection, interner, count);
11204            count_expr_dispatch(value, interner, count);
11205        }
11206        Expr::ManifestOf { zone } => count_expr_dispatch(zone, interner, count),
11207        Expr::ChunkAt { index, zone } => {
11208            count_expr_dispatch(index, interner, count);
11209            count_expr_dispatch(zone, interner, count);
11210        }
11211        Expr::List(items) | Expr::Tuple(items) => {
11212            for e in items {
11213                count_expr_dispatch(e, interner, count);
11214            }
11215        }
11216        Expr::Range { start, end } => {
11217            count_expr_dispatch(start, interner, count);
11218            count_expr_dispatch(end, interner, count);
11219        }
11220        Expr::FieldAccess { object, .. } => count_expr_dispatch(object, interner, count),
11221        Expr::New {
11222            type_name,
11223            type_args,
11224            init_fields,
11225        } => {
11226            let tn = interner.resolve(*type_name);
11227            if CORE_VARIANT_NAMES.contains(&tn) || CORE_TYPE_NAMES.contains(&tn) {
11228                *count += 1;
11229            }
11230            // A collection over a Core carrier type — `a new Map of Text to CVal` — is the
11231            // interpreter's environment/function map surviving in the residual.
11232            for ta in type_args {
11233                if type_expr_mentions_core(ta, interner) {
11234                    *count += 1;
11235                }
11236            }
11237            for (_, v) in init_fields {
11238                count_expr_dispatch(v, interner, count);
11239            }
11240        }
11241        Expr::NewVariant {
11242            variant, fields, ..
11243        } => {
11244            if CORE_VARIANT_NAMES.contains(&interner.resolve(*variant)) {
11245                *count += 1;
11246            }
11247            for (_, v) in fields {
11248                count_expr_dispatch(v, interner, count);
11249            }
11250        }
11251        Expr::Escape { code, .. } => count_escape_code_dispatch(interner.resolve(*code), count),
11252        Expr::OptionSome { value } => count_expr_dispatch(value, interner, count),
11253        Expr::WithCapacity { value, capacity } => {
11254            count_expr_dispatch(value, interner, count);
11255            count_expr_dispatch(capacity, interner, count);
11256        }
11257        Expr::Closure { body, .. } => match body {
11258            ClosureBody::Expression(e) => count_expr_dispatch(e, interner, count),
11259            ClosureBody::Block(b) => count_block_dispatch(b, interner, count),
11260        },
11261        Expr::CallExpr { callee, args } => {
11262            count_expr_dispatch(callee, interner, count);
11263            for a in args {
11264                count_expr_dispatch(a, interner, count);
11265            }
11266        }
11267        Expr::InterpolatedString(parts) => {
11268            for p in parts {
11269                if let StringPart::Expr { value, .. } = p {
11270                    count_expr_dispatch(value, interner, count);
11271                }
11272            }
11273        }
11274    }
11275}
11276
11277/// Returns the source text of the partial evaluator written in LOGOS.
11278///
11279/// This PE operates on CProgram representations using explicit environments
11280/// and static dispatch. It is first-order (no closures) and uses only
11281/// literal string function names (no dynamic dispatch).
11282pub fn pe_source_text() -> &'static str {
11283    include_str!("optimize/pe_source.logos")
11284}
11285
11286pub fn decompile_source_text() -> &'static str {
11287    include_str!("optimize/decompile_source.logos")
11288}
11289
11290pub fn pe_bti_source_text() -> &'static str {
11291    include_str!("optimize/pe_bti_source.logos")
11292}
11293
11294pub fn pe_mini_source_text() -> &'static str {
11295    include_str!("optimize/pe_mini_source.logos")
11296}
11297
11298/// The canonical inductive type catalog the Futamura projections are built on
11299/// (`CStmt`/`CExpr`/`CVal`/…). Every statement the tree-walker executes has a
11300/// `C…` constructor here; the partial-evaluator dialects dispatch on it. Exposed
11301/// so cross-tier lock tests can prove this catalog and every tier stay in sync —
11302/// a statement added to the language must appear here or it is dropped from the
11303/// projections (see `tier_parity_lock.rs`).
11304pub fn core_types_for_pe_source() -> &'static str {
11305    CORE_TYPES_FOR_PE
11306}
11307
11308const CORE_TYPES_FOR_PE: &str = r#"
11309## A CExpr is one of:
11310    A CInt with value Int.
11311    A CFloat with value Real.
11312    A CBool with value Bool.
11313    A CText with value Text.
11314    A CVar with name Text.
11315    A CBinOp with op Text and left CExpr and right CExpr.
11316    A CNot with inner CExpr.
11317    A CCall with name Text and args Seq of CExpr.
11318    A CIndex with coll CExpr and idx CExpr.
11319    A CLen with target CExpr.
11320    A CMapGet with target CExpr and key CExpr.
11321    A CNewSeq.
11322    A CNewVariant with tag Text and fnames Seq of Text and fvals Seq of CExpr.
11323    A CList with items Seq of CExpr.
11324    A CRange with start CExpr and end CExpr.
11325    A CSlice with coll CExpr and startIdx CExpr and endIdx CExpr.
11326    A CCopy with target CExpr.
11327    A CNewSet.
11328    A CContains with coll CExpr and elem CExpr.
11329    A CUnion with left CExpr and right CExpr.
11330    A CIntersection with left CExpr and right CExpr.
11331    A COptionSome with inner CExpr.
11332    A COptionNone.
11333    A CTuple with items Seq of CExpr.
11334    A CNew with typeName Text and fieldNames Seq of Text and fields Seq of CExpr.
11335    A CFieldAccess with target CExpr and field Text.
11336    A CClosure with params Seq of Text and body Seq of CStmt and captured Seq of Text.
11337    A CCallExpr with target CExpr and args Seq of CExpr.
11338    A CInterpolatedString with parts Seq of CStringPart.
11339    A CDuration with amount CExpr and unit Text.
11340    A CTimeNow.
11341    A CDateToday.
11342    A CEscExpr with code Text.
11343    A CManifestOf with zn CExpr.
11344    A CChunkAt with idx CExpr and zn CExpr.
11345
11346## A CStringPart is one of:
11347    A CLiteralPart with value Text.
11348    A CExprPart with expr CExpr.
11349
11350## A CStmt is one of:
11351    A CLet with name Text and expr CExpr.
11352    A CSet with name Text and expr CExpr.
11353    A CIf with cond CExpr and thenBlock Seq of CStmt and elseBlock Seq of CStmt.
11354    A CWhile with cond CExpr and body Seq of CStmt.
11355    A CReturn with expr CExpr.
11356    A CShow with expr CExpr.
11357    A CCallS with name Text and args Seq of CExpr.
11358    A CPush with expr CExpr and target Text.
11359    A CSetIdx with target Text and idx CExpr and val CExpr.
11360    A CMapSet with target Text and key CExpr and val CExpr.
11361    A CPop with target Text.
11362    A CRepeat with var Text and coll CExpr and body Seq of CStmt.
11363    A CRepeatRange with var Text and start CExpr and end CExpr and body Seq of CStmt.
11364    A CBreak.
11365    A CAdd with elem CExpr and target Text.
11366    A CRemove with elem CExpr and target Text.
11367    A CForceDynamic with name Text.
11368    A CSetField with target Text and field Text and val CExpr.
11369    A CStructDef with name Text and fieldNames Seq of Text.
11370    A CInspect with target CExpr and arms Seq of CMatchArm.
11371    A CEnumDef with name Text and variants Seq of Text.
11372    A CRuntimeAssert with cond CExpr and msg CExpr.
11373    A CHardAssert with cond CExpr and msg CExpr.
11374    A CGive with expr CExpr and target Text.
11375    A CEscStmt with code Text.
11376    A CSleep with duration CExpr.
11377    A CReadConsole with target Text.
11378    A CReadFile with path CExpr and target Text.
11379    A CWriteFile with path CExpr and content CExpr.
11380    A CCheck with predicate CExpr and msg CExpr.
11381    A CAssert with proposition CExpr.
11382    A CTrust with proposition CExpr and justification Text.
11383    A CRequire with dependency Text.
11384    A CMerge with target Text and other CExpr.
11385    A CJoin with target Text and other CExpr.
11386    A CIncrease with target Text and amount CExpr.
11387    A CDecrease with target Text and amount CExpr.
11388    A CAppendToSeq with target Text and value CExpr.
11389    A CResolve with target Text.
11390    A CSync with target Text and channel CExpr.
11391    A CMount with target Text and path CExpr.
11392    A CConcurrent with branches Seq of Seq of CStmt.
11393    A CParallel with branches Seq of Seq of CStmt.
11394    A CLaunchTask with body Seq of CStmt and handle Text.
11395    A CStopTask with handle CExpr.
11396    A CSelect with branches Seq of CSelectBranch.
11397    A CCreatePipe with name Text and capacity CExpr.
11398    A CSendPipe with chan Text and value CExpr.
11399    A CReceivePipe with chan Text and target Text.
11400    A CTrySendPipe with chan Text and value CExpr.
11401    A CTryReceivePipe with chan Text and target Text.
11402    A CSpawn with agentType Text and target Text.
11403    A CSendMessage with target CExpr and msg CExpr.
11404    A CStreamMessage with target CExpr and values CExpr.
11405    A CAwaitMessage with target Text.
11406    A CListen with addr CExpr and handler Text.
11407    A CConnectTo with addr CExpr and target Text.
11408    A CZone with name Text and kind Text and body Seq of CStmt.
11409
11410## A CSelectBranch is one of:
11411    A CSelectRecv with chan Text and var Text and body Seq of CStmt.
11412    A CSelectTimeout with duration CExpr and body Seq of CStmt.
11413
11414## A CMatchArm is one of:
11415    A CWhen with variantName Text and bindings Seq of Text and body Seq of CStmt.
11416    A COtherwise with body Seq of CStmt.
11417
11418## A CFunc is one of:
11419    A CFuncDef with name Text and params Seq of Text and paramTypes Seq of Text and returnType Text and body Seq of CStmt.
11420
11421## A CProgram is one of:
11422    A CProg with funcs Seq of CFunc and main Seq of CStmt.
11423
11424## A PEState is one of:
11425    A PEStateR with env Map of Text to CVal and funcs Map of Text to CFunc and depth Int and staticEnv Map of Text to CExpr and specResults Map of Text to CExpr and onStack Seq of Text.
11426
11427## A CVal is one of:
11428    A VInt with value Int.
11429    A VFloat with value Real.
11430    A VBool with value Bool.
11431    A VText with value Text.
11432    A VSeq with items Seq of CVal.
11433    A VMap with entries Map of Text to CVal.
11434    A VError with msg Text.
11435    A VNothing.
11436    A VSet with items Seq of CVal.
11437    A VOption with inner CVal and present Bool.
11438    A VTuple with items Seq of CVal.
11439    A VStruct with typeName Text and fields Map of Text to CVal.
11440    A VVariant with typeName Text and variantName Text and fields Seq of CVal.
11441    A VClosure with params Seq of Text and body Seq of CStmt and capturedEnv Map of Text to CVal.
11442    A VDuration with millis Int.
11443    A VDate with year Int and month Int and day Int.
11444    A VMoment with millis Int.
11445    A VSpan with startMillis Int and endMillis Int.
11446    A VTime with hour Int and minute Int and second Int.
11447    A VCrdt with kind Text and state Map of Text to CVal.
11448"#;
11449
11450/// Encodes the partial evaluator as CProgram construction source code.
11451///
11452/// Returns PE function definitions (so peBlock etc. are callable) followed by
11453/// LOGOS statements that construct the PE's functions as CFunc data in
11454/// `encodedFuncMap` and its main block in `encodedMain`.
11455/// The parser handles `## To` blocks anywhere in the token stream, so
11456/// function definitions placed after `## Main` are parsed correctly.
11457pub fn quote_pe_source() -> Result<String, String> {
11458    let pe_source = pe_source_text();
11459    let full_source = format!("{}\n{}", CORE_TYPES_FOR_PE, pe_source);
11460    let encoded = encode_program_source(&full_source)
11461        .map_err(|e| format!("Failed to encode PE: {}", describe_parse_error(&e)))?;
11462    Ok(format!("{}\n{}", pe_source, encoded))
11463}
11464
11465/// Second Futamura Projection: PE(PE, interpreter) = compiler
11466///
11467/// Specializes the partial evaluator with respect to a fixed interpreter,
11468/// producing a compiler that takes any CProgram as input and produces
11469/// optimized residual CStmt/CExpr data.
11470///
11471/// For the Core self-interpreter (which is the identity evaluator on CProgram
11472/// data), PE(PE, int) resolves to the PE itself operating directly on program
11473/// data — the interpreter's dispatch loop is the CExpr/CStmt case analysis
11474/// that the PE already implements. The result is the PE with its entry points
11475/// renamed to compileExpr/compileBlock: these ARE the specialized compiler
11476/// functions with no PE dispatch overhead (BTA, memoization, etc. are absent
11477/// because the interpreter's representation IS the PE's representation).
11478///
11479/// NOTE: this is the renamed-PE REPRESENTATION of P2 — it ASSERTS the collapse by renaming. The
11480/// GENUINE projection that DEMONSTRATES it by actually running `PE(pe_source, pe_mini)` is
11481/// [`genuine_projection2_residual`] (and [`run_genuine_p2_on_target`]). Enforcement gates use the
11482/// genuine path; `shortcut_quarantine_lock` forbids any Jones-certifying gate from using this rename.
11483pub fn projection2_source() -> Result<String, String> {
11484    let pe_source = pe_source_text();
11485
11486    let compiler_source = replace_word(
11487        &replace_word(&pe_source, "peExpr", "compileExpr"),
11488        "peBlock",
11489        "compileBlock",
11490    );
11491
11492    Ok(format!("{}\n{}", CORE_TYPES_FOR_PE, compiler_source))
11493}
11494
11495/// Third Futamura Projection: PE(PE, PE) = compiler_generator
11496///
11497/// Specializes the partial evaluator with respect to itself, producing a
11498/// compiler generator (cogen). Feed it any interpreter → it produces a
11499/// compiler for that interpreter's language.
11500///
11501/// Chain: cogen(int) → compiler → compiler(P) → compiled
11502///
11503/// For the CExpr/CStmt representation, PE(PE, PE) yields the PE with entry
11504/// points renamed to cogenExpr/cogenBlock. This works because the PE's
11505/// self-application is idempotent: the PE already operates on the same
11506/// representation it would specialize, so PE(PE, PE) = PE (up to naming).
11507/// The cogen handles different interpreters (Core, RPN, etc.) by processing
11508/// their encoded CProgram representations.
11509///
11510/// NOTE: the renamed-PE REPRESENTATION of P3 (asserts the collapse by renaming). The GENUINE cogen
11511/// that actually runs `PE(pe_source, pe_bti)` is [`genuine_projection3_residual`]. Enforcement uses
11512/// the genuine path; `shortcut_quarantine_lock` keeps this rename out of any Jones certificate.
11513pub fn projection3_source() -> Result<String, String> {
11514    let pe_source = pe_source_text();
11515
11516    let cogen_source = replace_word(
11517        &replace_word(&pe_source, "peExpr", "cogenExpr"),
11518        "peBlock",
11519        "cogenBlock",
11520    );
11521
11522    Ok(format!("{}\n{}", CORE_TYPES_FOR_PE, cogen_source))
11523}
11524
11525/// Compile and run LOGOS source, returning stdout.
11526///
11527/// Uses the full compilation pipeline: LOGOS → Rust → binary → execute.
11528/// This is the library-side equivalent of the test infrastructure's `run_logos()`.
11529pub fn run_logos_source(source: &str) -> Result<String, String> {
11530    let compile_output = compile_program_full(source)
11531        .map_err(|e| format!("Compilation failed: {}", describe_parse_error(&e)))?;
11532
11533    // Create temp directory using std (no tempfile crate needed)
11534    let temp_base = std::env::temp_dir().join("logos_run_source");
11535    std::fs::create_dir_all(&temp_base).map_err(|e| format!("mkdir failed: {}", e))?;
11536
11537    let pkg_name = format!(
11538        "logos_run_{}_{}",
11539        std::process::id(),
11540        std::time::SystemTime::now()
11541            .duration_since(std::time::UNIX_EPOCH)
11542            .unwrap()
11543            .as_nanos()
11544    );
11545    let project_dir = temp_base.join(&pkg_name);
11546
11547    // Find workspace root relative to this crate
11548    let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
11549    let workspace_root = manifest_dir.parent().unwrap().parent().unwrap();
11550
11551    let cargo_toml = format!(
11552        r#"[package]
11553name = "{}"
11554version = "0.1.0"
11555edition = "2021"
11556
11557[dependencies]
11558logicaffeine-data = {{ path = "{}/crates/logicaffeine_data" }}
11559logicaffeine-system = {{ path = "{}/crates/logicaffeine_system", features = ["full"] }}
11560tokio = {{ version = "1", features = ["rt-multi-thread", "macros"] }}
11561serde = {{ version = "1", features = ["derive"] }}
11562rayon = "1"
11563"#,
11564        pkg_name,
11565        workspace_root.display(),
11566        workspace_root.display(),
11567    );
11568
11569    std::fs::create_dir_all(project_dir.join("src")).map_err(|e| format!("mkdir failed: {}", e))?;
11570    std::fs::write(project_dir.join("Cargo.toml"), cargo_toml)
11571        .map_err(|e| format!("Write Cargo.toml failed: {}", e))?;
11572    std::fs::write(project_dir.join("src/main.rs"), &compile_output.rust_code)
11573        .map_err(|e| format!("Write main.rs failed: {}", e))?;
11574    // Pin dependency resolution to the workspace's lockfile: without it each
11575    // generated project re-resolves from the registry and a newly published
11576    // transitive version can break the build.
11577    std::fs::copy(
11578        workspace_root.join("Cargo.lock"),
11579        project_dir.join("Cargo.lock"),
11580    )
11581    .map_err(|e| format!("Seed Cargo.lock failed: {}", e))?;
11582
11583    // Use a shared target dir for caching. Under cargo-nextest, shard by the
11584    // per-test slot (mirrors the test harness's get_shared_target_dir) so
11585    // concurrent generated builds never contend on Cargo's build-dir lock.
11586    let shard = std::env::var("NEXTEST_TEST_GROUP_SLOT")
11587        .ok()
11588        .and_then(|s| s.parse::<u64>().ok())
11589        .or_else(|| {
11590            std::env::var("NEXTEST_TEST_GLOBAL_SLOT")
11591                .ok()
11592                .and_then(|s| s.parse::<u64>().ok())
11593                .map(|n| n % 12)
11594        });
11595    let target_dir = match shard {
11596        Some(s) => std::env::temp_dir().join(format!("logos_e2e_cache_{s}")),
11597        None => std::env::temp_dir().join("logos_e2e_cache"),
11598    };
11599    std::fs::create_dir_all(&target_dir).map_err(|e| format!("mkdir target failed: {}", e))?;
11600
11601    let mut run_cmd = std::process::Command::new("cargo");
11602    run_cmd
11603        .args(["run", "--quiet"])
11604        .current_dir(&project_dir)
11605        .env("CARGO_TARGET_DIR", &target_dir)
11606        .env("RUST_MIN_STACK", "268435456");
11607    // Bootstrap-scope: when the compiler is running its own PE / self-interpreter
11608    // (a `ReferenceScope`), the AOT child it spawns must run that compile-time
11609    // Logos under reference semantics — the partial evaluator is self-applicable
11610    // and only specializes when its threaded state is mutated in place.
11611    if crate::semantics::collections::reference_scope_active() {
11612        run_cmd.env("LOGOS_VALUE_SEMANTICS", "0");
11613    }
11614    let output = run_cmd
11615        .output()
11616        .map_err(|e| format!("cargo run failed: {}", e))?;
11617
11618    // Clean up temp project dir AND this project's artifacts in the shared
11619    // cache (unique package names would otherwise accrete one binary +
11620    // deps/incremental/fingerprint entries per run, forever — the shared
11621    // DEPENDENCY builds stay, which is the entire caching win).
11622    let _ = std::fs::remove_dir_all(&project_dir);
11623    {
11624        let stem = pkg_name.replace('-', "_");
11625        let debug = target_dir.join("debug");
11626        let _ = std::fs::remove_file(debug.join(&pkg_name));
11627        let _ = std::fs::remove_file(debug.join(format!("{pkg_name}.d")));
11628        for sub in ["deps", "incremental", ".fingerprint", "build"] {
11629            if let Ok(rd) = std::fs::read_dir(debug.join(sub)) {
11630                for e in rd.flatten() {
11631                    let name = e.file_name();
11632                    let n = name.to_string_lossy();
11633                    if n.starts_with(&format!("{stem}-")) || n.starts_with(&format!("lib{stem}-")) {
11634                        let path = e.path();
11635                        let _ = if path.is_dir() {
11636                            std::fs::remove_dir_all(&path)
11637                        } else {
11638                            std::fs::remove_file(&path)
11639                        };
11640                    }
11641                }
11642            }
11643        }
11644    }
11645
11646    if !output.status.success() {
11647        return Err(format!(
11648            "Execution failed (status={:?} code={:?}):\nstderr: {}\nstdout: {}",
11649            output.status,
11650            output.status.code(),
11651            String::from_utf8_lossy(&output.stderr),
11652            String::from_utf8_lossy(&output.stdout),
11653        ));
11654    }
11655
11656    Ok(String::from_utf8_lossy(&output.stdout).to_string())
11657}
11658
11659/// Result of a genuine Futamura projection via self-application.
11660/// Contains the LOGOS source of the residual and the discovered entry points.
11661pub struct GenuineProjectionResult {
11662    /// The LOGOS source of the genuine residual — exactly as the PE produced it,
11663    /// including specialized function definitions and a ## Main block.
11664    pub source: String,
11665    /// The name of the block-level entry point (e.g., "peBlockM_d_vPEMiniR_...").
11666    /// This is the specialized function that takes a Seq of CStmt and returns Seq of CStmt.
11667    pub block_entry: String,
11668    /// The name of the expression-level entry point, if discovered.
11669    pub expr_entry: Option<String>,
11670}
11671
11672/// Discover specialized entry points from a PE residual.
11673/// Searches for `## To {prefix}_...` function definitions in the residual source.
11674fn discover_entry_points(
11675    residual: &str,
11676    block_prefix: &str,
11677    expr_prefix: &str,
11678) -> (String, Option<String>) {
11679    let mut block_entry = String::new();
11680    let mut expr_entry = None;
11681    for line in residual.lines() {
11682        let trimmed = line.trim();
11683        if let Some(rest) = trimmed.strip_prefix("## To ") {
11684            // Extract function name: everything before the first ' ('
11685            let name = rest.split(" (").next().unwrap_or("").trim();
11686            if name.starts_with(block_prefix) && block_entry.is_empty() {
11687                block_entry = name.to_string();
11688            } else if name.starts_with(expr_prefix) && expr_entry.is_none() {
11689                expr_entry = Some(name.to_string());
11690            }
11691        }
11692    }
11693    (block_entry, expr_entry)
11694}
11695
11696/// Real Futamura Projection 1: pe(program) = compiled_program
11697///
11698/// Encodes the program as CProgram data, runs the LOGOS PE on it,
11699/// decompiles the residual back to LOGOS source.
11700pub fn projection1_source_real(
11701    core_types: &str,
11702    _interpreter: &str,
11703    program: &str,
11704) -> Result<String, String> {
11705    let full_source = if program.contains("## Main") || program.contains("## To ") {
11706        program.to_string()
11707    } else {
11708        format!("## Main\n{}", program)
11709    };
11710
11711    // Step 1: Encode the program as CProgram construction source
11712    let encoded = encode_program_source(&full_source)
11713        .map_err(|e| format!("Failed to encode program: {}", describe_parse_error(&e)))?;
11714
11715    // Step 2: Get PE source and decompile source
11716    let pe_source = pe_source_text();
11717    let decompile_source = decompile_source_text();
11718
11719    // Step 3: Build the combined source
11720    let actual_core_types = if core_types.is_empty() {
11721        CORE_TYPES_FOR_PE
11722    } else {
11723        core_types
11724    };
11725
11726    let driver = r#"
11727    Let state be makePeState(a new Map of Text to CVal, encodedFuncMap, 200).
11728    Let residual be peBlock(encodedMain, state).
11729    Let source be decompileBlock(residual, 0).
11730    Show source.
11731"#;
11732
11733    let combined = format!(
11734        "{}\n{}\n{}\n## Main\n{}\n{}",
11735        actual_core_types, pe_source, decompile_source, encoded, driver,
11736    );
11737
11738    // Step 4: Compile and run to get the decompiled residual
11739    let raw_residual = with_reference_semantics(|| run_logos_source(&combined))?;
11740    let trimmed = raw_residual.trim();
11741
11742    // Step 5: Wrap in ## Main if needed
11743    if trimmed.is_empty() {
11744        return Ok("## Main\n".to_string());
11745    }
11746
11747    // Check if the residual already has function definitions
11748    if trimmed.contains("## To ") || trimmed.starts_with("## Main") {
11749        Ok(trimmed.to_string())
11750    } else {
11751        Ok(format!("## Main\n{}", trimmed))
11752    }
11753}
11754
11755/// In-process variant of [`projection1_source_real`].
11756///
11757/// Identical in every respect except that the combined PE source is executed by the
11758/// tree-walking interpreter via [`interpret_program`] rather than compiled to Rust and
11759/// run through `cargo` ([`run_logos_source`]). This makes the genuine LOGOS partial
11760/// evaluator cheap enough to drive a generative/differential test corpus.
11761pub fn projection1_source_real_fast(
11762    core_types: &str,
11763    _interpreter: &str,
11764    program: &str,
11765) -> Result<String, String> {
11766    let combined = pe_combined_source(core_types, program)?;
11767
11768    let raw_residual = interpret_bootstrap(&combined)
11769        .map_err(|e| format!("PE execution failed: {}", describe_parse_error(&e)))?;
11770    let residual = finish_projection1_residual(raw_residual)?;
11771    // The residual is statements-only (`## To` specialized funcs + `## Main`); re-attach the
11772    // program's TYPE DEFINITIONS so a `new <Struct>` in the residual can default-fill its
11773    // fields — e.g. a `Shared` struct's CRDT `SharedSet`/`SharedSequence` field, which has no
11774    // explicit constructor argument and is materialized solely from the definition.
11775    Ok(prepend_type_definitions(program, residual))
11776}
11777
11778pub use crate::concurrency::marshal::{decode_value_raw, encode_value_raw};
11779
11780/// The self-interpreter (`coreEval` / `coreExecBlock`) as a first-class committed artifact — the
11781/// Logos program the genuine P2/P3 projections specialize (Futamura: `pe(pe, coreEval)` is a
11782/// compiler). Promoted out of the `phase_futamura` test fixture so it is a real source file, not a
11783/// string constant; the fixture now `include_str!`s this exact file (parity is structural).
11784pub fn core_interp_source() -> &'static str {
11785    include_str!("optimize/core_interp.logos")
11786}
11787
11788/// The compile-once native partial evaluator's SOURCE: the PE engine + decompiler + a driver
11789/// that reads its input `CProgram` from stdin (over the fast wire codec) instead of a baked-in
11790/// constructor. Compiled ONCE (content-addressed on this text) with `WireEncode`/`WireDecode`
11791/// emitted, it specializes any program handed to it as `program_to_core_wire_bytes` — the true
11792/// Futamura "compiler as an artifact", at native speed. The driver body is identical to
11793/// [`pe_combined_source`]'s (same transitive-decompile), only `encodedMain`/`encodedFuncMap`
11794/// come from `readWireProgram()` rather than the encoded program text.
11795/// The transitive-decompile driver logic shared by the resident-server PE (`pe_native_source`,
11796/// terminal statement writes the residual to stdout) and the in-process cdylib PE
11797/// (`pe_cdylib_source`, terminal statement `Return`s it). Everything up to that last statement is
11798/// identical — computing `output`, the Jones-optimal residual source, from `encodedMain` +
11799/// `encodedFuncMap`. Written at 0-base indent; the caller re-indents it under its enclosing arm.
11800const PE_DRIVER_CORE: &str = r#"Let state be makePeState(a new Map of Text to CVal, encodedFuncMap, 200).
11801Let residual be peBlock(encodedMain, state).
11802Let nl be chr(10).
11803Let mutable output be "".
11804Let specFuncs be peFuncs(state).
11805Let mutable allNames be collectCallNames(residual).
11806Let mutable emitted be a new Map of Text to Bool.
11807Let mutable changed be true.
11808While changed:
11809    Set changed to false.
11810    Let mutable toAdd be a new Seq of Text.
11811    Repeat for fnKey in allNames:
11812        Let fkStr be "{fnKey}".
11813        If emitted contains fkStr:
11814            Let skipE be true.
11815        Otherwise:
11816            Set item fkStr of emitted to true.
11817            Let fkStr2 be "{fnKey}".
11818            If specFuncs contains fkStr2:
11819                Let fdef be item fkStr2 of specFuncs.
11820                Inspect fdef:
11821                    When CFuncDef (fn0, ps0, pt0, rt0, body0):
11822                        Let children be collectCallNames(body0).
11823                        Repeat for child in children:
11824                            Let childStr be "{child}".
11825                            If not emitted contains childStr:
11826                                Push child to toAdd.
11827                                Set changed to true.
11828                    Otherwise:
11829                        Let skipF be true.
11830    Repeat for ta in toAdd:
11831        Push ta to allNames.
11832Repeat for fnKey in allNames:
11833    Let fkStr be "{fnKey}".
11834    If specFuncs contains fkStr:
11835        Let fdef be item fkStr of specFuncs.
11836        Let funcSrc be decompileFunc(fdef).
11837        If the length of funcSrc is greater than 0:
11838            Set output to "{output}{funcSrc}{nl}".
11839Let mainSrc be decompileBlock(residual, 0).
11840Set output to "{output}## Main{nl}{mainSrc}"."#;
11841
11842/// The PE driver body with `last` appended as its terminal statement — the only line that differs
11843/// between the stdout-writing server and the value-returning cdylib entry.
11844fn pe_driver_body(last: &str) -> String {
11845    format!("{PE_DRIVER_CORE}\n{last}")
11846}
11847
11848pub fn pe_native_source() -> String {
11849    let core = CORE_TYPES_FOR_PE;
11850    let pe = pe_source_text();
11851    let decompile = decompile_source_text();
11852    // The transitive-decompile driver body, written at 0-base indent — identical logic to
11853    // `pe_combined_source`. It is re-indented under the `When CProg` arm below so the CProg fields
11854    // (`LogosSeq`-typed, not the `Vec` a declared `Seq` return would be) stay in scope with the
11855    // right runtime type — sidestepping the return-type/field-type codegen mismatch.
11856    let driver_body = pe_driver_body("Let __wrn be writeWireResidual(output).");
11857    // Resident-server loop: `While true` reads one length-framed program per iteration
11858    // (`readWireProgram` exits the process on stdin EOF), specializes it, and writes the residual
11859    // back length-framed (`writeWireResidual`). Spawned ONCE by the host and reused — no per-call
11860    // process spawn. Indent the driver body to 16 spaces (inside the `When CProg` arm inside `While`).
11861    let indented: String = driver_body
11862        .lines()
11863        .map(|l| {
11864            if l.is_empty() {
11865                String::new()
11866            } else {
11867                format!("                {l}")
11868            }
11869        })
11870        .collect::<Vec<_>>()
11871        .join("\n");
11872    let main = format!(
11873        "    While true:\n        Let __prog be readWireProgram().\n        Inspect __prog:\n            When CProg (encFuncs, encMain):\n                Let encodedMain be encMain.\n                Let mutable encodedFuncMap be a new Map of Text to CFunc.\n                Repeat for __f in encFuncs:\n                    Inspect __f:\n                        When CFuncDef (__nm, __ps, __pt, __rt, __bd):\n                            Set item __nm of encodedFuncMap to __f.\n                        Otherwise:\n                            Let __skip be true.\n{indented}\n            Otherwise:\n                Let __wrn be writeWireResidual(\"\").\n"
11874    );
11875    format!("{}\n{}\n{}\n## Main\n{}", core, pe, decompile, main)
11876}
11877
11878/// The PE as an IN-PROCESS cdylib entry: the identical engine to [`pe_native_source`], but the
11879/// driver is a single-shot `## To peSpecializeOnce (__prog: CProgram) -> Text` that RETURNS the
11880/// residual instead of writing it to stdout — no `readWireProgram`/`writeWireResidual`, no stdin
11881/// loop. The exported cdylib ([`build_native_pe_cdylib`]) decodes the wire bytes to a `CProgram` in
11882/// its `extern "C"` shim and calls this function directly, so the resident server's process/pipe
11883/// round-trip is gone. The driver `is exported for native`: host code calls it, so it keeps the
11884/// signature it declares, its program taken by value, whatever the emitter would lend an internal
11885/// function. `## Main` is a trivial stub (a cdylib never runs it).
11886pub fn pe_cdylib_source() -> String {
11887    let core = CORE_TYPES_FOR_PE;
11888    let pe = pe_source_text();
11889    let decompile = decompile_source_text();
11890    // Same driver as the server, terminated by `Return output.`; re-indented to 12 spaces to sit
11891    // inside the `When CProg` arm of the function body (one level shallower than the server's
11892    // `While`-nested main).
11893    let driver_body = pe_driver_body("Return output.");
11894    let indented: String = driver_body
11895        .lines()
11896        .map(|l| {
11897            if l.is_empty() {
11898                String::new()
11899            } else {
11900                format!("            {l}")
11901            }
11902        })
11903        .collect::<Vec<_>>()
11904        .join("\n");
11905    let func = format!(
11906        "## To peSpecializeOnce (__prog: CProgram) -> Text is exported for native:\n    Inspect __prog:\n        When CProg (encFuncs, encMain):\n            Let encodedMain be encMain.\n            Let mutable encodedFuncMap be a new Map of Text to CFunc.\n            Repeat for __f in encFuncs:\n                Inspect __f:\n                    When CFuncDef (__nm, __ps, __pt, __rt, __bd):\n                        Set item __nm of encodedFuncMap to __f.\n                    Otherwise:\n                        Let __skip be true.\n{indented}\n        Otherwise:\n            Return \"\".\n"
11907    );
11908    format!(
11909        "{}\n{}\n{}\n{}\n## Main\n    Let __x be 0.\n",
11910        core, pe, decompile, func
11911    )
11912}
11913
11914use crate::interpreter::RuntimeValue;
11915
11916// ── Native Core-IR value builder ───────────────────────────────────────────────────────────
11917// Builds the `CProgram` VALUE directly in Rust — no interpreter, no re-parse of the 140-line
11918// CORE_TYPES type context (the marshal's dominant cost). Mirrors `encode_expr_src`/`encode_stmt_src`
11919// but emits `RuntimeValue::Inductive` (constructor + fields IN DECLARATION ORDER). The `inductive_type`
11920// is a placeholder: the native `CProgram::wire_decode` dispatches on the constructor and ignores the
11921// type name. Any construct not covered here returns `None`, and the caller falls back to the proven
11922// interpreter path — so a gap is slower, never wrong. Residual-equivalence with the interpreter path
11923// is locked by `native_pe_wire` + the `pe_jones_fuzz` corpus.
11924
11925/// The Core-IR ENUM a constructor belongs to — so the built value's `inductive_type` matches what
11926/// the interpreter records (`a new CInt` → `Inductive{ inductive_type: "CExpr", constructor: "CInt" }`),
11927/// making the native builder's wire bytes byte-identical to the interpreter path. The native decoder
11928/// ignores this field, but matching it keeps every byte-level lock exact.
11929fn cv_enum(ctor: &str) -> &'static str {
11930    match ctor {
11931        "CProg" => "CProgram",
11932        "CFuncDef" => "CFunc",
11933        "CLiteralPart" | "CExprPart" => "CStringPart",
11934        "CInt"
11935        | "CBool"
11936        | "CText"
11937        | "CFloat"
11938        | "CVar"
11939        | "CBinOp"
11940        | "CNot"
11941        | "CCall"
11942        | "CIndex"
11943        | "CLen"
11944        | "CMapGet"
11945        | "CList"
11946        | "CTuple"
11947        | "CRange"
11948        | "CSlice"
11949        | "CCopy"
11950        | "CContains"
11951        | "CUnion"
11952        | "CIntersection"
11953        | "COptionSome"
11954        | "COptionNone"
11955        | "CNewSeq"
11956        | "CNewSet"
11957        | "CNew"
11958        | "CNewVariant"
11959        | "CInterpolatedString"
11960        | "CClosure"
11961        | "CDuration"
11962        | "CCallExpr"
11963        | "CChunkAt"
11964        | "CEscExpr"
11965        | "CManifestOf" => "CExpr",
11966        "CSelectRecv" | "CSelectTimeout" => "CSelectBranch",
11967        _ => "CStmt",
11968    }
11969}
11970
11971fn cv_ind(ctor: &str, args: Vec<RuntimeValue>) -> RuntimeValue {
11972    RuntimeValue::Inductive(std::rc::Rc::new(crate::interpreter::InductiveValue {
11973        inductive_type: cv_enum(ctor).to_string(),
11974        constructor: ctor.to_string(),
11975        args,
11976    }))
11977}
11978fn cv_text(s: &str) -> RuntimeValue {
11979    RuntimeValue::Text(std::rc::Rc::new(s.to_string()))
11980}
11981fn cv_list(items: Vec<RuntimeValue>) -> RuntimeValue {
11982    RuntimeValue::List(std::rc::Rc::new(std::cell::RefCell::new(
11983        crate::interpreter::ListRepr::from_values(items),
11984    )))
11985}
11986
11987/// The binary-operator spelling — IDENTICAL to `encode_expr_src`'s `op_str` (the residual re-parses it).
11988fn cv_binop_str(op: BinaryOpKind) -> &'static str {
11989    match op {
11990        BinaryOpKind::Add => "+",
11991        BinaryOpKind::Subtract => "-",
11992        BinaryOpKind::Multiply => "*",
11993        BinaryOpKind::Divide | BinaryOpKind::ExactDivide => "/",
11994        BinaryOpKind::FloorDivide => "//",
11995        BinaryOpKind::Modulo => "%",
11996        BinaryOpKind::Eq => "==",
11997        BinaryOpKind::NotEq => "!=",
11998        BinaryOpKind::Lt => "<",
11999        BinaryOpKind::Gt => ">",
12000        BinaryOpKind::LtEq => "<=",
12001        BinaryOpKind::GtEq => ">=",
12002        BinaryOpKind::And => "&&",
12003        BinaryOpKind::Or => "||",
12004        BinaryOpKind::Concat => "+",
12005        BinaryOpKind::SeqConcat => "followed by",
12006        BinaryOpKind::ApproxEq => "is approximately",
12007        BinaryOpKind::Pow => "**",
12008        BinaryOpKind::BitXor => "^",
12009        BinaryOpKind::BitAnd => "&",
12010        BinaryOpKind::BitOr => "|",
12011        BinaryOpKind::Shl => "<<",
12012        BinaryOpKind::Shr => ">>",
12013    }
12014}
12015
12016type VCtors = std::collections::HashMap<String, Vec<String>>;
12017
12018/// A backend for the Core-IR builder. ONE generic AST traversal (`expr_to_core` / `stmt_to_core` /
12019/// `build_core`) drives EITHER the reference tree builder ([`TreeSink`] → a `RuntimeValue`, the form
12020/// `encode_value_raw` serializes) OR the single-pass wire emitter ([`WireSink`] → exactly those
12021/// `encode_value_raw` bytes with NO intermediate `RuntimeValue` tree and NO second encode walk).
12022/// Byte-identity of the two backends is locked by `native_builder_is_byte_identical_to_the_interpreter`
12023/// and the single-pass tests — so there is no way for them to silently diverge.
12024trait CoreSink {
12025    type Val;
12026    fn int(n: i64) -> Self::Val;
12027    fn boolean(b: bool) -> Self::Val;
12028    fn float(f: f64) -> Self::Val;
12029    fn text(s: &str) -> Self::Val;
12030    fn list(items: Vec<Self::Val>) -> Self::Val;
12031    fn inductive(ctor: &str, args: Vec<Self::Val>) -> Self::Val;
12032}
12033
12034/// Builds the reference `RuntimeValue` Core-IR tree (what `encode_value_raw` serializes).
12035struct TreeSink;
12036impl CoreSink for TreeSink {
12037    type Val = RuntimeValue;
12038    fn int(n: i64) -> RuntimeValue {
12039        RuntimeValue::Int(n)
12040    }
12041    fn boolean(b: bool) -> RuntimeValue {
12042        RuntimeValue::Bool(b)
12043    }
12044    fn float(f: f64) -> RuntimeValue {
12045        RuntimeValue::Float(f)
12046    }
12047    fn text(s: &str) -> RuntimeValue {
12048        cv_text(s)
12049    }
12050    fn list(items: Vec<RuntimeValue>) -> RuntimeValue {
12051        cv_list(items)
12052    }
12053    fn inductive(ctor: &str, args: Vec<RuntimeValue>) -> RuntimeValue {
12054        cv_ind(ctor, args)
12055    }
12056}
12057
12058/// Emits the wire bytes DIRECTLY — byte-for-byte what `encode_value_raw` (flat lists, structure off,
12059/// dedup off) produces for the equivalent [`TreeSink`] value, but with no `RuntimeValue` allocation
12060/// and no second walk. Each node returns its own encoded bytes; a parent writes its header then
12061/// concatenates its children. The `logicaffeine_data::wire` primitives are proven byte-identical to
12062/// the peer `native_encode` by `peer_and_wire_core_produce_identical_bytes`.
12063struct WireSink;
12064impl CoreSink for WireSink {
12065    type Val = Vec<u8>;
12066    fn int(n: i64) -> Vec<u8> {
12067        let mut v = Vec::with_capacity(4);
12068        v.push(logicaffeine_data::wire::T_INT);
12069        logicaffeine_data::wire::write_uvarint(logicaffeine_data::wire::zigzag(n), &mut v);
12070        v
12071    }
12072    fn boolean(b: bool) -> Vec<u8> {
12073        vec![if b {
12074            logicaffeine_data::wire::T_TRUE
12075        } else {
12076            logicaffeine_data::wire::T_FALSE
12077        }]
12078    }
12079    fn float(f: f64) -> Vec<u8> {
12080        let mut v = Vec::with_capacity(9);
12081        v.push(logicaffeine_data::wire::T_FLOAT);
12082        v.extend_from_slice(&f.to_le_bytes());
12083        v
12084    }
12085    fn text(s: &str) -> Vec<u8> {
12086        let mut v = Vec::with_capacity(2 + s.len());
12087        v.push(logicaffeine_data::wire::T_TEXT);
12088        logicaffeine_data::wire::write_str(s, &mut v);
12089        v
12090    }
12091    fn list(items: Vec<Vec<u8>>) -> Vec<u8> {
12092        let mut v = Vec::new();
12093        v.push(logicaffeine_data::wire::T_LIST);
12094        logicaffeine_data::wire::write_uvarint(items.len() as u64, &mut v);
12095        for it in &items {
12096            v.extend_from_slice(it);
12097        }
12098        v
12099    }
12100    fn inductive(ctor: &str, args: Vec<Vec<u8>>) -> Vec<u8> {
12101        let mut v = Vec::new();
12102        logicaffeine_data::wire::write_inductive_header(
12103            &mut v,
12104            cv_enum(ctor),
12105            ctor,
12106            args.len() as u64,
12107        );
12108        for a in &args {
12109            v.extend_from_slice(a);
12110        }
12111        v
12112    }
12113}
12114
12115fn exprs_to_core<S: CoreSink>(
12116    args: &[&Expr],
12117    interner: &Interner,
12118    vctors: &VCtors,
12119) -> Option<Vec<S::Val>> {
12120    let mut out = Vec::with_capacity(args.len());
12121    for a in args {
12122        out.push(expr_to_core::<S>(a, interner, vctors)?);
12123    }
12124    Some(out)
12125}
12126
12127fn expr_to_core<S: CoreSink>(expr: &Expr, interner: &Interner, vctors: &VCtors) -> Option<S::Val> {
12128    Some(match expr {
12129        Expr::Literal(Literal::Number(n)) => S::inductive("CInt", vec![S::int(*n)]),
12130        Expr::Literal(Literal::Boolean(b)) => S::inductive("CBool", vec![S::boolean(*b)]),
12131        Expr::Literal(Literal::Text(s)) => {
12132            S::inductive("CText", vec![S::text(interner.resolve(*s))])
12133        }
12134        Expr::Literal(Literal::Float(f)) => S::inductive("CFloat", vec![S::float(*f)]),
12135        // A duration literal (`1 seconds`, `500 milliseconds`) → `CDuration{amount = CInt(ms), unit}`,
12136        // normalized to milliseconds exactly as the reference does (used by `Sleep` and `Select`'s
12137        // `After …` timeout).
12138        Expr::Literal(Literal::Duration(nanos)) => S::inductive(
12139            "CDuration",
12140            vec![
12141                S::inductive("CInt", vec![S::int(nanos / 1_000_000)]),
12142                S::text("milliseconds"),
12143            ],
12144        ),
12145        Expr::Literal(Literal::Nothing) => S::inductive("CText", vec![S::text("nothing")]),
12146        Expr::Identifier(sym) => S::inductive("CVar", vec![S::text(interner.resolve(*sym))]),
12147        Expr::BinaryOp { op, left, right } => S::inductive(
12148            "CBinOp",
12149            vec![
12150                S::text(cv_binop_str(*op)),
12151                expr_to_core::<S>(left, interner, vctors)?,
12152                expr_to_core::<S>(right, interner, vctors)?,
12153            ],
12154        ),
12155        Expr::Not { operand } => {
12156            S::inductive("CNot", vec![expr_to_core::<S>(operand, interner, vctors)?])
12157        }
12158        Expr::Call { function, args } => {
12159            let fn_name = interner.resolve(*function);
12160            if let Some(field_names) = vctors.get(fn_name) {
12161                // Variant constructor call → CNewVariant (field names from the type registry).
12162                let mut fnames: Vec<S::Val> = Vec::with_capacity(args.len());
12163                let mut fvals: Vec<S::Val> = Vec::with_capacity(args.len());
12164                for (i, a) in args.iter().enumerate() {
12165                    fnames.push(S::text(
12166                        field_names.get(i).map(|s| s.as_str()).unwrap_or("value"),
12167                    ));
12168                    fvals.push(expr_to_core::<S>(a, interner, vctors)?);
12169                }
12170                S::inductive(
12171                    "CNewVariant",
12172                    vec![S::text(fn_name), S::list(fnames), S::list(fvals)],
12173                )
12174            } else {
12175                let avals = exprs_to_core::<S>(args, interner, vctors)?;
12176                S::inductive("CCall", vec![S::text(fn_name), S::list(avals)])
12177            }
12178        }
12179        Expr::Index { collection, index } => S::inductive(
12180            "CIndex",
12181            vec![
12182                expr_to_core::<S>(collection, interner, vctors)?,
12183                expr_to_core::<S>(index, interner, vctors)?,
12184            ],
12185        ),
12186        Expr::Length { collection } => S::inductive(
12187            "CLen",
12188            vec![expr_to_core::<S>(collection, interner, vctors)?],
12189        ),
12190        Expr::FieldAccess { object, field } => S::inductive(
12191            "CMapGet",
12192            vec![
12193                expr_to_core::<S>(object, interner, vctors)?,
12194                S::inductive("CText", vec![S::text(interner.resolve(*field))]),
12195            ],
12196        ),
12197        Expr::List(elems) => {
12198            let mut items: Vec<S::Val> = Vec::with_capacity(elems.len());
12199            for e in elems.iter() {
12200                items.push(expr_to_core::<S>(e, interner, vctors)?);
12201            }
12202            S::inductive("CList", vec![S::list(items)])
12203        }
12204        Expr::Tuple(elems) => {
12205            let mut items: Vec<S::Val> = Vec::with_capacity(elems.len());
12206            for e in elems.iter() {
12207                items.push(expr_to_core::<S>(e, interner, vctors)?);
12208            }
12209            S::inductive("CTuple", vec![S::list(items)])
12210        }
12211        Expr::Range { start, end } => S::inductive(
12212            "CRange",
12213            vec![
12214                expr_to_core::<S>(start, interner, vctors)?,
12215                expr_to_core::<S>(end, interner, vctors)?,
12216            ],
12217        ),
12218        Expr::Slice {
12219            collection,
12220            start,
12221            end,
12222        } => S::inductive(
12223            "CSlice",
12224            vec![
12225                expr_to_core::<S>(collection, interner, vctors)?,
12226                expr_to_core::<S>(start, interner, vctors)?,
12227                expr_to_core::<S>(end, interner, vctors)?,
12228            ],
12229        ),
12230        Expr::Copy { expr } => {
12231            S::inductive("CCopy", vec![expr_to_core::<S>(expr, interner, vctors)?])
12232        }
12233        Expr::Contains { collection, value } => S::inductive(
12234            "CContains",
12235            vec![
12236                expr_to_core::<S>(collection, interner, vctors)?,
12237                expr_to_core::<S>(value, interner, vctors)?,
12238            ],
12239        ),
12240        Expr::Union { left, right } => S::inductive(
12241            "CUnion",
12242            vec![
12243                expr_to_core::<S>(left, interner, vctors)?,
12244                expr_to_core::<S>(right, interner, vctors)?,
12245            ],
12246        ),
12247        Expr::Intersection { left, right } => S::inductive(
12248            "CIntersection",
12249            vec![
12250                expr_to_core::<S>(left, interner, vctors)?,
12251                expr_to_core::<S>(right, interner, vctors)?,
12252            ],
12253        ),
12254        Expr::OptionSome { value } => S::inductive(
12255            "COptionSome",
12256            vec![expr_to_core::<S>(value, interner, vctors)?],
12257        ),
12258        Expr::OptionNone => S::inductive("COptionNone", vec![]),
12259        Expr::InterpolatedString(parts) => {
12260            if parts.is_empty() {
12261                S::inductive("CText", vec![S::text("")])
12262            } else {
12263                let mut pvals: Vec<S::Val> = Vec::with_capacity(parts.len());
12264                for part in parts {
12265                    pvals.push(match part {
12266                        StringPart::Literal(sym) => {
12267                            S::inductive("CLiteralPart", vec![S::text(interner.resolve(*sym))])
12268                        }
12269                        StringPart::Expr { value, .. } => S::inductive(
12270                            "CExprPart",
12271                            vec![expr_to_core::<S>(value, interner, vctors)?],
12272                        ),
12273                    });
12274                }
12275                S::inductive("CInterpolatedString", vec![S::list(pvals)])
12276            }
12277        }
12278        Expr::NewVariant {
12279            variant, fields, ..
12280        } => {
12281            let mut fnames: Vec<S::Val> = Vec::with_capacity(fields.len());
12282            let mut fvals: Vec<S::Val> = Vec::with_capacity(fields.len());
12283            for (fname, fexpr) in fields {
12284                fnames.push(S::text(interner.resolve(*fname)));
12285                fvals.push(expr_to_core::<S>(fexpr, interner, vctors)?);
12286            }
12287            S::inductive(
12288                "CNewVariant",
12289                vec![
12290                    S::text(interner.resolve(*variant)),
12291                    S::list(fnames),
12292                    S::list(fvals),
12293                ],
12294            )
12295        }
12296        Expr::New {
12297            type_name,
12298            init_fields,
12299            ..
12300        } => {
12301            let tn = interner.resolve(*type_name);
12302            if tn == "Seq" || tn == "List" {
12303                S::inductive("CNewSeq", vec![])
12304            } else if tn == "Set" {
12305                S::inductive("CNewSet", vec![])
12306            } else if tn == "Map" || tn.starts_with("Map ") {
12307                S::inductive(
12308                    "CNew",
12309                    vec![S::text("Map"), S::list(vec![]), S::list(vec![])],
12310                )
12311            } else if init_fields.is_empty() {
12312                S::inductive(
12313                    "CNewVariant",
12314                    vec![S::text(tn), S::list(vec![]), S::list(vec![])],
12315                )
12316            } else {
12317                let mut fnames: Vec<S::Val> = Vec::with_capacity(init_fields.len());
12318                let mut fvals: Vec<S::Val> = Vec::with_capacity(init_fields.len());
12319                for (fname, fexpr) in init_fields {
12320                    fnames.push(S::text(interner.resolve(*fname)));
12321                    fvals.push(expr_to_core::<S>(fexpr, interner, vctors)?);
12322                }
12323                S::inductive("CNew", vec![S::text(tn), S::list(fnames), S::list(fvals)])
12324            }
12325        }
12326        // Closure: params (Seq Text), body (Seq CStmt), captured free vars (Seq Text, SORTED to
12327        // match the now-deterministic reference encoder). An expression body wraps as `CReturn e`.
12328        Expr::Closure { params, body, .. } => {
12329            let mut bound: std::collections::HashSet<String> = std::collections::HashSet::new();
12330            let mut param_vals: Vec<S::Val> = Vec::with_capacity(params.len());
12331            for (sym, _) in params {
12332                let name = interner.resolve(*sym);
12333                bound.insert(name.to_string());
12334                param_vals.push(S::text(name));
12335            }
12336            let body_vals: Vec<S::Val> = match body {
12337                ClosureBody::Expression(e) => {
12338                    vec![S::inductive(
12339                        "CReturn",
12340                        vec![expr_to_core::<S>(e, interner, vctors)?],
12341                    )]
12342                }
12343                ClosureBody::Block(stmts) => {
12344                    let mut bv: Vec<S::Val> = Vec::with_capacity(stmts.len());
12345                    for s in stmts.iter() {
12346                        // The reference encodes body stmts with the single-stmt encoder, which
12347                        // defers Inspect/Repeat to empty; fall back rather than replicate that quirk.
12348                        if matches!(s, Stmt::Inspect { .. } | Stmt::Repeat { .. }) {
12349                            return None;
12350                        }
12351                        bv.push(stmt_to_core::<S>(s, interner, vctors)?);
12352                    }
12353                    bv
12354                }
12355            };
12356            let mut free: Vec<String> = collect_free_vars_expr(expr, interner, &bound)
12357                .into_iter()
12358                .collect();
12359            free.sort();
12360            let cap_vals: Vec<S::Val> = free.iter().map(|fv| S::text(fv)).collect();
12361            S::inductive(
12362                "CClosure",
12363                vec![S::list(param_vals), S::list(body_vals), S::list(cap_vals)],
12364            )
12365        }
12366        // A callee-expression call (`(f)(x)`) → `CCallExpr{target, args}`.
12367        Expr::CallExpr { callee, args } => {
12368            let mut avals: Vec<S::Val> = Vec::with_capacity(args.len());
12369            for a in args.iter() {
12370                avals.push(expr_to_core::<S>(a, interner, vctors)?);
12371            }
12372            S::inductive(
12373                "CCallExpr",
12374                vec![expr_to_core::<S>(callee, interner, vctors)?, S::list(avals)],
12375            )
12376        }
12377        Expr::ChunkAt { index, zone } => S::inductive(
12378            "CChunkAt",
12379            vec![
12380                expr_to_core::<S>(index, interner, vctors)?,
12381                expr_to_core::<S>(zone, interner, vctors)?,
12382            ],
12383        ),
12384        Expr::ManifestOf { zone } => S::inductive(
12385            "CManifestOf",
12386            vec![expr_to_core::<S>(zone, interner, vctors)?],
12387        ),
12388        Expr::Escape { code, .. } => {
12389            S::inductive("CEscExpr", vec![S::text(interner.resolve(*code))])
12390        }
12391        // `Give`/`WithCapacity` are transparent: the reference encodes the inner value with no node
12392        // (an ownership move / an allocation hint the interpreter erases).
12393        Expr::Give { value } => expr_to_core::<S>(value, interner, vctors)?,
12394        Expr::WithCapacity { value, .. } => expr_to_core::<S>(value, interner, vctors)?,
12395        _ => return None,
12396    })
12397}
12398
12399fn stmt_to_core<S: CoreSink>(stmt: &Stmt, interner: &Interner, vctors: &VCtors) -> Option<S::Val> {
12400    Some(match stmt {
12401        Stmt::Let { var, value, .. } => S::inductive(
12402            "CLet",
12403            vec![
12404                S::text(interner.resolve(*var)),
12405                expr_to_core::<S>(value, interner, vctors)?,
12406            ],
12407        ),
12408        Stmt::Set { target, value } => S::inductive(
12409            "CSet",
12410            vec![
12411                S::text(interner.resolve(*target)),
12412                expr_to_core::<S>(value, interner, vctors)?,
12413            ],
12414        ),
12415        Stmt::Show { object, .. } => {
12416            S::inductive("CShow", vec![expr_to_core::<S>(object, interner, vctors)?])
12417        }
12418        Stmt::SetIndex {
12419            collection,
12420            index,
12421            value,
12422        } => S::inductive(
12423            "CSetIdx",
12424            vec![
12425                S::text(&extract_ident_name(collection, interner)),
12426                expr_to_core::<S>(index, interner, vctors)?,
12427                expr_to_core::<S>(value, interner, vctors)?,
12428            ],
12429        ),
12430        Stmt::SetField {
12431            object,
12432            field,
12433            value,
12434        } => S::inductive(
12435            "CMapSet",
12436            vec![
12437                S::text(&extract_ident_name(object, interner)),
12438                S::inductive("CText", vec![S::text(interner.resolve(*field))]),
12439                expr_to_core::<S>(value, interner, vctors)?,
12440            ],
12441        ),
12442        Stmt::Pop { collection, .. } => S::inductive(
12443            "CPop",
12444            vec![S::text(&extract_ident_name(collection, interner))],
12445        ),
12446        Stmt::Give { object, recipient } => S::inductive(
12447            "CGive",
12448            vec![
12449                expr_to_core::<S>(object, interner, vctors)?,
12450                S::text(&extract_ident_name(recipient, interner)),
12451            ],
12452        ),
12453        Stmt::Sleep { milliseconds } => S::inductive(
12454            "CSleep",
12455            vec![expr_to_core::<S>(milliseconds, interner, vctors)?],
12456        ),
12457        Stmt::RuntimeAssert {
12458            condition,
12459            hard,
12460            dim: _,
12461            reason,
12462        } => S::inductive(
12463            if *hard {
12464                "CHardAssert"
12465            } else {
12466                "CRuntimeAssert"
12467            },
12468            vec![
12469                expr_to_core::<S>(condition, interner, vctors)?,
12470                match reason {
12471                    Some(r) => expr_to_core::<S>(r, interner, vctors)?,
12472                    None => S::inductive("CText", vec![S::text("assertion failed")]),
12473                },
12474            ],
12475        ),
12476        Stmt::Fail { reason } => S::inductive(
12477            "CHardAssert",
12478            vec![
12479                S::inductive("CBool", vec![S::boolean(false)]),
12480                expr_to_core::<S>(reason, interner, vctors)?,
12481            ],
12482        ),
12483        Stmt::Return { value } => {
12484            let e = match value {
12485                Some(v) => expr_to_core::<S>(v, interner, vctors)?,
12486                None => S::inductive("CInt", vec![S::int(0)]),
12487            };
12488            S::inductive("CReturn", vec![e])
12489        }
12490        Stmt::Break => S::inductive("CBreak", vec![]),
12491        Stmt::If {
12492            cond,
12493            then_block,
12494            else_block,
12495        } => {
12496            let cond_v = expr_to_core::<S>(cond, interner, vctors)?;
12497            let then_s: Vec<&Stmt> = then_block.iter().collect();
12498            let then_v = stmt_list_to_core::<S>(&then_s, interner, vctors)?;
12499            let else_v = match else_block {
12500                Some(els) => {
12501                    let else_s: Vec<&Stmt> = els.iter().collect();
12502                    stmt_list_to_core::<S>(&else_s, interner, vctors)?
12503                }
12504                None => S::list(vec![]),
12505            };
12506            S::inductive("CIf", vec![cond_v, then_v, else_v])
12507        }
12508        Stmt::While { cond, body, .. } => {
12509            let cond_v = expr_to_core::<S>(cond, interner, vctors)?;
12510            let body_s: Vec<&Stmt> = body.iter().collect();
12511            S::inductive(
12512                "CWhile",
12513                vec![cond_v, stmt_list_to_core::<S>(&body_s, interner, vctors)?],
12514            )
12515        }
12516        Stmt::Call { function, args } => {
12517            let mut avals: Vec<S::Val> = Vec::with_capacity(args.len());
12518            for a in args {
12519                avals.push(expr_to_core::<S>(a, interner, vctors)?);
12520            }
12521            S::inductive(
12522                "CCallS",
12523                vec![S::text(interner.resolve(*function)), S::list(avals)],
12524            )
12525        }
12526        Stmt::Push { value, collection } => S::inductive(
12527            "CPush",
12528            vec![
12529                expr_to_core::<S>(value, interner, vctors)?,
12530                S::text(&extract_ident_name(collection, interner)),
12531            ],
12532        ),
12533        Stmt::Repeat {
12534            pattern,
12535            iterable,
12536            body,
12537            ..
12538        } => {
12539            let loop_var = match pattern {
12540                Pattern::Identifier(sym) => interner.resolve(*sym).to_string(),
12541                Pattern::Tuple(syms) => syms
12542                    .first()
12543                    .map(|s| interner.resolve(*s).to_string())
12544                    .unwrap_or_else(|| "item".to_string()),
12545            };
12546            let body_s: Vec<&Stmt> = body.iter().collect();
12547            let body_v = stmt_list_to_core::<S>(&body_s, interner, vctors)?;
12548            if let Expr::Range { start, end } = iterable {
12549                S::inductive(
12550                    "CRepeatRange",
12551                    vec![
12552                        S::text(&loop_var),
12553                        expr_to_core::<S>(start, interner, vctors)?,
12554                        expr_to_core::<S>(end, interner, vctors)?,
12555                        body_v,
12556                    ],
12557                )
12558            } else {
12559                S::inductive(
12560                    "CRepeat",
12561                    vec![
12562                        S::text(&loop_var),
12563                        expr_to_core::<S>(iterable, interner, vctors)?,
12564                        body_v,
12565                    ],
12566                )
12567            }
12568        }
12569        // CRDT ops (mirror `encode_stmt_src`; declaration order from CORE_TYPES_FOR_PE).
12570        Stmt::Add { value, collection } => S::inductive(
12571            "CAdd",
12572            vec![
12573                expr_to_core::<S>(value, interner, vctors)?,
12574                S::text(&extract_ident_name(collection, interner)),
12575            ],
12576        ),
12577        Stmt::Remove { value, collection } => S::inductive(
12578            "CRemove",
12579            vec![
12580                expr_to_core::<S>(value, interner, vctors)?,
12581                S::text(&extract_ident_name(collection, interner)),
12582            ],
12583        ),
12584        Stmt::MergeCrdt { source, target } => S::inductive(
12585            "CMerge",
12586            vec![
12587                S::text(&extract_ident_name(target, interner)),
12588                expr_to_core::<S>(source, interner, vctors)?,
12589            ],
12590        ),
12591        // The IDEMPOTENT sibling — a distinct `CJoin` core node so the self-hosted PE preserves the join.
12592        Stmt::JoinCrdt { source, target } => S::inductive(
12593            "CJoin",
12594            vec![
12595                S::text(&extract_ident_name(target, interner)),
12596                expr_to_core::<S>(source, interner, vctors)?,
12597            ],
12598        ),
12599        Stmt::IncreaseCrdt {
12600            object,
12601            field,
12602            amount,
12603        } => S::inductive(
12604            "CIncrease",
12605            vec![
12606                S::text(&format!(
12607                    "{}'s {}",
12608                    extract_ident_name(object, interner),
12609                    interner.resolve(*field)
12610                )),
12611                expr_to_core::<S>(amount, interner, vctors)?,
12612            ],
12613        ),
12614        Stmt::DecreaseCrdt {
12615            object,
12616            field,
12617            amount,
12618        } => S::inductive(
12619            "CDecrease",
12620            vec![
12621                S::text(&format!(
12622                    "{}'s {}",
12623                    extract_ident_name(object, interner),
12624                    interner.resolve(*field)
12625                )),
12626                expr_to_core::<S>(amount, interner, vctors)?,
12627            ],
12628        ),
12629        // Task launch (both handled forms; body is a single `CCallS`, handle defaults to `_task`).
12630        Stmt::LaunchTask { function, args } | Stmt::LaunchTaskWithHandle { function, args, .. } => {
12631            let func_name = interner.resolve(*function);
12632            let mut avals: Vec<S::Val> = Vec::with_capacity(args.len());
12633            for a in args {
12634                avals.push(expr_to_core::<S>(a, interner, vctors)?);
12635            }
12636            let call = S::inductive("CCallS", vec![S::text(func_name), S::list(avals)]);
12637            let body = S::list(vec![call]);
12638            let handle_name = if let Stmt::LaunchTaskWithHandle { handle, .. } = stmt {
12639                interner.resolve(*handle).to_string()
12640            } else {
12641                "_task".to_string()
12642            };
12643            S::inductive("CLaunchTask", vec![body, S::text(&handle_name)])
12644        }
12645        // Concurrency: one branch (Seq of CStmt) per task. The reference encodes each task with the
12646        // single-stmt encoder, which defers Inspect/Repeat to an EMPTY branch; rather than replicate
12647        // that quirk, fall back the whole program if a task is one of those.
12648        Stmt::Concurrent { tasks } => {
12649            let mut branches: Vec<S::Val> = Vec::with_capacity(tasks.len());
12650            for task in tasks.iter() {
12651                if matches!(task, Stmt::Inspect { .. } | Stmt::Repeat { .. }) {
12652                    return None;
12653                }
12654                branches.push(S::list(vec![stmt_to_core::<S>(task, interner, vctors)?]));
12655            }
12656            S::inductive("CConcurrent", vec![S::list(branches)])
12657        }
12658        Stmt::Parallel { tasks } => {
12659            let mut branches: Vec<S::Val> = Vec::with_capacity(tasks.len());
12660            for task in tasks.iter() {
12661                if matches!(task, Stmt::Inspect { .. } | Stmt::Repeat { .. }) {
12662                    return None;
12663                }
12664                branches.push(S::list(vec![stmt_to_core::<S>(task, interner, vctors)?]));
12665            }
12666            S::inductive("CParallel", vec![S::list(branches)])
12667        }
12668        // Sequence append (`Append x to d's lines`) — the base struct is forced dynamic at the list
12669        // level (see `stmt_list_to_vec`); here just the op. `target` round-trips as surface syntax.
12670        Stmt::AppendToSequence { sequence, value } => S::inductive(
12671            "CAppendToSeq",
12672            vec![
12673                S::text(&extract_ident_name(sequence, interner)),
12674                expr_to_core::<S>(value, interner, vctors)?,
12675            ],
12676        ),
12677        // Pipes / channels. Capacity is a `CInt` expression node (default 32, matching the reference).
12678        Stmt::CreatePipe {
12679            var: pipe_var,
12680            capacity,
12681            ..
12682        } => {
12683            let cap = capacity.unwrap_or(32);
12684            S::inductive(
12685                "CCreatePipe",
12686                vec![
12687                    S::text(interner.resolve(*pipe_var)),
12688                    S::inductive("CInt", vec![S::int(cap as i64)]),
12689                ],
12690            )
12691        }
12692        Stmt::SendPipe { value, pipe } => S::inductive(
12693            "CSendPipe",
12694            vec![
12695                S::text(&pipe_ident_name(pipe, interner)),
12696                expr_to_core::<S>(value, interner, vctors)?,
12697            ],
12698        ),
12699        Stmt::ReceivePipe {
12700            var: recv_var,
12701            pipe,
12702        } => S::inductive(
12703            "CReceivePipe",
12704            vec![
12705                S::text(&pipe_ident_name(pipe, interner)),
12706                S::text(interner.resolve(*recv_var)),
12707            ],
12708        ),
12709        Stmt::TrySendPipe { value, pipe, .. } => S::inductive(
12710            "CTrySendPipe",
12711            vec![
12712                S::text(&pipe_ident_name(pipe, interner)),
12713                expr_to_core::<S>(value, interner, vctors)?,
12714            ],
12715        ),
12716        Stmt::TryReceivePipe {
12717            var: recv_var,
12718            pipe,
12719        } => S::inductive(
12720            "CTryReceivePipe",
12721            vec![
12722                S::text(&pipe_ident_name(pipe, interner)),
12723                S::text(interner.resolve(*recv_var)),
12724            ],
12725        ),
12726        // Select over channels: one `CSelectRecv{chan,var,body}` or `CSelectTimeout{duration,body}`
12727        // per branch. Branch bodies use the single-stmt encoder (fall back on Inspect/Repeat).
12728        Stmt::Select { branches } => {
12729            let mut bvals: Vec<S::Val> = Vec::with_capacity(branches.len());
12730            for branch in branches.iter() {
12731                match branch {
12732                    SelectBranch::Receive {
12733                        var: recv_var,
12734                        pipe,
12735                        body,
12736                    } => bvals.push(S::inductive(
12737                        "CSelectRecv",
12738                        vec![
12739                            S::text(&pipe_ident_name(pipe, interner)),
12740                            S::text(interner.resolve(*recv_var)),
12741                            select_body_to_core::<S>(body, interner, vctors)?,
12742                        ],
12743                    )),
12744                    SelectBranch::Timeout { milliseconds, body } => bvals.push(S::inductive(
12745                        "CSelectTimeout",
12746                        vec![
12747                            expr_to_core::<S>(milliseconds, interner, vctors)?,
12748                            select_body_to_core::<S>(body, interner, vctors)?,
12749                        ],
12750                    )),
12751                }
12752            }
12753            S::inductive("CSelect", vec![S::list(bvals)])
12754        }
12755        // Proof / verification directives — the proposition/predicate is erased to `CBool(true)`
12756        // (it has no runtime effect to specialize; only its shape survives into the residual).
12757        Stmt::Assert { .. } => S::inductive(
12758            "CAssert",
12759            vec![S::inductive("CBool", vec![S::boolean(true)])],
12760        ),
12761        Stmt::Check { source_text, .. } => S::inductive(
12762            "CCheck",
12763            vec![
12764                S::inductive("CBool", vec![S::boolean(true)]),
12765                S::inductive("CText", vec![S::text(source_text)]),
12766            ],
12767        ),
12768        Stmt::Trust { justification, .. } => S::inductive(
12769            "CTrust",
12770            vec![
12771                S::inductive("CBool", vec![S::boolean(true)]),
12772                S::text(interner.resolve(*justification)),
12773            ],
12774        ),
12775        Stmt::Require { crate_name, .. } => {
12776            S::inductive("CRequire", vec![S::text(interner.resolve(*crate_name))])
12777        }
12778        // Inline-native escape hatch.
12779        Stmt::Escape { code, .. } => {
12780            S::inductive("CEscStmt", vec![S::text(interner.resolve(*code))])
12781        }
12782        // `Splice` (unconditional inlined block) desugars to `CIf(true, body, [])`.
12783        Stmt::Splice { body } => {
12784            let body_refs: Vec<&Stmt> = body.iter().collect();
12785            S::inductive(
12786                "CIf",
12787                vec![
12788                    S::inductive("CBool", vec![S::boolean(true)]),
12789                    stmt_list_to_core::<S>(&body_refs, interner, vctors)?,
12790                    S::list(vec![]),
12791                ],
12792            )
12793        }
12794        // Task / actor control.
12795        Stmt::StopTask { handle } => S::inductive(
12796            "CStopTask",
12797            vec![expr_to_core::<S>(handle, interner, vctors)?],
12798        ),
12799        Stmt::Spawn { agent_type, name } => S::inductive(
12800            "CSpawn",
12801            vec![
12802                S::text(interner.resolve(*agent_type)),
12803                S::text(interner.resolve(*name)),
12804            ],
12805        ),
12806        // Structured-concurrency zone (kind fixed to "heap"); body via the single-stmt encoder.
12807        Stmt::Zone { name, body, .. } => S::inductive(
12808            "CZone",
12809            vec![
12810                S::text(interner.resolve(*name)),
12811                S::text("heap"),
12812                select_body_to_core::<S>(body, interner, vctors)?,
12813            ],
12814        ),
12815        // CRDT conflict resolution (base struct forced dynamic at the list level, like Increase/Merge).
12816        Stmt::ResolveConflict { object, field, .. } => S::inductive(
12817            "CResolve",
12818            vec![S::text(&format!(
12819                "{}'s {}",
12820                extract_ident_name(object, interner),
12821                interner.resolve(*field)
12822            ))],
12823        ),
12824        // Sync / mount.
12825        Stmt::Sync {
12826            var: sync_var,
12827            topic,
12828        } => S::inductive(
12829            "CSync",
12830            vec![
12831                S::text(interner.resolve(*sync_var)),
12832                expr_to_core::<S>(topic, interner, vctors)?,
12833            ],
12834        ),
12835        Stmt::Mount {
12836            var: mount_var,
12837            path,
12838        } => S::inductive(
12839            "CMount",
12840            vec![
12841                S::text(interner.resolve(*mount_var)),
12842                expr_to_core::<S>(path, interner, vctors)?,
12843            ],
12844        ),
12845        // IO.
12846        Stmt::ReadFrom {
12847            var: read_var,
12848            source,
12849        } => {
12850            let var_name = interner.resolve(*read_var);
12851            match source {
12852                ReadSource::Console => S::inductive("CReadConsole", vec![S::text(var_name)]),
12853                ReadSource::File(path_expr) => S::inductive(
12854                    "CReadFile",
12855                    vec![
12856                        expr_to_core::<S>(path_expr, interner, vctors)?,
12857                        S::text(var_name),
12858                    ],
12859                ),
12860            }
12861        }
12862        Stmt::WriteFile { content, path } => S::inductive(
12863            "CWriteFile",
12864            vec![
12865                expr_to_core::<S>(path, interner, vctors)?,
12866                expr_to_core::<S>(content, interner, vctors)?,
12867            ],
12868        ),
12869        // Networking / messaging. (`LetPeerAgent` encodes as `CConnectTo` with the agent as target.)
12870        Stmt::ConnectTo { address, .. } => S::inductive(
12871            "CConnectTo",
12872            vec![
12873                expr_to_core::<S>(address, interner, vctors)?,
12874                S::text("conn"),
12875            ],
12876        ),
12877        Stmt::Listen { address, .. } => S::inductive(
12878            "CListen",
12879            vec![
12880                expr_to_core::<S>(address, interner, vctors)?,
12881                S::text("default"),
12882            ],
12883        ),
12884        Stmt::SendMessage {
12885            message,
12886            destination,
12887            ..
12888        } => S::inductive(
12889            "CSendMessage",
12890            vec![
12891                expr_to_core::<S>(destination, interner, vctors)?,
12892                expr_to_core::<S>(message, interner, vctors)?,
12893            ],
12894        ),
12895        Stmt::AwaitMessage { into, .. } => {
12896            S::inductive("CAwaitMessage", vec![S::text(interner.resolve(*into))])
12897        }
12898        Stmt::StreamMessage {
12899            values,
12900            destination,
12901        } => S::inductive(
12902            "CStreamMessage",
12903            vec![
12904                expr_to_core::<S>(destination, interner, vctors)?,
12905                expr_to_core::<S>(values, interner, vctors)?,
12906            ],
12907        ),
12908        Stmt::LetPeerAgent {
12909            var: pa_var,
12910            address,
12911        } => S::inductive(
12912            "CConnectTo",
12913            vec![
12914                expr_to_core::<S>(address, interner, vctors)?,
12915                S::text(interner.resolve(*pa_var)),
12916            ],
12917        ),
12918        _ => return None,
12919    })
12920}
12921
12922/// A channel name: a plain identifier, else the literal `"pipe"` (mirrors `encode_stmt_src`).
12923fn pipe_ident_name(pipe: &Expr, interner: &Interner) -> String {
12924    match pipe {
12925        Expr::Identifier(sym) => interner.resolve(*sym).to_string(),
12926        _ => "pipe".to_string(),
12927    }
12928}
12929
12930/// A `Select` branch body: each statement via the SINGLE-statement encoder — the reference defers
12931/// Inspect/Repeat to empty here, so fall back rather than replicate that quirk.
12932fn select_body_to_core<S: CoreSink>(
12933    body: &[Stmt],
12934    interner: &Interner,
12935    vctors: &VCtors,
12936) -> Option<S::Val> {
12937    let mut items: Vec<S::Val> = Vec::with_capacity(body.len());
12938    for s in body.iter() {
12939        if matches!(s, Stmt::Inspect { .. } | Stmt::Repeat { .. }) {
12940            return None;
12941        }
12942        items.push(stmt_to_core::<S>(s, interner, vctors)?);
12943    }
12944    Some(S::list(items))
12945}
12946
12947fn stmt_list_to_core<S: CoreSink>(
12948    stmts: &[&Stmt],
12949    interner: &Interner,
12950    vctors: &VCtors,
12951) -> Option<S::Val> {
12952    Some(S::list(stmt_list_to_vec::<S>(stmts, interner, vctors)?))
12953}
12954
12955/// Flatten a statement list into Core-IR nodes. Most statements map 1:1 via `stmt_to_core`; an
12956/// `Inspect` DESUGARS in place ([`inspect_to_cif`]) into the exact flat `CIf` chain `encode_stmts_src`
12957/// emits — so the PE folds a statically-known match to its single arm, Jones-optimally.
12958fn stmt_list_to_vec<S: CoreSink>(
12959    stmts: &[&Stmt],
12960    interner: &Interner,
12961    vctors: &VCtors,
12962) -> Option<Vec<S::Val>> {
12963    let mut out: Vec<S::Val> = Vec::with_capacity(stmts.len());
12964    for s in stmts {
12965        match s {
12966            Stmt::Inspect { .. } => inspect_to_cif::<S>(s, &mut out, interner, vctors)?,
12967            // A CRDT op forces its base struct DYNAMIC first (so the PE cannot statically fold a
12968            // struct it then mutates), THEN emits the op — a list-level transform mirroring
12969            // `encode_stmts_src`. `crdt_base_var` is `None` for a plain-variable collection (a bare
12970            // `Add x to s`), so those emit no force, exactly like the reference.
12971            Stmt::Add { collection, .. } | Stmt::Remove { collection, .. } => {
12972                if let Some(base) = crdt_base_var(collection, interner) {
12973                    out.push(S::inductive("CForceDynamic", vec![S::text(&base)]));
12974                }
12975                out.push(stmt_to_core::<S>(s, interner, vctors)?);
12976            }
12977            Stmt::AppendToSequence { sequence, .. } => {
12978                if let Some(base) = crdt_base_var(sequence, interner) {
12979                    out.push(S::inductive("CForceDynamic", vec![S::text(&base)]));
12980                }
12981                out.push(stmt_to_core::<S>(s, interner, vctors)?);
12982            }
12983            Stmt::IncreaseCrdt { object, .. }
12984            | Stmt::DecreaseCrdt { object, .. }
12985            | Stmt::ResolveConflict { object, .. } => {
12986                if matches!(object, Expr::Identifier(_) | Expr::FieldAccess { .. }) {
12987                    out.push(S::inductive(
12988                        "CForceDynamic",
12989                        vec![S::text(&crdt_base_var_root(object, interner))],
12990                    ));
12991                }
12992                out.push(stmt_to_core::<S>(s, interner, vctors)?);
12993            }
12994            Stmt::MergeCrdt { target, .. } | Stmt::JoinCrdt { target, .. } => {
12995                if matches!(target, Expr::Identifier(_) | Expr::FieldAccess { .. }) {
12996                    out.push(S::inductive(
12997                        "CForceDynamic",
12998                        vec![S::text(&crdt_base_var_root(target, interner))],
12999                    ));
13000                }
13001                out.push(stmt_to_core::<S>(s, interner, vctors)?);
13002            }
13003            _ => out.push(stmt_to_core::<S>(s, interner, vctors)?),
13004        }
13005    }
13006    Some(out)
13007}
13008
13009thread_local! {
13010    /// Per-program index for the `Inspect`-with-`Otherwise` "did any arm match" flag. Reset at the
13011    /// start of every full-program encode ([`program_to_core`] AND `encode_program_source`); both the
13012    /// native builder and the interpreter reference increment it in the SAME traversal (functions in
13013    /// source order, then main; DFS into bodies), so the Nth such Inspect is named `__inspectMatched_N`
13014    /// identically in both — DETERMINISTIC and collision-free. (The reference formerly named it from
13015    /// its global intermediate counter, whose value the value-based builder cannot reproduce; this
13016    /// dedicated index is the reproducible replacement.)
13017    static INSPECT_OTHERWISE_IDX: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
13018}
13019
13020fn reset_inspect_otherwise_idx() {
13021    INSPECT_OTHERWISE_IDX.with(|c| c.set(0));
13022}
13023
13024/// The next `Inspect`-with-`Otherwise` flag index (post-increment). Called at the START of each such
13025/// Inspect's desugaring in BOTH encoders, so a nested Inspect gets a strictly higher index than its
13026/// enclosing one — no two live flags ever collide.
13027pub fn next_inspect_otherwise_idx() -> usize {
13028    INSPECT_OTHERWISE_IDX.with(|c| {
13029        let v = c.get();
13030        c.set(v + 1);
13031        v
13032    })
13033}
13034
13035/// Desugar `Inspect target: When Variant(field→bind): body … [Otherwise: rest]` into the flat `CIf`
13036/// chain `encode_stmts_src` produces, byte-for-byte. Each variant arm →
13037/// `CIf(target's __tag == "Variant", [<set match flag if Otherwise>; binds; body], [])`; when the PE
13038/// knows the variant it folds the comparison and keeps only the matching arm (zero dispatch =
13039/// Jones-optimal). WITH an `Otherwise`, a `__inspectMatched_N` flag (N = [`next_inspect_otherwise_idx`],
13040/// deterministic in both encoders) is declared false, set true in each arm, and checked negated to run
13041/// the Otherwise body. An `Otherwise`-only inspect just inlines that body.
13042fn inspect_to_cif<S: CoreSink>(
13043    stmt: &Stmt,
13044    out: &mut Vec<S::Val>,
13045    interner: &Interner,
13046    vctors: &VCtors,
13047) -> Option<()> {
13048    let Stmt::Inspect { target, arms, .. } = stmt else {
13049        return None;
13050    };
13051    let has_otherwise = arms.iter().any(|a| a.variant.is_none());
13052    let has_variant = arms.iter().any(|a| a.variant.is_some());
13053
13054    // No variant arms (empty or Otherwise-only): the reference inlines the Otherwise body directly.
13055    if !has_variant {
13056        for arm in arms {
13057            if arm.variant.is_none() {
13058                let body_refs: Vec<&Stmt> = arm.body.iter().collect();
13059                out.extend(stmt_list_to_vec::<S>(&body_refs, interner, vctors)?);
13060            }
13061        }
13062        return Some(());
13063    }
13064
13065    // The match flag is created (and its index reserved) BEFORE the arms — so a nested Inspect in an
13066    // arm/otherwise body gets a strictly higher index, exactly as the reference does.
13067    let matched_name = if has_otherwise {
13068        let name = format!("__inspectMatched_{}", next_inspect_otherwise_idx());
13069        out.push(S::inductive(
13070            "CLet",
13071            vec![
13072                S::text(&name),
13073                S::inductive("CBool", vec![S::boolean(false)]),
13074            ],
13075        ));
13076        Some(name)
13077    } else {
13078        None
13079    };
13080
13081    for arm in arms {
13082        if arm.variant.is_none() {
13083            continue;
13084        }
13085        let variant_name = interner.resolve(arm.variant.unwrap());
13086        let tag_get = S::inductive(
13087            "CMapGet",
13088            vec![
13089                expr_to_core::<S>(target, interner, vctors)?,
13090                S::inductive("CText", vec![S::text("__tag")]),
13091            ],
13092        );
13093        let cond = S::inductive(
13094            "CBinOp",
13095            vec![
13096                S::text("=="),
13097                tag_get,
13098                S::inductive("CText", vec![S::text(variant_name)]),
13099            ],
13100        );
13101        let mut then_items: Vec<S::Val> = Vec::new();
13102        if let Some(ref mname) = matched_name {
13103            then_items.push(S::inductive(
13104                "CSet",
13105                vec![
13106                    S::text(mname),
13107                    S::inductive("CBool", vec![S::boolean(true)]),
13108                ],
13109            ));
13110        }
13111        for (field_name, binding_name) in &arm.bindings {
13112            let field_str = interner.resolve(*field_name);
13113            let bind_str = interner.resolve(*binding_name);
13114            let fget = S::inductive(
13115                "CMapGet",
13116                vec![
13117                    expr_to_core::<S>(target, interner, vctors)?,
13118                    S::inductive("CText", vec![S::text(field_str)]),
13119                ],
13120            );
13121            then_items.push(S::inductive("CLet", vec![S::text(bind_str), fget]));
13122        }
13123        let body_refs: Vec<&Stmt> = arm.body.iter().collect();
13124        then_items.extend(stmt_list_to_vec::<S>(&body_refs, interner, vctors)?);
13125        out.push(S::inductive(
13126            "CIf",
13127            vec![cond, S::list(then_items), S::list(vec![])],
13128        ));
13129    }
13130
13131    // Otherwise: `CIf(not __inspectMatched_N, otherwise_body, [])`.
13132    if let Some(ref mname) = matched_name {
13133        let not_matched = S::inductive("CNot", vec![S::inductive("CVar", vec![S::text(mname)])]);
13134        let mut otherwise_body: Vec<&Stmt> = Vec::new();
13135        for arm in arms {
13136            if arm.variant.is_none() {
13137                otherwise_body = arm.body.iter().collect();
13138            }
13139        }
13140        let ow = stmt_list_to_core::<S>(&otherwise_body, interner, vctors)?;
13141        out.push(S::inductive("CIf", vec![not_matched, ow, S::list(vec![])]));
13142    }
13143    Some(())
13144}
13145
13146/// Whether the native Core-IR value builder covers `program` (the fast marshal path is taken, not
13147/// the interpreter fallback). For test coverage assertions.
13148pub fn program_covered_by_native_builder(program: &str) -> bool {
13149    program_to_core_value(program).is_some()
13150}
13151
13152/// Build the whole `CProgram` value for `program` on the [`TreeSink`] backend, or `None` if it uses
13153/// any construct the native builder does not cover (caller falls back to the interpreter path).
13154fn program_to_core_value(program: &str) -> Option<RuntimeValue> {
13155    program_to_core::<TreeSink>(program)
13156}
13157
13158/// Parse `program` and construct its Core-IR `CProg` on the sink `S` — the shared parse+build spine
13159/// behind both the `RuntimeValue` builder ([`program_to_core_value`], `S = TreeSink`) and the direct
13160/// single-pass wire marshal ([`program_to_core_wire_bytes`], `S = WireSink`). `None` if any construct
13161/// is uncovered. The parse (lex + discovery + `parse_program`) dominates; the sink chooses whether the
13162/// build allocates a `RuntimeValue` tree + a second encode walk or emits bytes in one pass.
13163fn program_to_core<S: CoreSink>(program: &str) -> Option<S::Val> {
13164    reset_inspect_otherwise_idx(); // match the reference's deterministic `__inspectMatched_N` numbering
13165    let full_source = if program.contains("## Main") || program.contains("## To ") {
13166        program.to_string()
13167    } else {
13168        format!("## Main\n{}", program)
13169    };
13170    let mut interner = Interner::new();
13171    let mut lexer = Lexer::new(&full_source, &mut interner);
13172    let tokens = lexer.tokenize();
13173    let type_registry = {
13174        let mut discovery = DiscoveryPass::new(&tokens, &mut interner);
13175        discovery.run_full().types
13176    };
13177    let mut vctors: VCtors = std::collections::HashMap::new();
13178    for (_t, def) in type_registry.iter_types() {
13179        if let crate::analysis::TypeDef::Enum { variants, .. } = def {
13180            for v in variants {
13181                let fnames: Vec<String> = v
13182                    .fields
13183                    .iter()
13184                    .map(|f| interner.resolve(f.name).to_string())
13185                    .collect();
13186                vctors.insert(interner.resolve(v.name).to_string(), fnames);
13187            }
13188        }
13189    }
13190    let mut world_state = WorldState::new();
13191    let expr_arena = Arena::new();
13192    let term_arena = Arena::new();
13193    let np_arena = Arena::new();
13194    let sym_arena = Arena::new();
13195    let role_arena = Arena::new();
13196    let pp_arena = Arena::new();
13197    let stmt_arena: Arena<Stmt> = Arena::new();
13198    let _compile_facts = crate::optimize::facts::scope();
13199    let imperative_expr_arena: Arena<Expr> = Arena::new();
13200    let type_expr_arena: Arena<TypeExpr> = Arena::new();
13201    let ast_ctx = AstContext::with_types(
13202        &expr_arena,
13203        &term_arena,
13204        &np_arena,
13205        &sym_arena,
13206        &role_arena,
13207        &pp_arena,
13208        &stmt_arena,
13209        &imperative_expr_arena,
13210        &type_expr_arena,
13211    );
13212    let mut parser = crate::parser::Parser::new(
13213        tokens,
13214        &mut world_state,
13215        &mut interner,
13216        ast_ctx,
13217        type_registry,
13218    );
13219    let stmts = parser.parse_program().ok()?;
13220    build_core::<S>(&stmts, &interner, &vctors)
13221}
13222
13223/// Construct the Core-IR `CProg` for an ALREADY-PARSED program on the sink `S`: partition top-level
13224/// statements into `## To` functions (`CFuncDef`) and the main block, then emit `CProg [funcs] main`.
13225/// This is the parse-free spine — an integrated caller that already holds the AST + interner + variant
13226/// table skips the ~90%-of-marshal parse entirely by calling [`stmts_to_core_wire_bytes`]. `None` if
13227/// any statement uses a construct the native builder does not cover.
13228fn build_core<S: CoreSink>(stmts: &[Stmt], interner: &Interner, vctors: &VCtors) -> Option<S::Val> {
13229    let mut funcs: Vec<S::Val> = Vec::new();
13230    let mut main_stmts: Vec<&Stmt> = Vec::new();
13231    for stmt in stmts {
13232        if let Stmt::FunctionDef {
13233            name,
13234            params,
13235            body,
13236            return_type,
13237            is_native,
13238            ..
13239        } = stmt
13240        {
13241            if *is_native {
13242                continue;
13243            }
13244            let fname = interner.resolve(*name).to_string();
13245            let pnames: Vec<S::Val> = params
13246                .iter()
13247                .map(|(n, _)| S::text(interner.resolve(*n)))
13248                .collect();
13249            let ptypes: Vec<S::Val> = params
13250                .iter()
13251                .map(|(_, ty)| S::text(&decompile_type_expr(ty, interner)))
13252                .collect();
13253            let ret = return_type
13254                .map(|rt| decompile_type_expr(rt, interner))
13255                .unwrap_or_else(|| "Nothing".to_string());
13256            let body_s: Vec<&Stmt> = body.iter().collect();
13257            let body_v = stmt_list_to_core::<S>(&body_s, interner, vctors)?;
13258            funcs.push(S::inductive(
13259                "CFuncDef",
13260                vec![
13261                    S::text(&fname),
13262                    S::list(pnames),
13263                    S::list(ptypes),
13264                    S::text(&ret),
13265                    body_v,
13266                ],
13267            ));
13268        } else if matches!(
13269            stmt,
13270            Stmt::StructDef { .. }
13271                | Stmt::Theorem(_)
13272                | Stmt::Definition(_)
13273                | Stmt::Axiom(_)
13274                | Stmt::Theory(_)
13275        ) {
13276            // Declarations contribute NOTHING to the runtime statement list — they live in the type
13277            // catalog / proof layer, and the reference encoder drops them. Skipping them here (rather
13278            // than routing to `stmt_to_core` → `None` → fallback) lets programs that carry an enum /
13279            // `Shared` struct (the ones that use Inspect, CRDT counters, typed closures) still hit the
13280            // fast native builder. Byte-identical: the reference likewise emits nothing for these.
13281        } else {
13282            main_stmts.push(stmt);
13283        }
13284    }
13285    let main_v = stmt_list_to_core::<S>(&main_stmts, interner, vctors)?;
13286    Some(S::inductive("CProg", vec![S::list(funcs), main_v]))
13287}
13288
13289/// Serialize a program's Core-IR `CProgram` (a `CProg` with its functions and main block) to the
13290/// plain wire form — the bytes a compile-once native partial evaluator reads on stdin. FAST PATH:
13291/// `program_to_core` on `WireSink` emits the wire bytes in ONE pass straight from the AST — no
13292/// intermediate `RuntimeValue` tree and no second `encode_value_raw` walk (byte-for-byte identical to
13293/// the old two-pass form; locked by `native_builder_is_byte_identical_to_the_interpreter`). FALLBACK:
13294/// for a construct the native builder does not cover, run the constructor source on the tree-walker
13295/// (`wireBytes`). Both are decoded identically by the native binary's generated `CProgram::wire_decode`.
13296pub fn program_to_core_wire_bytes(program: &str) -> Result<Vec<u8>, String> {
13297    if let Some(bytes) = program_to_core::<WireSink>(program) {
13298        return Ok(bytes);
13299    }
13300    program_to_core_wire_bytes_via_interpreter(program)
13301}
13302
13303/// The PARSE-FREE marshal: emit a program's Core-IR wire bytes directly from an ALREADY-PARSED AST,
13304/// skipping the lex + discovery + `parse_program` that dominates [`program_to_core_wire_bytes`] (~90%
13305/// of a specialization). An integrated caller that parsed the program once for compilation reuses that
13306/// AST here to feed the native PE at a fraction of the cost. `variant_fields` maps each variant
13307/// constructor name to its ordered field names (the caller derives it from its type registry, as
13308/// `program_to_core` does). `None` if a construct is uncovered. Byte-identical to
13309/// [`program_to_core_wire_bytes`] on the same program — same `build_core`/`WireSink` spine.
13310pub fn stmts_to_core_wire_bytes(
13311    stmts: &[Stmt],
13312    interner: &Interner,
13313    variant_fields: &std::collections::HashMap<String, Vec<String>>,
13314) -> Option<Vec<u8>> {
13315    build_core::<WireSink>(stmts, interner, variant_fields)
13316}
13317
13318/// The TWO-PASS marshal that [`program_to_core_wire_bytes`] replaced: build the full `RuntimeValue`
13319/// Core-IR tree (`TreeSink`) then `encode_value_raw` it. Kept as the correctness ORACLE and the
13320/// speed BASELINE for the single-pass (`WireSink`) form — the two are byte-identical by construction
13321/// (`WireSink` emits exactly what `encode_value_raw` would), and the single pass avoids the tree
13322/// allocation + the second encode walk. `None` if a construct is uncovered.
13323pub fn program_to_core_wire_bytes_two_pass(program: &str) -> Option<Vec<u8>> {
13324    program_to_core::<TreeSink>(program).and_then(|v| encode_value_raw(&v).ok())
13325}
13326
13327/// The REFERENCE marshal: always the interpreter path (construct the `CProgram` via the tree-walker,
13328/// `wireBytes`-serialize it). The native builder's output must be BYTE-IDENTICAL to this — locked by
13329/// `native_pe_wire::native_builder_is_byte_identical_to_the_interpreter`. Kept public so the lock can
13330/// force the reference regardless of native-builder coverage.
13331pub fn program_to_core_wire_bytes_via_interpreter(program: &str) -> Result<Vec<u8>, String> {
13332    let full_source = if program.contains("## Main") || program.contains("## To ") {
13333        program.to_string()
13334    } else {
13335        format!("## Main\n{}", program)
13336    };
13337    let encoded = encode_program_source(&full_source)
13338        .map_err(|e| format!("Failed to encode program: {}", describe_parse_error(&e)))?;
13339    let driver = "    Let prog be a new CProg with funcs encodedFuncSeq and main encodedMain.\n    Let wb be wireBytes(prog).\n    Repeat for b in wb:\n        Show \"{b}\".\n";
13340    let combined = format!("{}\n## Main\n{}\n{}", CORE_TYPES_FOR_PE, encoded, driver);
13341    let out = interpret_bootstrap(&combined)
13342        .map_err(|e| format!("wire-encode run failed: {}", describe_parse_error(&e)))?;
13343    let mut bytes = Vec::new();
13344    for line in out.lines() {
13345        let t = line.trim();
13346        if t.is_empty() {
13347            continue;
13348        }
13349        let n: u16 = t
13350            .parse()
13351            .map_err(|_| format!("wireBytes emitted a non-byte line: {:?}", t))?;
13352        bytes.push(n as u8);
13353    }
13354    Ok(bytes)
13355}
13356
13357#[cfg(not(target_arch = "wasm32"))]
13358thread_local! {
13359    /// The already-built native PE binary path for this process. Caching it avoids re-running
13360    /// `aot_cache_key` on every specialization — which spawns `rustc --version` (~15 ms) and
13361    /// re-hashes the 167 KB source. The path is stable for the process (the PE source doesn't
13362    /// change at runtime), so one lookup per process suffices.
13363    static NATIVE_PE_BIN: std::cell::RefCell<Option<std::path::PathBuf>> = const { std::cell::RefCell::new(None) };
13364}
13365
13366/// The collection semantics every bootstrap program — the partial evaluator, its dialects, the
13367/// self-interpreter, the decompiler, the wire encoder — runs and compiles under: reference, so the
13368/// state it threads through `mutable` parameters is mutated in place
13369/// ([`crate::semantics::collections::with_reference_semantics`]). Part of every cache key of a
13370/// natively compiled bootstrap program, since the Rust it compiles to depends on it.
13371#[cfg(not(target_arch = "wasm32"))]
13372const BOOTSTRAP_SEMANTICS: &str = "collections: reference";
13373
13374/// Build (once, content-addressed) the compile-once native PE binary and return its path. Keyed
13375/// on the generated Rust of [`pe_native_source`] + toolchain, so the one-time rustc compile of the
13376/// whole PE engine happens exactly once per PE version and is reused across every program and
13377/// session. This is the amortization that turns AOT from "recompile per program" into the 210x win.
13378#[cfg(not(target_arch = "wasm32"))]
13379pub fn build_native_pe_binary() -> Result<std::path::PathBuf, String> {
13380    // Warm path: the binary was already located/built this process — reuse it (no `rustc --version`
13381    // spawn, no re-hash) as long as it still exists on disk.
13382    if let Some(p) = NATIVE_PE_BIN.with(|c| c.borrow().clone()) {
13383        if p.exists() {
13384            return Ok(p);
13385        }
13386    }
13387    let src = pe_native_source();
13388    // Key on the (stable) PE SOURCE text + toolchain + the collection semantics it compiles under
13389    // — NOT the generated Rust: computing the Rust means recompiling the whole 167 KB engine,
13390    // which would defeat the cache on every warm call.
13391    let key = aot_cache_key(&format!("{src}\n{BOOTSTRAP_SEMANTICS}"));
13392    let base = std::env::temp_dir().join("logos_native_pe");
13393    std::fs::create_dir_all(&base).map_err(|e| e.to_string())?;
13394    let proj = base.join(format!("pe_{key}"));
13395    let bin = proj.join("target").join("release").join("logos_native_pe");
13396    if bin.exists() {
13397        NATIVE_PE_BIN.with(|c| *c.borrow_mut() = Some(bin.clone()));
13398        return Ok(bin);
13399    }
13400    let rust = with_reference_semantics(|| compile_program_full_with_wire(&src))
13401        .map_err(|e| format!("native PE compile: {}", describe_parse_error(&e)))?
13402        .rust_code;
13403    std::fs::create_dir_all(proj.join("src")).map_err(|e| e.to_string())?;
13404    let manifest = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
13405    let root = manifest.parent().unwrap().parent().unwrap();
13406    std::fs::write(
13407        proj.join("Cargo.toml"),
13408        format!(
13409            "[package]\nname=\"logos_native_pe\"\nversion=\"0.1.0\"\nedition=\"2021\"\n[dependencies]\nlogicaffeine-data={{path=\"{r}/crates/logicaffeine_data\"}}\nlogicaffeine-system={{path=\"{r}/crates/logicaffeine_system\",features=[\"full\"]}}\ntokio={{version=\"1\",features=[\"rt-multi-thread\",\"macros\"]}}\nserde={{version=\"1\",features=[\"derive\"]}}\nrayon=\"1\"\n[profile.release]\nopt-level=3\n",
13410            r = root.display()
13411        ),
13412    )
13413    .map_err(|e| e.to_string())?;
13414    std::fs::write(proj.join("src/main.rs"), &rust).map_err(|e| e.to_string())?;
13415    std::fs::copy(root.join("Cargo.lock"), proj.join("Cargo.lock")).map_err(|e| e.to_string())?;
13416    let out = std::process::Command::new("cargo")
13417        .args(["build", "--release", "--quiet"])
13418        .current_dir(&proj)
13419        .env("CARGO_TARGET_DIR", proj.join("target"))
13420        .env("RUST_MIN_STACK", "268435456")
13421        .output()
13422        .map_err(|e| e.to_string())?;
13423    if !out.status.success() {
13424        return Err(format!(
13425            "native PE build failed:\n{}",
13426            String::from_utf8_lossy(&out.stderr)
13427        ));
13428    }
13429    if bin.exists() {
13430        NATIVE_PE_BIN.with(|c| *c.borrow_mut() = Some(bin.clone()));
13431        Ok(bin)
13432    } else {
13433        Err("native PE binary missing after a successful build".into())
13434    }
13435}
13436
13437/// Specialize `program` on the compile-once native PE via the RESIDENT SERVER (the fallback path;
13438/// the default [`run_native_pe`] prefers the faster in-process cdylib): serialize it to wire bytes
13439/// ([`program_to_core_wire_bytes`]), stream them to the server, and return its Jones-optimal
13440/// residual. The server (the compiled PE binary) is spawned ONCE per thread and reused — length-
13441/// framed request/response over its stdin/stdout — so there is no per-call process spawn and no
13442/// per-call rustc: just the host marshal + native `peBlock`, plus one pipe round-trip.
13443///
13444/// The server persists in a thread-local; dropping it (thread end / on I/O error, which triggers a
13445/// respawn) closes its stdin, and `readWireProgram` exits the child cleanly on that EOF.
13446#[cfg(not(target_arch = "wasm32"))]
13447struct PeServer {
13448    child: std::process::Child,
13449    stdin: std::process::ChildStdin,
13450    stdout: std::io::BufReader<std::process::ChildStdout>,
13451}
13452
13453#[cfg(not(target_arch = "wasm32"))]
13454impl Drop for PeServer {
13455    fn drop(&mut self) {
13456        // Reap the child so a long-lived host (or the test harness) never accumulates zombies.
13457        let _ = self.child.kill();
13458        let _ = self.child.wait();
13459    }
13460}
13461
13462#[cfg(not(target_arch = "wasm32"))]
13463thread_local! {
13464    static PE_SERVER: std::cell::RefCell<Option<PeServer>> = const { std::cell::RefCell::new(None) };
13465}
13466
13467#[cfg(not(target_arch = "wasm32"))]
13468pub fn run_native_pe_server(program: &str) -> Result<String, String> {
13469    use std::io::{Read, Write};
13470    let bytes = program_to_core_wire_bytes(program)?;
13471    let raw = PE_SERVER.with(|cell| -> Result<String, String> {
13472        // A single request/response over the resident server; on ANY I/O failure the server is
13473        // dropped (respawned next call) so a crashed child never wedges the pipeline.
13474        let attempt = |slot: &mut Option<PeServer>| -> Result<String, String> {
13475            if slot.is_none() {
13476                let bin = build_native_pe_binary()?;
13477                let mut child = std::process::Command::new(&bin)
13478                    .stdin(std::process::Stdio::piped())
13479                    .stdout(std::process::Stdio::piped())
13480                    .stderr(std::process::Stdio::null())
13481                    .env("RUST_MIN_STACK", "268435456")
13482                    .spawn()
13483                    .map_err(|e| format!("native PE server spawn: {e}"))?;
13484                let stdin = child.stdin.take().unwrap();
13485                let stdout = std::io::BufReader::new(child.stdout.take().unwrap());
13486                *slot = Some(PeServer {
13487                    child,
13488                    stdin,
13489                    stdout,
13490                });
13491            }
13492            let srv = slot.as_mut().unwrap();
13493            srv.stdin
13494                .write_all(&(bytes.len() as u32).to_le_bytes())
13495                .and_then(|_| srv.stdin.write_all(&bytes))
13496                .and_then(|_| srv.stdin.flush())
13497                .map_err(|e| format!("native PE server write: {e}"))?;
13498            let mut len = [0u8; 4];
13499            srv.stdout
13500                .read_exact(&mut len)
13501                .map_err(|e| format!("native PE server read length: {e}"))?;
13502            let n = u32::from_le_bytes(len) as usize;
13503            let mut buf = vec![0u8; n];
13504            srv.stdout
13505                .read_exact(&mut buf)
13506                .map_err(|e| format!("native PE server read residual: {e}"))?;
13507            String::from_utf8(buf).map_err(|e| format!("native PE residual not UTF-8: {e}"))
13508        };
13509        let mut slot = cell.borrow_mut();
13510        match attempt(&mut slot) {
13511            Ok(v) => Ok(v),
13512            Err(e) => {
13513                *slot = None; // drop the (possibly dead) server so the next call respawns
13514                Err(e)
13515            }
13516        }
13517    })?;
13518    let residual = finish_projection1_residual(raw)?;
13519    Ok(prepend_type_definitions(program, residual))
13520}
13521
13522#[cfg(not(target_arch = "wasm32"))]
13523thread_local! {
13524    /// The already-built PE cdylib path for this process (see [`NATIVE_PE_BIN`]).
13525    static NATIVE_PE_CDYLIB: std::cell::RefCell<Option<std::path::PathBuf>> = const { std::cell::RefCell::new(None) };
13526}
13527
13528/// The in-process FFI shim appended to the generated PE engine to form the cdylib's `lib.rs`. It
13529/// lives in the SAME crate-root module as the generated `pub enum CProgram` and the exported
13530/// `pub fn peSpecializeOnce(CProgram) -> String`, so it can call both directly. `into_boxed_slice` gives
13531/// an allocation with capacity EXACTLY == len, so `logos_pe_free` reconstructs the identical
13532/// `Box<[u8]>` (reconstructing a `Vec` with cap==len would be UB if the allocator over-allocated).
13533#[cfg(not(target_arch = "wasm32"))]
13534const PE_CDYLIB_SHIM: &str = r#"
13535
13536// ── in-process FFI entry (appended by build_native_pe_cdylib) ───────────────────────────────
13537#[no_mangle]
13538pub extern "C" fn logos_pe_specialize(ptr: *const u8, len: usize, out_len: *mut usize) -> *mut u8 {
13539    let bytes = unsafe { std::slice::from_raw_parts(ptr, len) };
13540    let prog = <CProgram as logicaffeine_data::wire::WireDecode>::wire_decode(bytes, &mut 0usize)
13541        .expect("logos_pe_specialize: decode CProgram");
13542    let out: String = peSpecializeOnce(prog);
13543    let boxed: Box<[u8]> = out.into_bytes().into_boxed_slice();
13544    let n = boxed.len();
13545    unsafe { *out_len = n; }
13546    Box::into_raw(boxed) as *mut u8
13547}
13548
13549#[no_mangle]
13550pub extern "C" fn logos_pe_free(ptr: *mut u8, len: usize) {
13551    if !ptr.is_null() {
13552        unsafe { drop(Box::from_raw(std::slice::from_raw_parts_mut(ptr, len) as *mut [u8])); }
13553    }
13554}
13555"#;
13556
13557/// The PE cdylib's `lib.rs`: [`pe_cdylib_source`] through the Rust emitter, under the reference
13558/// collection semantics, followed by `PE_CDYLIB_SHIM`.
13559#[cfg(not(target_arch = "wasm32"))]
13560pub fn native_pe_cdylib_lib_rs() -> Result<String, String> {
13561    let generated = with_reference_semantics(|| compile_program_full_with_wire(&pe_cdylib_source()))
13562        .map_err(|e| format!("native PE cdylib compile: {}", describe_parse_error(&e)))?
13563        .rust_code;
13564    Ok(format!("{generated}\n{PE_CDYLIB_SHIM}"))
13565}
13566
13567/// Build (and cache) the PE compiled as an IN-PROCESS cdylib exporting `logos_pe_specialize`.
13568/// Mirrors [`build_native_pe_binary`] but emits a `cdylib` whose `lib.rs` is the generated PE engine
13569/// ([`pe_cdylib_source`]) plus a hand-written `extern "C"` shim (`PE_CDYLIB_SHIM`) that decodes the
13570/// wire `CProgram` and calls `peSpecializeOnce` directly — so the caller loads it once and
13571/// specializes with a plain function call, no process, no pipe. Content-addressed on the (stable)
13572/// cdylib PE source + shim + toolchain, so warm calls skip rustc.
13573#[cfg(not(target_arch = "wasm32"))]
13574pub fn build_native_pe_cdylib() -> Result<std::path::PathBuf, String> {
13575    if let Some(p) = NATIVE_PE_CDYLIB.with(|c| c.borrow().clone()) {
13576        if p.exists() {
13577            return Ok(p);
13578        }
13579    }
13580    let src = pe_cdylib_source();
13581    // Key on the PE source, the FFI shim and the collection semantics the engine compiles under,
13582    // so changing any of them invalidates the on-disk cache.
13583    let key = aot_cache_key(&format!("{src}\n{PE_CDYLIB_SHIM}\n{BOOTSTRAP_SEMANTICS}"));
13584    let base = std::env::temp_dir().join("logos_native_pe_cdylib");
13585    std::fs::create_dir_all(&base).map_err(|e| e.to_string())?;
13586    let proj = base.join(format!("pe_{key}"));
13587    let so = proj.join("target").join("release").join(format!(
13588        "{}logos_native_pe_lib{}",
13589        std::env::consts::DLL_PREFIX,
13590        std::env::consts::DLL_SUFFIX
13591    ));
13592    if so.exists() {
13593        NATIVE_PE_CDYLIB.with(|c| *c.borrow_mut() = Some(so.clone()));
13594        return Ok(so);
13595    }
13596    let lib_rs = native_pe_cdylib_lib_rs()?;
13597    std::fs::create_dir_all(proj.join("src")).map_err(|e| e.to_string())?;
13598    let manifest = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
13599    let root = manifest.parent().unwrap().parent().unwrap();
13600    std::fs::write(
13601        proj.join("Cargo.toml"),
13602        format!(
13603            "[package]\nname=\"logos_native_pe_lib\"\nversion=\"0.1.0\"\nedition=\"2021\"\n[lib]\ncrate-type=[\"cdylib\"]\npath=\"src/lib.rs\"\n[dependencies]\nlogicaffeine-data={{path=\"{r}/crates/logicaffeine_data\"}}\nlogicaffeine-system={{path=\"{r}/crates/logicaffeine_system\",features=[\"full\"]}}\ntokio={{version=\"1\",features=[\"rt-multi-thread\",\"macros\"]}}\nserde={{version=\"1\",features=[\"derive\"]}}\nrayon=\"1\"\n[profile.release]\nopt-level=3\n",
13604            r = root.display()
13605        ),
13606    )
13607    .map_err(|e| e.to_string())?;
13608    std::fs::write(proj.join("src/lib.rs"), &lib_rs).map_err(|e| e.to_string())?;
13609    std::fs::copy(root.join("Cargo.lock"), proj.join("Cargo.lock")).map_err(|e| e.to_string())?;
13610    let out = std::process::Command::new("cargo")
13611        .args(["build", "--release", "--quiet"])
13612        .current_dir(&proj)
13613        .env("CARGO_TARGET_DIR", proj.join("target"))
13614        .env("RUST_MIN_STACK", "268435456")
13615        .output()
13616        .map_err(|e| e.to_string())?;
13617    if !out.status.success() {
13618        return Err(format!(
13619            "native PE cdylib build failed:\n{}",
13620            String::from_utf8_lossy(&out.stderr)
13621        ));
13622    }
13623    if so.exists() {
13624        NATIVE_PE_CDYLIB.with(|c| *c.borrow_mut() = Some(so.clone()));
13625        Ok(so)
13626    } else {
13627        Err("native PE cdylib missing after a successful build".into())
13628    }
13629}
13630
13631/// The loaded PE cdylib for this thread: the `Library` kept alive alongside the raw entry-point
13632/// pointers derived from it (valid for as long as the `Library` is not unloaded, which is exactly
13633/// this struct's lifetime).
13634#[cfg(not(target_arch = "wasm32"))]
13635struct PeLib {
13636    _lib: libloading::Library,
13637    specialize: unsafe extern "C" fn(*const u8, usize, *mut usize) -> *mut u8,
13638    free: unsafe extern "C" fn(*mut u8, usize),
13639}
13640
13641#[cfg(not(target_arch = "wasm32"))]
13642thread_local! {
13643    static PE_LIB: std::cell::RefCell<Option<PeLib>> = const { std::cell::RefCell::new(None) };
13644}
13645
13646/// Specialize `program` on the compile-once native PE, IN PROCESS: marshal it to wire bytes, hand
13647/// them to the `dlopen`ed PE cdylib's `logos_pe_specialize` as a plain function call, and reclaim
13648/// the residual bytes. No child process, no pipe — the ~59 µs IPC round-trip of the resident server
13649/// is gone; all that remains is the host marshal + native `peBlock` + one FFI call. The cdylib is
13650/// built + loaded ONCE per thread and cached. Residual-identity with the server / tree-walker is
13651/// locked by `native_pe_wire`.
13652#[cfg(not(target_arch = "wasm32"))]
13653pub fn run_native_pe_inprocess(program: &str) -> Result<String, String> {
13654    let bytes = program_to_core_wire_bytes(program)?;
13655    let raw = PE_LIB.with(|cell| -> Result<String, String> {
13656        let mut slot = cell.borrow_mut();
13657        if slot.is_none() {
13658            let so = build_native_pe_cdylib()?;
13659            // SAFETY: the cdylib was just built from our own generated source; its exported symbols
13660            // have exactly the signatures declared here, and the raw pointers are stored alongside
13661            // the owning `Library` so they never outlive it.
13662            unsafe {
13663                let lib = libloading::Library::new(&so)
13664                    .map_err(|e| format!("native PE cdylib load: {e}"))?;
13665                let specialize: libloading::Symbol<
13666                    unsafe extern "C" fn(*const u8, usize, *mut usize) -> *mut u8,
13667                > = lib
13668                    .get(b"logos_pe_specialize")
13669                    .map_err(|e| format!("dlsym logos_pe_specialize: {e}"))?;
13670                let free: libloading::Symbol<unsafe extern "C" fn(*mut u8, usize)> = lib
13671                    .get(b"logos_pe_free")
13672                    .map_err(|e| format!("dlsym logos_pe_free: {e}"))?;
13673                let specialize = *specialize;
13674                let free = *free;
13675                *slot = Some(PeLib {
13676                    _lib: lib,
13677                    specialize,
13678                    free,
13679                });
13680            }
13681        }
13682        let pl = slot.as_ref().unwrap();
13683        let mut out_len: usize = 0;
13684        // SAFETY: `bytes` is a live slice for the duration of the call; the callee writes `out_len`
13685        // and returns a buffer of that length we own until `free`.
13686        let p = unsafe { (pl.specialize)(bytes.as_ptr(), bytes.len(), &mut out_len as *mut usize) };
13687        if p.is_null() {
13688            return Err("native PE cdylib returned a null residual".into());
13689        }
13690        let residual_bytes = unsafe { std::slice::from_raw_parts(p, out_len).to_vec() };
13691        unsafe { (pl.free)(p, out_len) };
13692        String::from_utf8(residual_bytes).map_err(|e| format!("native PE residual not UTF-8: {e}"))
13693    })?;
13694    let residual = finish_projection1_residual(raw)?;
13695    Ok(prepend_type_definitions(program, residual))
13696}
13697
13698/// Specialize `program` on the compile-once native PE — the DEFAULT entry and the pit of success.
13699/// Prefers the IN-PROCESS cdylib path ([`run_native_pe_inprocess`]; no process/pipe boundary) and
13700/// falls back to the resident server ([`run_native_pe_server`]) only if the in-process build/load
13701/// fails (e.g. no toolchain), so the fast+correct route is what every caller gets by default. The
13702/// two paths are proven byte-identical by `native_pe_wire`.
13703#[cfg(not(target_arch = "wasm32"))]
13704pub fn run_native_pe(program: &str) -> Result<String, String> {
13705    match run_native_pe_inprocess(program) {
13706        Ok(v) => Ok(v),
13707        Err(_) => run_native_pe_server(program),
13708    }
13709}
13710
13711/// VM-driven twin of [`projection1_source_real_fast`].
13712///
13713/// Executes the identical assembled PE program on the register bytecode VM
13714/// ([`vm_run_source`]) instead of the tree-walker. The PE engine is a fixed program —
13715/// only its `encodedMain` input varies per call — so the VM either supports the whole
13716/// engine or none of it; measured ~2× faster than the tree-walker with a byte-identical
13717/// residual. The corpus-wide equivalence is locked by `futamura_tier_lock`.
13718pub fn projection1_source_real_fast_on_vm(
13719    core_types: &str,
13720    _interpreter: &str,
13721    program: &str,
13722) -> Result<String, String> {
13723    let combined = pe_combined_source(core_types, program)?;
13724
13725    let raw_residual = with_reference_semantics(|| vm_run_source(&combined))
13726        .map_err(|e| format!("PE VM execution failed: {e}"))?;
13727    let residual = finish_projection1_residual(raw_residual)?;
13728    Ok(prepend_type_definitions(program, residual))
13729}
13730
13731/// Re-attach every original `## …` section that is NOT `## Main` and NOT a `## To` function
13732/// (the residual supplies its own Main + specialized functions). These are the type / struct
13733/// / policy definitions that make the residual a self-contained, re-runnable program.
13734fn prepend_type_definitions(program: &str, residual: String) -> String {
13735    let mut defs = String::new();
13736    let mut keep = false;
13737    for line in program.lines() {
13738        if let Some(header) = line.strip_prefix("## ") {
13739            keep = header != "Main" && !header.starts_with("To ");
13740        }
13741        if keep {
13742            defs.push_str(line);
13743            defs.push('\n');
13744        }
13745    }
13746    if defs.trim().is_empty() {
13747        residual
13748    } else {
13749        format!("{}{}", defs, residual)
13750    }
13751}
13752
13753/// Assemble the full PE-run source (core types + PE + decompiler + encoded
13754/// input + driver) — the exact program [`projection1_source_real_fast`]
13755/// executes. Public so differential harnesses can run it on a specific engine.
13756pub fn pe_combined_source(core_types: &str, program: &str) -> Result<String, String> {
13757    let full_source = if program.contains("## Main") || program.contains("## To ") {
13758        program.to_string()
13759    } else {
13760        format!("## Main\n{}", program)
13761    };
13762
13763    let encoded = encode_program_source(&full_source)
13764        .map_err(|e| format!("Failed to encode program: {}", describe_parse_error(&e)))?;
13765
13766    let pe_source = pe_source_text();
13767    let decompile_source = decompile_source_text();
13768
13769    let actual_core_types = if core_types.is_empty() {
13770        CORE_TYPES_FOR_PE
13771    } else {
13772        core_types
13773    };
13774
13775    // Driver: run PE, then transitively decompile every referenced function (specialized
13776    // or original) so residual calls — e.g. an MSG-generalized recursive loop — resolve.
13777    // For fully-inlined residuals (no calls) this emits nothing and matches the bare form.
13778    let driver = r#"
13779    Let state be makePeState(a new Map of Text to CVal, encodedFuncMap, 200).
13780    Let residual be peBlock(encodedMain, state).
13781    Let nl be chr(10).
13782    Let mutable output be "".
13783    Let specFuncs be peFuncs(state).
13784    Let mutable allNames be collectCallNames(residual).
13785    Let mutable emitted be a new Map of Text to Bool.
13786    Let mutable changed be true.
13787    While changed:
13788        Set changed to false.
13789        Let mutable toAdd be a new Seq of Text.
13790        Repeat for fnKey in allNames:
13791            Let fkStr be "{fnKey}".
13792            If emitted contains fkStr:
13793                Let skipE be true.
13794            Otherwise:
13795                Set item fkStr of emitted to true.
13796                Let fkStr2 be "{fnKey}".
13797                If specFuncs contains fkStr2:
13798                    Let fdef be item fkStr2 of specFuncs.
13799                    Inspect fdef:
13800                        When CFuncDef (fn0, ps0, pt0, rt0, body0):
13801                            Let children be collectCallNames(body0).
13802                            Repeat for child in children:
13803                                Let childStr be "{child}".
13804                                If not emitted contains childStr:
13805                                    Push child to toAdd.
13806                                    Set changed to true.
13807                        Otherwise:
13808                            Let skipF be true.
13809        Repeat for ta in toAdd:
13810            Push ta to allNames.
13811    Repeat for fnKey in allNames:
13812        Let fkStr be "{fnKey}".
13813        If specFuncs contains fkStr:
13814            Let fdef be item fkStr of specFuncs.
13815            Let funcSrc be decompileFunc(fdef).
13816            If the length of funcSrc is greater than 0:
13817                Set output to "{output}{funcSrc}{nl}".
13818    Let mainSrc be decompileBlock(residual, 0).
13819    Set output to "{output}## Main{nl}{mainSrc}".
13820    Show output.
13821"#;
13822
13823    let combined = format!(
13824        "{}\n{}\n{}\n## Main\n{}\n{}",
13825        actual_core_types, pe_source, decompile_source, encoded, driver,
13826    );
13827
13828    Ok(combined)
13829}
13830
13831/// The post-processing applied to a raw PE residual (the `Any`-type safety
13832/// net + `## Main` normalization).
13833pub fn finish_projection1_residual(raw_residual: String) -> Result<String, String> {
13834    // Safety net (mirrors `fix_decompiled_types` on the P2/P3 path): specialized functions
13835    // whose param/return types the PE could not propagate are emitted as `Any`, which the
13836    // parser rejects. The tree-walker is dynamically typed, so a concrete placeholder type
13837    // is cosmetic at runtime — rewrite `Any` annotations so the residual re-parses.
13838    let fixed = raw_residual
13839        .replace(": Any)", ": Int)")
13840        .replace("-> Any:", "-> Int:")
13841        .replace(" of Any", " of Int")
13842        .replace(" to Any", " to Int");
13843    let trimmed = fixed.trim();
13844
13845    if trimmed.is_empty() {
13846        return Ok("## Main\n".to_string());
13847    }
13848
13849    if trimmed.contains("## To ") || trimmed.starts_with("## Main") {
13850        Ok(trimmed.to_string())
13851    } else {
13852        Ok(format!("## Main\n{}", trimmed))
13853    }
13854}
13855
13856/// Run genuine P2 on a specific target: PE(pe_source, pe_mini(target))
13857///
13858/// This is the real Futamura Projection 2 applied end-to-end:
13859/// 1. Build pe_mini applied to the target (pe_mini compiles the target)
13860/// 2. Encode the combined pe_mini+target as CProgram data
13861/// 3. Run pe_source on the encoded data (PE specializes pe_mini for this target)
13862/// 4. Decompile the residual to LOGOS source
13863/// 5. Execute the decompiled residual to get the target's output
13864///
13865/// No decompilation of specialized functions — the PE directly produces the compiled
13866/// target as CStmt data, which is decompiled to a simple LOGOS program and run.
13867pub fn run_genuine_p2_on_target(
13868    program: &str,
13869    core_types: &str,
13870    interpreter: &str,
13871) -> Result<String, String> {
13872    let combined = genuine_p2_on_target_source(program, core_types, interpreter)?;
13873    with_reference_semantics(|| run_logos_source(&combined))
13874}
13875
13876/// The whole program [`run_genuine_p2_on_target`] runs, so a harness can run it on any backend.
13877pub fn genuine_p2_on_target_source(
13878    program: &str,
13879    core_types: &str,
13880    interpreter: &str,
13881) -> Result<String, String> {
13882    let pe_mini = pe_mini_source_text();
13883    let pe = pe_source_text();
13884
13885    let full_source = if program.contains("## Main") || program.contains("## To ") {
13886        program.to_string()
13887    } else {
13888        format!("## Main\n{}", program)
13889    };
13890
13891    // Build pe_mini applied to the specific target.
13892    // pe_mini ONLY COMPILES the target — produces CStmt data as output.
13893    // Build pe_mini + interpreter applied to the target.
13894    // pe_mini compiles the target, coreExecBlock runs the compiled result.
13895    let target_encoded = encode_program_source(&full_source)
13896        .map_err(|e| format!("Failed to encode target: {}", describe_parse_error(&e)))?;
13897    let pe_mini_prog = format!(
13898        "{}\n{}\n{}\n## Main\n{}\n\
13899         Let compileEnv be a new Map of Text to CVal.\n\
13900         Let compileState be makePeState(compileEnv, encodedFuncMap, 200).\n\
13901         Let compiled be peBlockM(encodedMain, compileState).\n\
13902         Let runEnv be a new Map of Text to CVal.\n\
13903         coreExecBlock(compiled, runEnv, encodedFuncMap).\n",
13904        core_types, pe_mini, interpreter, target_encoded
13905    );
13906
13907    // Encode pe_mini+target as CProgram data for the outer PE
13908    let encoded = encode_program_source_compact(&pe_mini_prog).map_err(|e| {
13909        format!(
13910            "Failed to encode pe_mini+target for P2: {}",
13911            describe_parse_error(&e)
13912        )
13913    })?;
13914
13915    // The driver runs PE on the encoded pe_mini+target, then executes the residual.
13916    // peFuncs(state) contains BOTH the PE-specialized functions AND the original
13917    // functions from the encoded program (including pe_mini, interpreter, and
13918    // target functions like factorial).
13919    let driver = r#"    Let state be makePeState(a new Map of Text to CVal, encodedFuncMap, 500).
13920    Let residual be peBlock(encodedMain, state).
13921    Let allFuncs be peFuncs(state).
13922    Let runEnv be a new Map of Text to CVal.
13923    coreExecBlock(residual, runEnv, allFuncs).
13924"#;
13925    Ok(format!(
13926        "{}\n{}\n{}\n## Main\n{}\n{}",
13927        CORE_TYPES_FOR_PE, pe, interpreter, encoded, driver
13928    ))
13929}
13930
13931/// Run genuine P3 on a specific target: PE(pe_source, pe_bti(target))
13932pub fn run_genuine_p3_on_target(
13933    program: &str,
13934    core_types: &str,
13935    interpreter: &str,
13936) -> Result<String, String> {
13937    let combined = genuine_p3_on_target_source(program, core_types, interpreter)?;
13938    with_reference_semantics(|| run_logos_source(&combined))
13939}
13940
13941/// The whole program [`run_genuine_p3_on_target`] runs, so a harness can run it on any backend.
13942pub fn genuine_p3_on_target_source(
13943    program: &str,
13944    core_types: &str,
13945    interpreter: &str,
13946) -> Result<String, String> {
13947    let pe_bti = pe_bti_source_text();
13948    let pe = pe_source_text();
13949
13950    let full_source = if program.contains("## Main") || program.contains("## To ") {
13951        program.to_string()
13952    } else {
13953        format!("## Main\n{}", program)
13954    };
13955
13956    let bti_types = CORE_TYPES_FOR_PE
13957        .replace("specResults", "memoCache")
13958        .replace("onStack", "callGuard");
13959
13960    let target_encoded = encode_program_source(&full_source)
13961        .map_err(|e| format!("Failed to encode target: {}", describe_parse_error(&e)))?;
13962    let pe_bti_prog = format!(
13963        "{}\n{}\n{}\n## Main\n{}\n\
13964         Let compileEnv be a new Map of Text to CVal.\n\
13965         Let compileState be makePeState(compileEnv, encodedFuncMap, 200).\n\
13966         Let compiled be peBlockB(encodedMain, compileState).\n\
13967         Let runEnv be a new Map of Text to CVal.\n\
13968         coreExecBlock(compiled, runEnv, encodedFuncMap).\n",
13969        bti_types, pe_bti, interpreter, target_encoded
13970    );
13971
13972    let encoded = encode_program_source_compact(&pe_bti_prog).map_err(|e| {
13973        format!(
13974            "Failed to encode pe_bti+target for P3: {}",
13975            describe_parse_error(&e)
13976        )
13977    })?;
13978
13979    // Execute residual directly — no decompilation needed
13980    let driver = r#"    Let state be makePeState(a new Map of Text to CVal, encodedFuncMap, 200).
13981    Let residual be peBlock(encodedMain, state).
13982    Let runEnv be a new Map of Text to CVal.
13983    coreExecBlock(residual, runEnv, encodedFuncMap).
13984"#;
13985    Ok(format!(
13986        "{}\n{}\n{}\n## Main\n{}\n{}",
13987        CORE_TYPES_FOR_PE, pe, interpreter, encoded, driver
13988    ))
13989}
13990
13991/// Genuine Futamura Projection 2 via self-application: PE(pe_source, pe_mini(targetStmts))
13992///
13993/// The outer PE (pe_source) specializes pe_mini's FULL BLOCK evaluator with known
13994/// state (empty env, empty funcs, depth 200). targetStmts is a free/dynamic variable;
13995/// state is fully static. The PE produces a specialized peBlockM_ function that IS
13996/// the compiler — handling all CStmt variants with specialized expression processing.
13997///
13998/// This eliminates the need for a Rust-generated block wrapper: the PE naturally
13999/// produces block-level dispatch through specialization of peBlockM.
14000pub fn projection2_source_real(
14001    _core_types: &str,
14002    _interpreter: &str,
14003) -> Result<GenuineProjectionResult, String> {
14004    let pe_mini = pe_mini_source_text();
14005    let pe = pe_source_text();
14006    let decompile = decompile_source_text();
14007
14008    // Build pe_mini program with peBlockM as entry — FULL block-level specialization.
14009    // targetStmts = free/dynamic variable (program's main block).
14010    // targetFuncs = free/dynamic variable (program's function definitions).
14011    // env = static (empty — programs start with no bindings).
14012    // depth = static (200 — PE eliminates depth checks).
14013    // targetStmts is a free/dynamic variable. State is fully static (empty env,
14014    // empty funcs, depth 200). The PE specializes pe_mini's dispatch code completely.
14015    // The resulting compiler handles function definitions at USE time via the state
14016    // parameter provided by the test harness.
14017    let program = format!(
14018        "{}\n{}\n## Main\n    Let env be a new Map of Text to CVal.\n    Let funcs be a new Map of Text to CFunc.\n    Let state be makePeState(env, funcs, 200).\n    Let result be peBlockM(targetStmts, state).\n    Show \"done\".\n",
14019        CORE_TYPES_FOR_PE, pe_mini
14020    );
14021
14022    // Encode pe_mini + driver as CProgram data (compact encoding)
14023    let encoded = encode_program_source_compact(&program).map_err(|e| {
14024        format!(
14025            "Failed to encode pe_mini for P2: {}",
14026            describe_parse_error(&e)
14027        )
14028    })?;
14029
14030    // Driver: run PE, then decompile specialized functions transitively.
14031    // Fixpoint collection: discover all transitively-referenced specialized functions
14032    // at arbitrary depth, not limited to any fixed number of levels.
14033    let driver = r#"    Let state be makePeState(a new Map of Text to CVal, encodedFuncMap, 200).
14034    Let residual be peBlock(encodedMain, state).
14035    Let nl be chr(10).
14036    Let mutable output be "".
14037    Let specFuncs be peFuncs(state).
14038    Let mutable allNames be collectCallNames(residual).
14039    Let mutable emitted be a new Map of Text to Bool.
14040    Let mutable changed be true.
14041    While changed:
14042        Set changed to false.
14043        Let mutable toAdd be a new Seq of Text.
14044        Repeat for fnKey in allNames:
14045            Let fkStr be "{fnKey}".
14046            If emitted contains fkStr:
14047                Let skipE be true.
14048            Otherwise:
14049                Set item fkStr of emitted to true.
14050                Let fkStr2 be "{fnKey}".
14051                If specFuncs contains fkStr2:
14052                    Let fdef be item fkStr2 of specFuncs.
14053                    Inspect fdef:
14054                        When CFuncDef (fn0, ps0, pt0, rt0, body0):
14055                            Let children be collectCallNames(body0).
14056                            Repeat for child in children:
14057                                Let childStr be "{child}".
14058                                If not emitted contains childStr:
14059                                    Push child to toAdd.
14060                                    Set changed to true.
14061                        Otherwise:
14062                            Let skipF be true.
14063        Repeat for ta in toAdd:
14064            Push ta to allNames.
14065    Repeat for fnKey in allNames:
14066        Let fkStr be "{fnKey}".
14067        If specFuncs contains fkStr:
14068            Let fdef be item fkStr of specFuncs.
14069            Let funcSrc be decompileFunc(fdef).
14070            If the length of funcSrc is greater than 0:
14071                Set output to "{output}{funcSrc}{nl}".
14072    Let mainSrc be decompileBlock(residual, 0).
14073    Set output to "{output}## Main{nl}{mainSrc}".
14074    Show output.
14075"#;
14076    let combined = format!(
14077        "{}\n{}\n{}\n## Main\n{}\n{}",
14078        CORE_TYPES_FOR_PE, pe, decompile, encoded, driver
14079    );
14080
14081    let result = with_reference_semantics(|| run_logos_source(&combined))?;
14082
14083    // The decompiler now emits types from CFunc's paramTypes/returnType fields for
14084    // functions that carry type info. PE-generated specializations may still use "Any"
14085    // for types that couldn't be propagated through specialization. Apply type fixup
14086    // as a safety net for any remaining "Any" types in specialized function signatures.
14087    let result = fix_decompiled_types(&result, &[
14088        ("peExprM_", "(e: CExpr) -> CExpr:"),
14089        ("peBlockM_", "(stmts: Seq of CStmt) -> Seq of CStmt:"),
14090        ("checkLiteralM_", "(e: CExpr) -> Bool:"),
14091        ("exprToValM_", "(e: CExpr) -> CVal:"),
14092        ("valToExprM_", "(v: CVal) -> CExpr:"),
14093        ("evalBinOpM_", "(binOp: Text) and (lv: CVal) and (rv: CVal) -> CVal:"),
14094        ("isCopyPropSafeM_", "(e: CExpr) -> Bool:"),
14095        ("checkVNothingM_", "(v: CVal) -> Bool:"),
14096        ("hasReturnM_", "(stmts: Seq of CStmt) -> Bool:"),
14097        ("extractReturnM_", "(stmts: Seq of CStmt) -> CExpr:"),
14098        ("validateExtractReturnM_", "(result: CExpr) and (bodyStmts: Seq of CStmt) -> CExpr:"),
14099        ("makeKeyM_", "(fnName: Text) and (args: Seq of CExpr) -> Text:"),
14100        ("exprToKeyPartM_", "(e: CExpr) -> Text:"),
14101        ("collectSetVarsM_", "(stmts: Seq of CStmt) -> Seq of Text:"),
14102        ("peEnvM_", "(st: PEMiniState) -> Map of Text to CVal:"),
14103        ("peFuncsM_", "(st: PEMiniState) -> Map of Text to CFunc:"),
14104        ("peDepthM_", "(st: PEMiniState) -> Int:"),
14105        ("peStaticEnvM_", "(st: PEMiniState) -> Map of Text to CExpr:"),
14106        ("peMemoCacheM_", "(st: PEMiniState) -> Map of Text to CExpr:"),
14107        ("peStateWithEnvDepthM_", "(st: PEMiniState) and (newEnv: Map of Text to CVal) and (d: Int) -> PEMiniState:"),
14108        ("peStateWithEnvDepthStaticM_", "(st: PEMiniState) and (newEnv: Map of Text to CVal) and (d: Int) and (newSe: Map of Text to CExpr) -> PEMiniState:"),
14109    ]);
14110
14111    // Discover the PE-generated block entry point — this IS the compiler.
14112    let (block_entry, expr_entry) = discover_entry_points(&result, "peBlockM_", "peExprM_");
14113    if block_entry.is_empty() {
14114        return Err("Genuine P2: no peBlockM_ entry found in residual".to_string());
14115    }
14116
14117    // Strip the ## Main block from the residual — we only need the specialized function
14118    // definitions. The test harness provides its own ## Main.
14119    let func_defs_only = strip_main_block(&result);
14120
14121    // The specialized functions call pe_mini's unspecialized helpers (checkLiteralM,
14122    // valToExprM, etc.) which the PE couldn't fold because their args are dynamic.
14123    // Include the original pe_mini source so these helpers are available.
14124    let pe_mini_helpers = pe_mini_source_text();
14125
14126    // No Rust-generated block wrapper needed — the PE produced a specialized peBlockM_
14127    // function that handles all CStmt variants with specialized expression processing.
14128    // Generate a thin alias for backward compatibility.
14129    let alias = format!(
14130        "\n## To compileBlock (stmts: Seq of CStmt) -> Seq of CStmt:\n    Return {}(stmts).\n",
14131        block_entry
14132    );
14133
14134    // Combine: pe_mini helpers first (authoritative), then specialized functions, then alias.
14135    // Deduplicate: if the decompiled residual redefines a pe_mini function (unspecialized),
14136    // the dedup removes the second definition, keeping the original pe_mini version.
14137    let combined = format!("{}\n{}\n{}", pe_mini_helpers, func_defs_only, alias);
14138    let full_source = deduplicate_functions(&combined);
14139
14140    Ok(GenuineProjectionResult {
14141        source: full_source,
14142        block_entry: "compileBlock".to_string(),
14143        expr_entry,
14144    })
14145}
14146
14147/// Run genuine PE(pe_source, pe_mini(targetStmts)) and return the specialized
14148/// compiler residual as LOGOS source code.
14149///
14150/// This is the actual Futamura Projection 2: the outer PE (pe_source) specializes
14151/// pe_mini's peBlockM with known state (empty env, empty funcs, depth 200).
14152/// The result is a specialized compiler function that takes target statements and
14153/// compiles them with pe_mini's dispatch logic partially evaluated away.
14154///
14155/// Returns the decompiled LOGOS source of the genuine P2 residual, including
14156/// specialized function definitions extracted from peFuncs.
14157pub fn genuine_projection2_residual() -> Result<String, String> {
14158    let pe_mini = pe_mini_source_text();
14159    let pe = pe_source_text();
14160    let decompile = decompile_source_text();
14161
14162    // Build pe_mini program with peBlockM as entry — full block-level specialization
14163    let program = format!(
14164        "{}\n{}\n## Main\n    Let env be a new Map of Text to CVal.\n    Let funcs be a new Map of Text to CFunc.\n    Let state be makePeState(env, funcs, 200).\n    Let result be peBlockM(targetStmts, state).\n    Show \"done\".\n",
14165        CORE_TYPES_FOR_PE, pe_mini
14166    );
14167
14168    // Encode pe_mini + driver as CProgram data (compact encoding)
14169    let encoded = encode_program_source_compact(&program)
14170        .map_err(|e| format!("Failed to encode pe_mini: {}", describe_parse_error(&e)))?;
14171
14172    // Driver: run PE, then decompile residual + specialized functions
14173    let driver = r#"    Let state be makePeState(a new Map of Text to CVal, encodedFuncMap, 200).
14174    Let residual be peBlock(encodedMain, state).
14175    Let nl be chr(10).
14176    Let mutable output be "".
14177    Let specFuncs be peFuncs(state).
14178    Let specNames be collectCallNames(residual).
14179    Repeat for sn in specNames:
14180        Let snKey be "{sn}".
14181        If specFuncs contains snKey:
14182            Let fdef be item snKey of specFuncs.
14183            Let funcSrc be decompileFunc(fdef).
14184            If the length of funcSrc is greater than 0:
14185                Set output to "{output}{funcSrc}{nl}".
14186    Let mainSrc be decompileBlock(residual, 0).
14187    Set output to "{output}## Main{nl}{mainSrc}".
14188    Show output.
14189"#;
14190    let combined = format!(
14191        "{}\n{}\n{}\n## Main\n{}\n{}",
14192        CORE_TYPES_FOR_PE, pe, decompile, encoded, driver
14193    );
14194
14195    let result = with_reference_semantics(|| run_logos_source(&combined))?;
14196    Ok(result)
14197}
14198
14199/// Run genuine PE(pe_source, pe_bti(targetExpr)) and return the specialized
14200/// cogen residual as LOGOS source code.
14201///
14202/// This is the actual Futamura Projection 3: the outer PE (pe_source) specializes
14203/// pe_bti (a full PE with memoization) with known state (empty env, empty funcs,
14204/// depth 200). pe_bti is structurally identical to pe_source with renamed entry
14205/// points (peExprB, peBlockB, etc.) — so this is genuinely PE(PE, PE).
14206///
14207/// The result is a specialized cogen: pe_bti's dispatch partially evaluated away,
14208/// producing a program that takes a target CExpr and compiles it.
14209pub fn genuine_projection3_residual() -> Result<String, String> {
14210    let pe_bti = pe_bti_source_text();
14211    let pe = pe_source_text();
14212    let decompile = decompile_source_text();
14213
14214    // pe_bti uses memoCache/callGuard instead of specResults/onStack
14215    let bti_types = CORE_TYPES_FOR_PE
14216        .replace("specResults", "memoCache")
14217        .replace("onStack", "callGuard");
14218
14219    // Build pe_bti program with peBlockB as entry — full block-level specialization
14220    let program = format!(
14221        "{}\n{}\n## Main\n    Let env be a new Map of Text to CVal.\n    Let funcs be a new Map of Text to CFunc.\n    Let state be makePeState(env, funcs, 200).\n    Let result be peBlockB(targetStmts, state).\n    Show \"done\".\n",
14222        bti_types, pe_bti
14223    );
14224
14225    // Encode pe_bti + driver as CProgram data (compact encoding)
14226    let encoded = encode_program_source_compact(&program)
14227        .map_err(|e| format!("Failed to encode pe_bti: {}", describe_parse_error(&e)))?;
14228
14229    // Driver: run PE, then decompile residual + specialized functions
14230    let driver = r#"    Let state be makePeState(a new Map of Text to CVal, encodedFuncMap, 200).
14231    Let residual be peBlock(encodedMain, state).
14232    Let nl be chr(10).
14233    Let mutable output be "".
14234    Let specFuncs be peFuncs(state).
14235    Let specNames be collectCallNames(residual).
14236    Repeat for sn in specNames:
14237        Let snKey be "{sn}".
14238        If specFuncs contains snKey:
14239            Let fdef be item snKey of specFuncs.
14240            Let funcSrc be decompileFunc(fdef).
14241            If the length of funcSrc is greater than 0:
14242                Set output to "{output}{funcSrc}{nl}".
14243    Let mainSrc be decompileBlock(residual, 0).
14244    Set output to "{output}## Main{nl}{mainSrc}".
14245    Show output.
14246"#;
14247    let combined = format!(
14248        "{}\n{}\n{}\n## Main\n{}\n{}",
14249        CORE_TYPES_FOR_PE, pe, decompile, encoded, driver
14250    );
14251
14252    let result = with_reference_semantics(|| run_logos_source(&combined))?;
14253    Ok(result)
14254}
14255
14256/// Genuine Futamura Projection 3 via self-application: PE(pe_source, pe_bti(targetStmts))
14257///
14258/// The outer PE (pe_source) specializes pe_bti's FULL BLOCK evaluator (a full PE with
14259/// memoization, structurally identical to pe_source with renamed entry points) with
14260/// known state (empty env, empty funcs, depth 200). This is genuinely PE(PE, PE).
14261///
14262/// The result is a specialized cogen: the PE naturally produces block-level dispatch
14263/// through specialization of peBlockB, eliminating the need for a Rust-generated wrapper.
14264pub fn projection3_source_real(_core_types: &str) -> Result<GenuineProjectionResult, String> {
14265    let pe_bti = pe_bti_source_text();
14266    let pe = pe_source_text();
14267    let decompile = decompile_source_text();
14268
14269    // pe_bti uses memoCache/callGuard instead of specResults/onStack
14270    let bti_types = CORE_TYPES_FOR_PE
14271        .replace("specResults", "memoCache")
14272        .replace("onStack", "callGuard");
14273
14274    // Build pe_bti program with peBlockB as entry — FULL block-level specialization.
14275    let program = format!(
14276        "{}\n{}\n## Main\n    Let env be a new Map of Text to CVal.\n    Let funcs be a new Map of Text to CFunc.\n    Let state be makePeState(env, funcs, 200).\n    Let result be peBlockB(targetStmts, state).\n    Show \"done\".\n",
14277        bti_types, pe_bti
14278    );
14279
14280    // Encode pe_bti + driver as CProgram data (compact encoding)
14281    let encoded = encode_program_source_compact(&program).map_err(|e| {
14282        format!(
14283            "Failed to encode pe_bti for P3: {}",
14284            describe_parse_error(&e)
14285        )
14286    })?;
14287
14288    // Driver: fixpoint transitive collection (same algorithm as P2)
14289    let driver = r#"    Let state be makePeState(a new Map of Text to CVal, encodedFuncMap, 200).
14290    Let residual be peBlock(encodedMain, state).
14291    Let nl be chr(10).
14292    Let mutable output be "".
14293    Let specFuncs be peFuncs(state).
14294    Let mutable allNames be collectCallNames(residual).
14295    Let mutable emitted be a new Map of Text to Bool.
14296    Let mutable changed be true.
14297    While changed:
14298        Set changed to false.
14299        Let mutable toAdd be a new Seq of Text.
14300        Repeat for fnKey in allNames:
14301            Let fkStr be "{fnKey}".
14302            If emitted contains fkStr:
14303                Let skipE be true.
14304            Otherwise:
14305                Set item fkStr of emitted to true.
14306                Let fkStr2 be "{fnKey}".
14307                If specFuncs contains fkStr2:
14308                    Let fdef be item fkStr2 of specFuncs.
14309                    Inspect fdef:
14310                        When CFuncDef (fn0, ps0, pt0, rt0, body0):
14311                            Let children be collectCallNames(body0).
14312                            Repeat for child in children:
14313                                Let childStr be "{child}".
14314                                If not emitted contains childStr:
14315                                    Push child to toAdd.
14316                                    Set changed to true.
14317                        Otherwise:
14318                            Let skipF be true.
14319        Repeat for ta in toAdd:
14320            Push ta to allNames.
14321    Repeat for fnKey in allNames:
14322        Let fkStr be "{fnKey}".
14323        If specFuncs contains fkStr:
14324            Let fdef be item fkStr of specFuncs.
14325            Let funcSrc be decompileFunc(fdef).
14326            If the length of funcSrc is greater than 0:
14327                Set output to "{output}{funcSrc}{nl}".
14328    Let mainSrc be decompileBlock(residual, 0).
14329    Set output to "{output}## Main{nl}{mainSrc}".
14330    Show output.
14331"#;
14332    let combined = format!(
14333        "{}\n{}\n{}\n## Main\n{}\n{}",
14334        CORE_TYPES_FOR_PE, pe, decompile, encoded, driver
14335    );
14336
14337    let result = with_reference_semantics(|| run_logos_source(&combined))?;
14338
14339    // Fix decompiled types for pe_bti specialized functions (B suffix)
14340    // Fix decompiled types for pe_bti specialized functions (B suffix)
14341    let result = fix_decompiled_types(
14342        &result,
14343        &[
14344            ("peExprB_", "(e: CExpr) -> CExpr:"),
14345            ("peBlockB_", "(stmts: Seq of CStmt) -> Seq of CStmt:"),
14346            ("isStatic_", "(e: CExpr) -> Bool:"),
14347            ("isLiteral_", "(e: CExpr) -> Bool:"),
14348            ("allStatic_", "(args: Seq of CExpr) -> Bool:"),
14349            ("exprToVal_", "(e: CExpr) -> CVal:"),
14350            ("valToExpr_", "(v: CVal) -> CExpr:"),
14351            (
14352                "evalBinOp_",
14353                "(binOp: Text) and (lv: CVal) and (rv: CVal) -> CVal:",
14354            ),
14355            ("isCopyPropSafe_", "(e: CExpr) -> Bool:"),
14356            ("isVNothing_", "(v: CVal) -> Bool:"),
14357            ("hasReturn_", "(stmts: Seq of CStmt) -> Bool:"),
14358            ("extractReturnB_", "(stmts: Seq of CStmt) -> CExpr:"),
14359            (
14360                "makeKey_",
14361                "(fnName: Text) and (args: Seq of CExpr) -> Text:",
14362            ),
14363            ("exprToKeyPartB_", "(e: CExpr) -> Text:"),
14364            ("collectSetVars_", "(stmts: Seq of CStmt) -> Seq of Text:"),
14365        ],
14366    );
14367
14368    // Discover the PE-generated block entry point — this IS the cogen.
14369    let (block_entry, expr_entry) = discover_entry_points(&result, "peBlockB_", "peExprB_");
14370    if block_entry.is_empty() {
14371        return Err("Genuine P3: no peBlockB_ entry found in residual".to_string());
14372    }
14373
14374    // Strip the ## Main block — we only need the specialized function definitions
14375    let func_defs_only = strip_main_block(&result);
14376
14377    // Include pe_bti helpers (unspecialized functions called by specialized ones)
14378    let pe_bti_helpers = pe_bti_source_text();
14379
14380    // No Rust-generated block wrapper needed — the PE produced a specialized peBlockB_
14381    // function. Generate a thin alias for backward compatibility.
14382    let alias = format!(
14383        "\n## To cogenBlock (stmts: Seq of CStmt) -> Seq of CStmt:\n    Return {}(stmts).\n",
14384        block_entry
14385    );
14386    let combined = format!("{}\n{}\n{}", pe_bti_helpers, func_defs_only, alias);
14387    let full_source = deduplicate_functions(&combined);
14388
14389    Ok(GenuineProjectionResult {
14390        source: full_source,
14391        block_entry: "cogenBlock".to_string(),
14392        expr_entry,
14393    })
14394}
14395
14396/// Remove duplicate function definitions, keeping the first occurrence.
14397fn deduplicate_functions(source: &str) -> String {
14398    let mut seen = std::collections::HashSet::new();
14399    let mut result = String::with_capacity(source.len());
14400    let mut skip_until_next = false;
14401    for line in source.lines() {
14402        let trimmed = line.trim();
14403        if let Some(rest) = trimmed.strip_prefix("## To ") {
14404            let name = rest.split(' ').next().unwrap_or("");
14405            if !seen.insert(name.to_string()) {
14406                skip_until_next = true;
14407                continue;
14408            }
14409            skip_until_next = false;
14410        } else if trimmed.starts_with("## Main") {
14411            skip_until_next = false;
14412        } else if skip_until_next {
14413            // Skip body of duplicate function
14414            if !trimmed.starts_with("## ") {
14415                continue;
14416            }
14417            skip_until_next = false;
14418        }
14419        result.push_str(line);
14420        result.push('\n');
14421    }
14422    result
14423}
14424
14425/// Strip the ## Main block from decompiled source, keeping only function definitions.
14426/// The genuine residual's ## Main references internal PE variables (targetExpr, blockResult)
14427/// that don't exist in the test context. We only need the specialized function definitions.
14428fn strip_main_block(source: &str) -> String {
14429    let mut result = String::with_capacity(source.len());
14430    let mut in_main = false;
14431    for line in source.lines() {
14432        let trimmed = line.trim();
14433        if trimmed == "## Main" {
14434            in_main = true;
14435            continue;
14436        }
14437        if in_main {
14438            // Main block ends when we hit another ## To definition or end of file
14439            if trimmed.starts_with("## To ") {
14440                in_main = false;
14441            } else {
14442                continue;
14443            }
14444        }
14445        result.push_str(line);
14446        result.push('\n');
14447    }
14448    result
14449}
14450
14451/// Extract the ## Main block content from source.
14452fn extract_main_block(source: &str) -> String {
14453    let mut result = String::new();
14454    let mut in_main = false;
14455    for line in source.lines() {
14456        let trimmed = line.trim();
14457        if trimmed == "## Main" {
14458            in_main = true;
14459            continue;
14460        }
14461        if in_main {
14462            if trimmed.starts_with("## To ") {
14463                break;
14464            }
14465            result.push_str(line);
14466            result.push('\n');
14467        }
14468    }
14469    result
14470}
14471
14472/// Fix decompiled function signatures: replace `(param: Any) -> Any:` with correct types.
14473/// PE-generated specializations still use "Any" for types the PE couldn't propagate.
14474/// This restores correct types based on function name prefixes.
14475fn fix_decompiled_types(source: &str, type_map: &[(&str, &str)]) -> String {
14476    let mut result = String::with_capacity(source.len());
14477    for line in source.lines() {
14478        let trimmed = line.trim();
14479        if let Some(rest) = trimmed.strip_prefix("## To ") {
14480            let name = rest.split(' ').next().unwrap_or("");
14481            let mut fixed = false;
14482            for (prefix, sig) in type_map {
14483                if name.starts_with(prefix) {
14484                    result.push_str(&format!("## To {} {}\n", name, sig));
14485                    fixed = true;
14486                    break;
14487                }
14488            }
14489            if !fixed {
14490                result.push_str(line);
14491                result.push('\n');
14492            }
14493        } else {
14494            result.push_str(line);
14495            result.push('\n');
14496        }
14497    }
14498    let result = result
14499        .replace("Seq of Any", "Seq of CExpr")
14500        .replace("Set of Any", "Set of CExpr")
14501        .replace(": Any)", ": CExpr)")
14502        .replace("-> Any:", "-> CExpr:");
14503    result
14504}
14505
14506fn replace_word(source: &str, from: &str, to: &str) -> String {
14507    let mut result = String::with_capacity(source.len());
14508    let mut remaining = source;
14509    while let Some(pos) = remaining.find(from) {
14510        let before = if pos > 0 {
14511            remaining.as_bytes()[pos - 1]
14512        } else {
14513            b' '
14514        };
14515        let after_pos = pos + from.len();
14516        let after = if after_pos < remaining.len() {
14517            remaining.as_bytes()[after_pos]
14518        } else {
14519            b' '
14520        };
14521        let is_word = !before.is_ascii_alphanumeric()
14522            && before != b'_'
14523            && !after.is_ascii_alphanumeric()
14524            && after != b'_';
14525        result.push_str(&remaining[..pos]);
14526        if is_word {
14527            result.push_str(to);
14528        } else {
14529            result.push_str(from);
14530        }
14531        remaining = &remaining[after_pos..];
14532    }
14533    result.push_str(remaining);
14534    result
14535}
14536
14537#[cfg(test)]
14538#[path = "../../logicaffeine_tests/unit/logicaffeine_compile/compile/tests.rs"]
14539mod tests;