Skip to main content

aver/codegen/
mod.rs

1/// Aver → target language transpilation.
2///
3/// The codegen module transforms a type-checked Aver AST into source code
4/// for a target language. Current backends: Rust deployment and Lean proof export.
5pub(crate) mod builtin_helpers;
6pub(crate) mod builtin_records;
7pub(crate) mod builtins;
8pub mod common;
9#[cfg(feature = "runtime")]
10pub mod dafny;
11#[cfg(feature = "runtime")]
12pub mod lean;
13pub mod program_view;
14#[cfg(feature = "runtime")]
15pub mod proof_lower;
16#[cfg(feature = "runtime")]
17pub mod recursion;
18#[cfg(feature = "runtime")]
19pub mod rust;
20pub mod scc;
21#[cfg(feature = "wasip2")]
22pub mod wasip2;
23#[cfg(feature = "wasm-compile")]
24pub mod wasm_gc;
25
26use std::collections::{HashMap, HashSet};
27
28use crate::ast::{FnDef, TopLevel, TypeDef};
29use crate::source::LoadedModule;
30use crate::types::checker::TypeCheckResult;
31
32/// Information about a dependent module loaded for codegen.
33pub struct ModuleInfo {
34    /// Qualified module path, e.g. "Models.User".
35    pub prefix: String,
36    /// Direct `depends [...]` entries from the source module.
37    pub depends: Vec<String>,
38    /// Type definitions from the module.
39    pub type_defs: Vec<TypeDef>,
40    /// Function definitions from the module (excluding `main`).
41    pub fn_defs: Vec<FnDef>,
42    /// IR-level analysis facts produced by the dep module's pipeline run
43    /// (`analyze` stage). `None` for modules loaded via paths that skip
44    /// the analyze stage (none in production today; left optional for
45    /// future ad-hoc loaders). Aver's module DAG invariant makes per-module
46    /// analysis sufficient — see `project_aver_module_dag` memory and
47    /// `src/ir/analyze.rs` for why cross-module SCCs are impossible.
48    pub analysis: Option<crate::ir::AnalysisResult>,
49}
50
51impl ModuleInfo {
52    /// Build a [`ModuleInfo`] from a freshly-parsed [`LoadedModule`].
53    /// Skips the analyze stage — callers that need per-dep analysis
54    /// facts should run the pipeline themselves (see
55    /// `crate::main::commands::load_compile_deps` /
56    /// `playground::loaded_to_module_info`). Used by ad-hoc loaders
57    /// (`vm_profile`, the eval-spec test helpers) that just need the
58    /// dep's symbol layout to feed `SymbolTable::build` /
59    /// `pipeline::run`'s `dep_modules` slot.
60    pub fn from_loaded(loaded: &LoadedModule) -> Self {
61        let depends = loaded
62            .items
63            .iter()
64            .find_map(|i| match i {
65                TopLevel::Module(m) => Some(m.depends.clone()),
66                _ => None,
67            })
68            .unwrap_or_default();
69        let type_defs = loaded
70            .items
71            .iter()
72            .filter_map(|i| match i {
73                TopLevel::TypeDef(td) => Some(td.clone()),
74                _ => None,
75            })
76            .collect();
77        let fn_defs = loaded
78            .items
79            .iter()
80            .filter_map(|i| match i {
81                TopLevel::FnDef(fd) if fd.name != "main" => Some(fd.clone()),
82                _ => None,
83            })
84            .collect();
85        Self {
86            prefix: loaded.dep_name.clone(),
87            depends,
88            type_defs,
89            fn_defs,
90            analysis: None,
91        }
92    }
93}
94
95/// Collected context from the Aver program, shared across all backends.
96///
97/// # Invariant (epic #170 Phase 2)
98///
99/// **`resolved_program` is the primary backend input.** Every
100/// identity-sensitive decision (call/ctor/type lookup, fn-by-id
101/// dispatch, mutual-SCC analysis) belongs to that view; the
102/// pipeline produced it once and `build_context` projects it through.
103///
104/// The legacy AST-shape fields below — `items`, `fn_defs`,
105/// `type_defs`, `resolved_fn_defs`, `resolved_module_fn_defs` — are
106/// **source metadata / migration caches**, not independent sources
107/// of truth:
108///
109/// - `items`, `fn_defs`, `type_defs` retain source-shape spans and
110///   diagnostics; backends mid-migration still walk them. They are
111///   NOT the place to add new identity-sensitive logic.
112/// - `resolved_fn_defs` / `resolved_module_fn_defs` are projections
113///   of `resolved_program` kept for callsites that don't yet route
114///   through the `FnId` index. New code should reach
115///   `resolved_program.fn_by_id(fn_id)` instead.
116///
117/// Subsequent epic phases migrate backends (Rust, Lean, Dafny,
118/// wasm-gc) to iterate the view directly. New code in backends
119/// should default to the view. AST consumption requires a clear
120/// category in a code comment: `diagnostic-only`,
121/// `syntax-discovery-only`, `backend-link-stage`, `display-only`,
122/// or `temporary-migration-bridge`.
123pub struct CodegenContext {
124    /// All top-level items (post-TCO transform, post-typecheck).
125    ///
126    /// **Source metadata** — kept for span / diagnostic / syntax
127    /// discovery access. Backends iterating fn bodies should reach
128    /// `resolved_program.entry_fns()` instead.
129    pub items: Vec<TopLevel>,
130    /// Functions eligible for auto-memoization.
131    pub memo_fns: HashSet<String>,
132    /// Set of type names whose values are memo-safe.
133    pub memo_safe_types: HashSet<String>,
134    /// User-defined type definitions (for struct/enum generation).
135    ///
136    /// **Source metadata.** Type-id-keyed lookups go through
137    /// `symbol_table` (see [`Self::symbol_table`]); fn bodies that
138    /// need a resolved type reach it via `Type::Named(TypeId, _)`
139    /// after the typechecker stamps. This list stays for ergonomic
140    /// iteration over user-declared types in syntax-discovery sites
141    /// (e.g. cataloguing all `enum` declarations for the proof
142    /// pipeline's refinement detection).
143    pub type_defs: Vec<TypeDef>,
144    /// User-defined function definitions.
145    ///
146    /// **Source metadata.** Backends mid-migration walk this for
147    /// fn-signature shape; new identity-sensitive code reaches
148    /// `resolved_program.entry_fns()` / `fn_by_id(fn_id)` instead.
149    /// Synthesized FnDefs (memo wrappers, TCO hoists) appended after
150    /// the pipeline ran live here too; the on-demand resolver
151    /// (`Self::resolve_fn_def`) lifts them through the symbol table.
152    pub fn_defs: Vec<FnDef>,
153    /// Project/binary name.
154    pub project_name: String,
155    /// Dependent modules loaded for inlining.
156    pub modules: Vec<ModuleInfo>,
157    /// Set of module prefixes for qualified name resolution (e.g. "Models.User").
158    pub module_prefixes: HashSet<String>,
159    /// Embedded runtime policy from `aver.toml` for generated code.
160    #[cfg(feature = "runtime")]
161    pub policy: Option<crate::config::ProjectConfig>,
162    /// Emit generated scoped runtime support (replay and/or runtime-loaded policy).
163    pub emit_replay_runtime: bool,
164    /// Load runtime policy from the active module root instead of embedding it.
165    pub runtime_policy_from_env: bool,
166    /// Explicit guest entry boundary for scoped replay/policy.
167    pub guest_entry: Option<String>,
168    /// Emit extra generated helpers needed only by the cached self-host helper.
169    pub emit_self_host_support: bool,
170    /// Extra fn_defs visible during current module emission (not in `fn_defs` or `modules`).
171    /// Set temporarily by the Rust backend when emitting a dependent module so that
172    /// `find_fn_def_by_name` can resolve same-module calls.
173    pub extra_fn_defs: Vec<FnDef>,
174    /// Functions that are part of a mutual-TCO SCC group (emitted as
175    /// trampoline + wrappers). Functions NOT in this set but with
176    /// TailCalls are emitted as plain self-TCO loops. Keyed by opaque
177    /// [`crate::ir::FnId`] from the symbol table — entry-module fns
178    /// and dep-module fns with the same bare name can't accidentally
179    /// merge under bare-name keying.
180    pub mutual_tco_members: HashSet<crate::ir::FnId>,
181    /// Functions that call themselves directly or transitively. Set-
182    /// form union of `entry_analysis.recursive_fns` plus each
183    /// module's `analysis.recursive_fns`. Keyed by opaque
184    /// [`crate::ir::FnId`] — same disambiguation guarantee as
185    /// `mutual_tco_members`. Used by codegen sites that previously
186    /// called `call_graph::find_recursive_fns` ad-hoc.
187    pub recursive_fns: HashSet<crate::ir::FnId>,
188    /// Buffer-build sink fns (`List.prepend`/`reverse` builders consumed
189    /// by `String.join`). The Rust backend emits a `<fn>__buffered`
190    /// variant alongside each entry; the WASM backend rewrites bodies
191    /// to call `rt_buffer_*` helpers. Detection lives in `ir::buffer_build`.
192    pub buffer_build_sinks: HashMap<String, crate::ir::BufferBuildShape>,
193    /// Fusion sites detected for `String.join(<sink>(...), sep)` calls.
194    /// Each entry pairs an enclosing fn + line + sink fn name; the
195    /// emitter rewrites these call expressions to use buffered variants
196    /// in place of the producer + consumer chain.
197    pub buffer_fusion_sites: Vec<crate::ir::FusionSite>,
198    /// Synthesized `<fn>__buffered` variants for every buffer-build
199    /// sink, produced by `ir::synthesize_buffered_variants`. These are
200    /// real `FnDef`s with proper body AST; backends iterate over them
201    /// alongside `fn_defs` so they reach codegen through the same
202    /// pipeline (TCO / no-alloc / mutual-recursion all apply
203    /// identically). Empty when no sinks are detected.
204    pub synthesized_buffered_fns: Vec<FnDef>,
205    /// Proof-export decision IR populated by `proof_lower::lower`
206    /// during `build_context`. Backends (Lean, Dafny) read from
207    /// here to decide refinement-record lift, recursion contracts,
208    /// law-theorem shape, etc. Single source of truth — both
209    /// backends see the same decisions so cross-backend drift
210    /// becomes impossible at the shape level. Step 2: only
211    /// `refined_types` is populated; backends still consume legacy
212    /// `refinement_info_for` for now. Step 3+ migrates backends.
213    #[cfg(feature = "runtime")]
214    pub proof_ir: crate::ir::ProofIR,
215    /// Resolved-identity table (#138 phase E). Always populated:
216    /// `pipeline::run` builds it unconditionally and threads it
217    /// through `build_context`. Consumers (proof IR lookups,
218    /// backend FnId/TypeId resolution) read it directly — no
219    /// `Option` wrapper to unwrap at each callsite.
220    pub symbol_table: crate::ir::SymbolTable,
221    /// Resolved-HIR forms of every entry-scope fn in `fn_defs`,
222    /// in the same source order.
223    ///
224    /// **Compatibility projection of `resolved_program.entry_fns()`**
225    /// (epic #170 Phase 1). Position-aligned with the entry slice of
226    /// `resolved_program.entry_items`. New code should prefer
227    /// `resolved_program.entry_fns()` / `fn_by_id(fn_id)` so the
228    /// `FnId` index is the lookup mechanism. This vec stays for
229    /// callsites that haven't yet been migrated to the view; it will
230    /// be retired once Phase 3-6 migrate all backends.
231    pub resolved_fn_defs: Vec<crate::ir::hir::ResolvedFnDef>,
232    /// Module scope currently active for name resolution. Set by a
233    /// backend dispatcher before emitting a dep-module's fns so that
234    /// legacy resolve-on-demand adapters (e.g. Lean's
235    /// `emit_expr_legacy`) thread the right scope into
236    /// `resolve_expr` / `resolve_stmt` instead of defaulting to entry.
237    /// Empty by default. Set with [`Self::with_module_scope`] in a
238    /// scoped manner.
239    pub current_module_scope: std::cell::RefCell<Option<String>>,
240    /// Per-dep resolved fn defs, parallel to `modules`.
241    ///
242    /// **Compatibility projection of `resolved_program.modules[i].fn_defs`**
243    /// (epic #170 Phase 1). Position-aligned with `modules` for
244    /// callsites that index by `modules[i]`. New code should prefer
245    /// `resolved_program.module_fns(prefix)` or the global
246    /// `fn_by_id(fn_id)` index — that's where cross-module bare-name
247    /// disambiguation happens for free. Retired alongside
248    /// `resolved_fn_defs` once Phase 3-6 migrate the remaining
249    /// backends.
250    pub resolved_module_fn_defs: Vec<Vec<crate::ir::hir::ResolvedFnDef>>,
251    /// Canonical resolved-program view of the whole codegen input —
252    /// entry items (post-pipeline `NameResolve`) + per-dep-module
253    /// resolved fn defs + `FnId`-keyed lookup.
254    ///
255    /// **Epic #170 Phase 1 invariant.** `resolved_program` is the
256    /// primary source of truth for backend codegen — `fn_defs`,
257    /// `type_defs`, `items`, `resolved_fn_defs`, and
258    /// `resolved_module_fn_defs` remain available as projection /
259    /// source metadata / migration cache, but consumers should reach
260    /// the view first when an `FnId` / `TypeId` is in hand. Subsequent
261    /// phases (#170 Phase 3+) migrate backends to iterate the view as
262    /// their primary input; this field is the foundation those PRs
263    /// build on.
264    pub resolved_program: crate::codegen::program_view::ResolvedProgramView,
265}
266
267/// Output files from a codegen backend.
268pub struct ProjectOutput {
269    /// Files to write: (relative_path, content).
270    pub files: Vec<(String, String)>,
271}
272
273/// Build a CodegenContext from parsed + type-checked items.
274///
275/// `entry_analysis` is the `analyze` stage output for `items` (entry
276/// module). When provided, codegen reads `mutual_tco_members`,
277/// `recursive_fns`, and per-fn `FnAnalysis` from it instead of recomputing.
278/// Each `ModuleInfo` in `modules` carries its own per-module analysis;
279/// codegen unions the per-module sets to build a global view (sound
280/// under Aver's module DAG invariant — no cross-module SCCs possible,
281/// see `src/ir/analyze.rs` doc).
282///
283/// `symbol_table` is the resolved-identity layer built by the
284/// pipeline (`pipeline_result.symbol_table`). Always required:
285/// `pipeline::run` builds it unconditionally so every caller has
286/// one available. The ad-hoc test helpers that drive a stripped
287/// pipeline build their own via `SymbolTable::build(&items,
288/// &modules)` and pass it here.
289#[allow(clippy::too_many_arguments)]
290pub fn build_context(
291    items: Vec<TopLevel>,
292    tc_result: &TypeCheckResult,
293    entry_analysis: Option<&crate::ir::AnalysisResult>,
294    memo_fns: HashSet<String>,
295    project_name: String,
296    modules: Vec<ModuleInfo>,
297    symbol_table: crate::ir::SymbolTable,
298    resolved_items: Vec<crate::ir::hir::ResolvedTopLevel>,
299) -> CodegenContext {
300    let type_defs: Vec<TypeDef> = items
301        .iter()
302        .filter_map(|item| {
303            if let TopLevel::TypeDef(td) = item {
304                Some(td.clone())
305            } else {
306                None
307            }
308        })
309        .collect();
310
311    let fn_defs: Vec<FnDef> = items
312        .iter()
313        .filter_map(|item| {
314            if let TopLevel::FnDef(fd) = item {
315                Some(fd.clone())
316            } else {
317                None
318            }
319        })
320        .collect();
321
322    let module_prefixes: HashSet<String> = modules.iter().map(|m| m.prefix.clone()).collect();
323
324    // Mutual-TCO membership unions per-scope sets from the analyze
325    // stage (entry's `entry_analysis` + each dep module's
326    // `module.analysis`); falls back to recomputing per-scope via
327    // `call_graph::tailcall_scc_components` when no analysis ran.
328    // Aver's module DAG invariant guarantees SCCs never span
329    // modules — per-scope union is the correct global view (see
330    // `project_aver_module_dag` memory + `src/ir/analyze.rs`). The
331    // FnId resolution happens inside the `scc` wrappers below.
332    let mut mutual_tco_members: HashSet<crate::ir::FnId> = HashSet::new();
333    match entry_analysis {
334        Some(a) => mutual_tco_members.extend(scc::analysis_set_to_fn_ids(
335            &a.mutual_tco_members,
336            &symbol_table,
337            None,
338        )),
339        None => {
340            // No entry analysis: compute the per-scope SCC set inline
341            // via `call_graph` and project to FnIds. Same effect as
342            // running the analyze stage's mutual-TCO discovery.
343            // **syntax-discovery-only** (epic #170 Phase 8 guardrail):
344            // `entry_fns` is filtered from `fn_defs` — the entry-scope
345            // FnDef vec — so `FnKey::entry(&fd.name)` below is the
346            // correct keying by construction (every `fd` here is
347            // entry-scope).
348            let entry_fns: Vec<&FnDef> = fn_defs.iter().filter(|fd| fd.name != "main").collect();
349            for group in crate::call_graph::tailcall_scc_components(&entry_fns) {
350                if group.len() < 2 {
351                    continue;
352                }
353                for fd in group {
354                    if let Some(id) = symbol_table.fn_id_of(&crate::ir::FnKey::entry(&fd.name)) {
355                        mutual_tco_members.insert(id);
356                    }
357                }
358            }
359        }
360    }
361    for module in &modules {
362        match module.analysis.as_ref() {
363            Some(a) => mutual_tco_members.extend(scc::analysis_set_to_fn_ids(
364                &a.mutual_tco_members,
365                &symbol_table,
366                Some(&module.prefix),
367            )),
368            None => {
369                let mod_fns: Vec<&FnDef> = module.fn_defs.iter().collect();
370                for group in crate::call_graph::tailcall_scc_components(&mod_fns) {
371                    if group.len() < 2 {
372                        continue;
373                    }
374                    for fd in group {
375                        if let Some(id) = symbol_table.fn_id_of(&crate::ir::FnKey::in_module(
376                            module.prefix.clone(),
377                            &fd.name,
378                        )) {
379                            mutual_tco_members.insert(id);
380                        }
381                    }
382                }
383            }
384        }
385    }
386
387    // `recursive_fns` follows the same shape — per-scope union with
388    // analyze-stage fallback. Keyed by opaque `FnId` so entry +
389    // dep-module same-bare-name fns stay distinct.
390    let mut recursive_fns: HashSet<crate::ir::FnId> = HashSet::new();
391    match entry_analysis {
392        Some(a) => recursive_fns.extend(scc::analysis_set_to_fn_ids(
393            &a.recursive_fns,
394            &symbol_table,
395            None,
396        )),
397        None => recursive_fns.extend(scc::bare_names_to_fn_ids(
398            crate::call_graph::find_recursive_fns(&items)
399                .iter()
400                .map(String::as_str),
401            &symbol_table,
402            None,
403        )),
404    }
405    for module in &modules {
406        match module.analysis.as_ref() {
407            Some(a) => recursive_fns.extend(scc::analysis_set_to_fn_ids(
408                &a.recursive_fns,
409                &symbol_table,
410                Some(&module.prefix),
411            )),
412            None => {
413                let mod_items: Vec<TopLevel> = module
414                    .fn_defs
415                    .iter()
416                    .map(|fd| TopLevel::FnDef(fd.clone()))
417                    .collect();
418                recursive_fns.extend(scc::bare_names_to_fn_ids(
419                    crate::call_graph::find_recursive_fns(&mod_items)
420                        .iter()
421                        .map(String::as_str),
422                    &symbol_table,
423                    Some(&module.prefix),
424                ));
425            }
426        }
427    }
428
429    // Detection layer for buffer-build sinks + fusion sites. The
430    // ACTUAL rewrite + synthesis must happen BEFORE the resolver
431    // pass (callers run it via `ir::run_buffer_build_pass` between
432    // TCO and resolver) — the detector matches on `Expr::Ident`
433    // shapes that resolver later rewrites to `Expr::Resolved`. We
434    // rerun detection here against the final items so the resulting
435    // ctx fields reflect what's actually in the AST. With pre-
436    // resolver pass having already run, sinks/sites should be the
437    // same set (sinks are fns, not call sites; fusion sites were
438    // rewritten away so the post-rewrite count is zero in normal flow).
439    let detect_fns: Vec<&FnDef> = fn_defs
440        .iter()
441        .chain(modules.iter().flat_map(|m| m.fn_defs.iter()))
442        .collect();
443    let buffer_build_sinks = crate::ir::compute_buffer_build_sinks(&detect_fns);
444    let buffer_fusion_sites = crate::ir::find_fusion_sites(&detect_fns, &buffer_build_sinks);
445    // The synthesizer already ran in the pre-resolver compile pass
446    // (`ir::run_buffer_build_pass`); the resulting `<fn>__buffered`
447    // variants live in `items` (or in dep `module.fn_defs`) directly,
448    // so we just collect references for the ctx field instead of
449    // re-synthesizing — re-running here would duplicate every fn
450    // and confuse the WASM emitter's fn_indices table.
451    let synthesized_buffered_fns: Vec<FnDef> = fn_defs
452        .iter()
453        .chain(modules.iter().flat_map(|m| m.fn_defs.iter()))
454        .filter(|fd| fd.name.ends_with("__buffered"))
455        .cloned()
456        .collect();
457
458    // Epic #170 Phase 1: build the canonical `ResolvedProgramView`
459    // once, from the pipeline's already-resolved entry items + the
460    // dep modules' AST fn defs. The view does the module-side
461    // resolution (pinning `ResolveCtx.current_module = Some(prefix)`)
462    // — that's the only producer in the codebase. `resolved_fn_defs`
463    // / `resolved_module_fn_defs` then project FROM the view rather
464    // than running an independent second resolve, eliminating the
465    // "two truths" hazard build_context carried since PR 9.
466    let resolved_program = crate::codegen::program_view::ResolvedProgramView::build(
467        resolved_items,
468        &modules,
469        &symbol_table,
470    );
471    let resolved_fn_defs: Vec<crate::ir::hir::ResolvedFnDef> =
472        resolved_program.entry_fns().cloned().collect();
473    let resolved_module_fn_defs: Vec<Vec<crate::ir::hir::ResolvedFnDef>> = resolved_program
474        .modules
475        .iter()
476        .map(|m| m.fn_defs.clone())
477        .collect();
478
479    let ctx = CodegenContext {
480        items,
481        memo_fns,
482        memo_safe_types: tc_result.memo_safe_types.clone(),
483        type_defs,
484        fn_defs,
485        project_name,
486        modules,
487        module_prefixes,
488        #[cfg(feature = "runtime")]
489        policy: None,
490        emit_replay_runtime: false,
491        runtime_policy_from_env: false,
492        guest_entry: None,
493        emit_self_host_support: false,
494        extra_fn_defs: Vec::new(),
495        mutual_tco_members,
496        recursive_fns,
497        buffer_build_sinks,
498        buffer_fusion_sites,
499        synthesized_buffered_fns,
500        #[cfg(feature = "runtime")]
501        proof_ir: crate::ir::ProofIR::default(),
502        // Symbol table threaded through from the pipeline (or
503        // built locally in fallback). The FnId-keyed `recursive_
504        // fns` / `mutual_tco_members` above used it; backends
505        // (proof_lower / Lean / Rust / Dafny) read it directly off
506        // ctx for opaque-ID lookups.
507        symbol_table,
508        resolved_fn_defs,
509        resolved_module_fn_defs,
510        current_module_scope: std::cell::RefCell::new(None),
511        resolved_program,
512    };
513    // ProofIR no longer populated here. Pipeline owns the lowerings
514    // (`PipelineStage::RefinementLower`, `PipelineStage::ContractLower`);
515    // proof backends opt in via `PipelineConfig.run_refinement_lower` /
516    // `run_contract_lower` and read `pipeline_result.proof_ir` back.
517    // Runtime backends (VM / WASM / Rust) leave both off and skip the
518    // work. Tests that bypass the pipeline assemble the ctx by hand
519    // and call `refresh_facts()` to populate the field — the field
520    // stays `default()` here for those callers until they explicitly
521    // refresh.
522    ctx
523}
524
525impl CodegenContext {
526    /// Set `current_module_scope` for the duration of `f`. Backends
527    /// wrap their per-module emit calls with this so legacy
528    /// resolve-on-demand adapters see the correct prefix.
529    pub fn with_module_scope<R>(&self, scope: Option<&str>, f: impl FnOnce() -> R) -> R {
530        let prev = self
531            .current_module_scope
532            .replace(scope.map(|s| s.to_string()));
533        let out = f();
534        *self.current_module_scope.borrow_mut() = prev;
535        out
536    }
537
538    /// Snapshot of the active module scope. Cloned so callers may
539    /// pass `as_deref()` into resolver/emitter APIs without holding
540    /// the `RefCell` borrow.
541    pub fn active_module_scope(&self) -> Option<String> {
542        self.current_module_scope.borrow().clone()
543    }
544
545    /// Identity-keyed lookup from a bare fn name + scope to the
546    /// matching `&FnDef` in `fn_defs` / `modules[i].fn_defs`. Resolves
547    /// the name through the symbol table to an `FnId` first, then
548    /// recovers the AST `FnDef` via `fn_id_for_decl` pointer-eq scope
549    /// matching — so two same-bare-name fns across modules can't
550    /// cross-resolve.
551    ///
552    /// **Epic #170 Phase 5 helper.** Replaces the
553    /// `ctx.fn_defs.iter().find(|fd| fd.name == name)` pattern that
554    /// proof-mode law / verify rewriters used pre-migration. Backends
555    /// that still need a `&FnDef` (rather than the resolved twin —
556    /// e.g. `rewrite_effectful_calls_in_law` consumes AST shape)
557    /// reach this method instead of walking by bare name.
558    ///
559    /// Returns `None` when the symbol table doesn't know the name
560    /// under the given scope, or when the resolved `FnId` doesn't
561    /// match any `&FnDef` in that scope (synthetic FnDefs added
562    /// post-pipeline fall through here — callers can fallback to a
563    /// bare-name walk over `extra_fn_defs` etc. when that matters).
564    pub fn fn_def_by_name(&self, name: &str, scope: Option<&str>) -> Option<&FnDef> {
565        use crate::ir::FnKey;
566        let key = match scope {
567            Some(prefix) => FnKey::in_module(prefix.to_string(), name),
568            None => FnKey::entry(name),
569        };
570        let fn_id = self.symbol_table.fn_id_of(&key)?;
571        let matches = |fd: &&FnDef| crate::codegen::common::fn_id_for_decl(self, fd) == Some(fn_id);
572        match scope {
573            None => self.fn_defs.iter().find(matches),
574            Some(prefix) => self
575                .modules
576                .iter()
577                .find(|m| m.prefix == prefix)?
578                .fn_defs
579                .iter()
580                .find(matches),
581        }
582    }
583}
584
585impl CodegenContext {
586    /// Test-only bridge: recompute every derived fact
587    /// (`mutual_tco_members`, `recursive_fns`, `proof_ir`,
588    /// `resolved_program`) from the current `items` and `modules`.
589    /// Used exclusively by unit tests that construct a
590    /// `CodegenContext` piecewise — pushing synthetic `FnDef`s
591    /// straight into the items list rather than going through the
592    /// parser and pipeline. Production code never needs this: every
593    /// derived fact is populated by the pipeline stages (analyze,
594    /// proof_lower) and propagated through `build_context`. Calling
595    /// `refresh_facts` on a production-built ctx is redundant work
596    /// that produces the same answer — leave it off the hot path.
597    ///
598    /// **Single-source-of-truth invariant** (epic #170 Phase 1+2):
599    /// rebuilds `resolved_program` once from the freshly-resolved
600    /// items, then derives `resolved_fn_defs` /
601    /// `resolved_module_fn_defs` as projections of that view. There
602    /// is no parallel resolve path here.
603    pub fn refresh_facts(&mut self) {
604        // Synthetic-ctx path must own its symbol table too — FnId-
605        // keyed sets below resolve through it, same shape as the
606        // production `build_context` flow.
607        let symbol_table = crate::ir::SymbolTable::build(&self.items, &self.modules);
608        let entry_fn_id = |name: &str| -> Option<crate::ir::FnId> {
609            symbol_table.fn_id_of(&crate::ir::FnKey::entry(name))
610        };
611        let module_fn_id = |prefix: &str, name: &str| -> Option<crate::ir::FnId> {
612            symbol_table.fn_id_of(&crate::ir::FnKey::in_module(prefix.to_string(), name))
613        };
614
615        let entry_fn_refs: Vec<&FnDef> =
616            self.fn_defs.iter().filter(|fd| fd.name != "main").collect();
617
618        let mut mutual_tco_members: HashSet<crate::ir::FnId> = HashSet::new();
619        for group in crate::call_graph::tailcall_scc_components(&entry_fn_refs) {
620            if group.len() < 2 {
621                continue;
622            }
623            for fd in group {
624                if let Some(id) = entry_fn_id(&fd.name) {
625                    mutual_tco_members.insert(id);
626                }
627            }
628        }
629        for module in &self.modules {
630            let mod_fns: Vec<&FnDef> = module.fn_defs.iter().collect();
631            for group in crate::call_graph::tailcall_scc_components(&mod_fns) {
632                if group.len() < 2 {
633                    continue;
634                }
635                for fd in group {
636                    if let Some(id) = module_fn_id(&module.prefix, &fd.name) {
637                        mutual_tco_members.insert(id);
638                    }
639                }
640            }
641        }
642        self.mutual_tco_members = mutual_tco_members;
643
644        let mut recursive_fns: HashSet<crate::ir::FnId> = scc::bare_names_to_fn_ids(
645            crate::call_graph::find_recursive_fns(&self.items)
646                .iter()
647                .map(String::as_str),
648            &symbol_table,
649            None,
650        );
651        for module in &self.modules {
652            let mod_items: Vec<TopLevel> = module
653                .fn_defs
654                .iter()
655                .map(|fd| TopLevel::FnDef(fd.clone()))
656                .collect();
657            recursive_fns.extend(scc::bare_names_to_fn_ids(
658                crate::call_graph::find_recursive_fns(&mod_items)
659                    .iter()
660                    .map(String::as_str),
661                &symbol_table,
662                Some(&module.prefix),
663            ));
664        }
665        self.recursive_fns = recursive_fns;
666
667        // Reuse the symbol table built at the top of this function
668        // for proof_lower below — it already resolved every FnId we
669        // need for `recursive_fns` / `mutual_tco_members`.
670        self.symbol_table = symbol_table;
671
672        // Rebuild the canonical resolved view from the current items
673        // + modules (post-PR-A: this is the single source for resolved
674        // bodies). Entry-side resolved items are produced by
675        // `resolve_program`, then the view runs the per-dep-module
676        // resolve internally and indexes everything by `FnId`. The
677        // `resolved_fn_defs` / `resolved_module_fn_defs` mirrors below
678        // are projections of this view, kept for callsites that still
679        // walk them directly during the #170 backend-migration arc.
680        let entry_resolved_items = crate::ir::hir::resolve_program(&self.symbol_table, &self.items);
681        self.resolved_program = crate::codegen::program_view::ResolvedProgramView::build(
682            entry_resolved_items,
683            &self.modules,
684            &self.symbol_table,
685        );
686        self.resolved_fn_defs = self.resolved_program.entry_fns().cloned().collect();
687        self.resolved_module_fn_defs = self
688            .resolved_program
689            .modules
690            .iter()
691            .map(|m| m.fn_defs.clone())
692            .collect();
693
694        // ProofIR's `fn_contracts` / `refined_types` are derived from
695        // the just-recomputed item set + the recursion classifier, so
696        // they must stay in step with the rest of the facts. Test
697        // helpers that build the context piecewise and call
698        // `refresh_facts` rely on this to see the same proof decisions
699        // the production pipeline would emit.
700        let inputs = crate::codegen::proof_lower::ProofLowerInputs::from_ctx(self);
701        self.proof_ir = crate::codegen::proof_lower::lower(&inputs);
702    }
703
704    /// Look up the resolved-HIR mirror of a source-shape [`FnDef`]
705    /// previously stashed in [`resolved_fn_defs`] /
706    /// [`resolved_module_fn_defs`]. Falls back to a fresh per-call
707    /// resolver lift against the entry's [`crate::ir::SymbolTable`]
708    /// when neither path covers `fd` — this happens for synthetic
709    /// FnDefs inserted between `build_context` and emit (memo
710    /// wrappers, TCO hoist rewrites, test fixtures) which the
711    /// resolver hasn't lifted upfront.
712    ///
713    /// `scope` is the owning module prefix when `fd` came from a
714    /// dependency module's `module.fn_defs`, `None` when `fd` is part
715    /// of the entry's `ctx.fn_defs`. Lookup keys by
716    /// [`crate::ir::FnKey`] through the [`crate::ir::SymbolTable`] so
717    /// two modules that share a bare fn name (e.g. `Util.format` and
718    /// `Other.format`) resolve to their own [`crate::ir::FnId`]
719    /// without bare-name collisions. Pre-PR-9.3a this matched by
720    /// `rfd.name == fd.name` against a flat search of every resolved
721    /// table — fragile the moment flatten changes (or doesn't run)
722    /// and two scopes share a name.
723    ///
724    /// Phase E shared lookup boundary — Rust codegen (PR 8) already
725    /// consumes this through `rust::toplevel::resolved_fn_def_for`;
726    /// wasm-gc / Lean / Dafny / self-host backends pick it up in
727    /// their follow-up PRs.
728    ///
729    /// [`resolved_fn_defs`]: Self::resolved_fn_defs
730    /// [`resolved_module_fn_defs`]: Self::resolved_module_fn_defs
731    pub fn resolve_fn_def<'a>(
732        &'a self,
733        fd: &'a FnDef,
734        scope: Option<&str>,
735    ) -> std::borrow::Cow<'a, crate::ir::hir::ResolvedFnDef> {
736        use crate::ir::FnKey;
737        use crate::ir::hir::{
738            ResolveCtx, ResolvedFnBody, ResolvedFnDef, ResolvedStmt, resolve_fn_def_external,
739        };
740        use std::borrow::Cow;
741
742        // Resolve identity via the symbol table — entry scope vs
743        // dependency module scope is the caller's stated context.
744        let key = match scope {
745            Some(prefix) => FnKey::in_module(prefix.to_string(), fd.name.clone()),
746            None => FnKey::entry(fd.name.clone()),
747        };
748        if let Some(fn_id) = self.symbol_table.fn_id_of(&key) {
749            // Canonical lookup goes through the resolved-program view —
750            // its `fn_by_id` index is the single FnId-keyed source for
751            // the resolved body, replacing the dual-walk over
752            // `resolved_fn_defs` + `resolved_module_fn_defs` that
753            // predated #170 Phase 1.
754            if let Some(rfd) = self.resolved_program.fn_by_id(fn_id) {
755                return Cow::Borrowed(rfd);
756            }
757            // Symbol table knew the key but the view didn't index it.
758            // Falls through to the synthetic-fallback path below; in
759            // production this shouldn't happen.
760        }
761
762        // Synthetic FnDef path — memo wrappers, TCO hoist rewrites,
763        // test fixtures the resolver never saw. Lift on demand
764        // against the entry's resolver context.
765        let module_name = self.items.iter().find_map(|i| match i {
766            TopLevel::Module(m) => Some(m.name.clone()),
767            _ => None,
768        });
769        let mut rctx = ResolveCtx::new(&self.symbol_table);
770        rctx.current_module = scope.map(String::from).or(module_name);
771        let lifted = resolve_fn_def_external(&rctx, fd).unwrap_or_else(|| {
772            let stmts: Vec<ResolvedStmt> = match fd.body.as_ref() {
773                crate::ast::FnBody::Block(stmts) => {
774                    stmts.iter().map(|s| self.resolve_stmt(s, scope)).collect()
775                }
776            };
777            ResolvedFnDef {
778                fn_id: crate::ir::FnId(u32::MAX),
779                name: fd.name.clone(),
780                line: fd.line,
781                params: fd
782                    .params
783                    .iter()
784                    .map(|(n, ann)| (n.clone(), crate::types::parse_type_str(ann)))
785                    .collect(),
786                return_type: crate::types::parse_type_str(&fd.return_type),
787                effects: fd.effects.clone(),
788                desc: fd.desc.clone(),
789                body: std::sync::Arc::new(ResolvedFnBody::Block(stmts)),
790                resolution: fd.resolution.clone(),
791            }
792        });
793        Cow::Owned(lifted)
794    }
795
796    /// Entry module's name from `items` (the `module X` declaration's
797    /// X). `None` for ad-hoc test programs without a module decl.
798    fn entry_module_name(&self) -> Option<String> {
799        self.items.iter().find_map(|i| match i {
800            TopLevel::Module(m) => Some(m.name.clone()),
801            _ => None,
802        })
803    }
804
805    /// Resolve a source-shape `Spanned<Expr>` on demand using the
806    /// entry's resolver context. Used by emit helpers that still walk
807    /// `Expr` (TCO hoisting, mutual TCO, verify blocks, follow-up
808    /// backends pre-migration) and need to feed the resolved shape
809    /// into the migrated emitter. The returned `Spanned<ResolvedExpr>`
810    /// carries the same line + type stamp as the input.
811    ///
812    /// `scope` is the owning module prefix when the caller knows
813    /// which dep module the expression lives in, `None` for entry-
814    /// scope code. Required for cross-module name resolution — e.g.,
815    /// a call site in module `A` referring to `Val.ValOk` declared
816    /// in module `B` only resolves to `ResolvedCtor::User` when the
817    /// resolver's `current_module` matches the call site's owning
818    /// scope. Pre-PR-9.4 the helper used the *entry* module name
819    /// uniformly, which broke cross-module ctor / fn classification
820    /// for the legacy emit paths (mutual TCO trampolines, TCO hoist
821    /// — they walked dep-module fn bodies but the resolver context
822    /// said "you're in the entry module"; the self-host regen
823    /// surfaced the gap when same-name shadowing across modules was
824    /// no longer an option).
825    pub fn resolve_expr(
826        &self,
827        expr: &crate::ast::Spanned<crate::ast::Expr>,
828        scope: Option<&str>,
829    ) -> crate::ast::Spanned<crate::ir::hir::ResolvedExpr> {
830        use crate::ir::hir::{ResolveCtx, ResolvedStmt};
831        let mut rctx = ResolveCtx::new(&self.symbol_table);
832        rctx.current_module = scope.map(String::from).or_else(|| self.entry_module_name());
833        let stmt = crate::ast::Stmt::Expr(expr.clone());
834        match crate::ir::hir::resolve::resolve_stmt_external(&rctx, &stmt) {
835            ResolvedStmt::Expr(s) => s,
836            ResolvedStmt::Binding { value, .. } => value,
837        }
838    }
839
840    /// Same as [`Self::resolve_expr`] but for whole statements
841    /// (`Binding(name, ty_ann, expr)` or `Expr(expr)`).
842    pub fn resolve_stmt(
843        &self,
844        stmt: &crate::ast::Stmt,
845        scope: Option<&str>,
846    ) -> crate::ir::hir::ResolvedStmt {
847        use crate::ir::hir::ResolveCtx;
848        let mut rctx = ResolveCtx::new(&self.symbol_table);
849        rctx.current_module = scope.map(String::from).or_else(|| self.entry_module_name());
850        crate::ir::hir::resolve::resolve_stmt_external(&rctx, stmt)
851    }
852
853    /// Resolve a source-shape [`crate::ast::Pattern`] to its resolved
854    /// HIR form. Wraps the pattern in a synthetic match arm + drops
855    /// it through `resolve_stmt_external`, since the resolver doesn't
856    /// expose a standalone pattern lifter — same workaround
857    /// `rust/toplevel.rs` used pre-PR-9.
858    pub fn resolve_pattern(
859        &self,
860        pat: &crate::ast::Pattern,
861        scope: Option<&str>,
862    ) -> crate::ir::hir::ResolvedPattern {
863        use crate::ast::{Expr, Literal, MatchArm, Spanned, Stmt};
864        use crate::ir::hir::{ResolveCtx, ResolvedExpr, ResolvedStmt};
865        let mut rctx = ResolveCtx::new(&self.symbol_table);
866        rctx.current_module = scope.map(String::from).or_else(|| self.entry_module_name());
867        let synthetic_arm = MatchArm {
868            pattern: pat.clone(),
869            body: Box::new(Spanned::bare(Expr::Literal(Literal::Unit))),
870            binding_slots: std::sync::OnceLock::new(),
871        };
872        let stmt = Stmt::Expr(Spanned::bare(Expr::Match {
873            subject: Box::new(Spanned::bare(Expr::Literal(Literal::Unit))),
874            arms: vec![synthetic_arm],
875        }));
876        let resolved_stmt = crate::ir::hir::resolve::resolve_stmt_external(&rctx, &stmt);
877        let ResolvedStmt::Expr(spanned) = resolved_stmt else {
878            unreachable!()
879        };
880        let ResolvedExpr::Match { arms, .. } = spanned.node else {
881            unreachable!()
882        };
883        arms.into_iter().next().unwrap().pattern
884    }
885}
886
887/// Per-key projection of the legacy `fn_sigs` map: routes a source-
888/// level name through `resolved_program` first (entry + every dep
889/// module's resolved fns), then walks `TypeDef`s for constructor sigs,
890/// then handles the synthesised `__buf_*` intrinsics. Lets a
891/// `CodegenContext` answer `FnSigOracle::fn_sig` without materialising
892/// the whole `FnSigMap` up front — the verify-law helpers query
893/// individual names, so per-key resolution is cheaper than per-call
894/// rebuild.
895fn codegen_ctx_fn_sig(ctx: &CodegenContext, name: &str) -> Option<crate::verify_law::FnSigInfo> {
896    use crate::verify_law::FnSigInfo;
897
898    if let Some(fn_id) = crate::codegen::common::fn_id_for_dotted_name(ctx, name)
899        && let Some(rfd) = ctx.resolved_program.fn_by_id(fn_id)
900    {
901        return Some(FnSigInfo {
902            return_type: rfd.return_type.clone(),
903            is_pure: rfd.effects.is_empty(),
904        });
905    }
906
907    // Constructor lookup: `Type.Variant` (entry sum), `Module.Type.
908    // Variant` (module sum), `Box` (entry product), `Module.Box`
909    // (module product). Walks the same `TypeDef` surfaces the
910    // legacy fn_sigs population did via SymbolRegistry.
911    let walk = |td: &crate::ast::TypeDef, scope: Option<&str>| -> Option<FnSigInfo> {
912        match td {
913            crate::ast::TypeDef::Sum {
914                name: parent,
915                variants,
916                ..
917            } => {
918                let parent_full = match scope {
919                    Some(prefix) => format!("{prefix}.{parent}"),
920                    None => parent.clone(),
921                };
922                for v in variants {
923                    let bare = format!("{parent}.{}", v.name);
924                    let full = format!("{parent_full}.{}", v.name);
925                    if name == bare || name == full {
926                        return Some(FnSigInfo {
927                            return_type: crate::types::Type::named(parent_full.clone()),
928                            is_pure: true,
929                        });
930                    }
931                }
932                None
933            }
934            crate::ast::TypeDef::Product { name: parent, .. } => {
935                let parent_full = match scope {
936                    Some(prefix) => format!("{prefix}.{parent}"),
937                    None => parent.clone(),
938                };
939                if name == parent || name == parent_full {
940                    return Some(FnSigInfo {
941                        return_type: crate::types::Type::named(parent_full),
942                        is_pure: true,
943                    });
944                }
945                None
946            }
947        }
948    };
949    for item in &ctx.items {
950        if let TopLevel::TypeDef(td) = item
951            && let Some(info) = walk(td, None)
952        {
953            return Some(info);
954        }
955    }
956    for m in &ctx.modules {
957        for td in &m.type_defs {
958            if let Some(info) = walk(td, Some(&m.prefix)) {
959                return Some(info);
960            }
961        }
962    }
963
964    // Synthesised `__buf_*` intrinsics — the deforestation pipeline
965    // emits these as opaque callables; verify-law walkers may surface
966    // a reference if a user's law body sketches the buffer pipeline.
967    match name {
968        "__buf_new" => Some(FnSigInfo {
969            return_type: crate::types::Type::named("Buffer"),
970            is_pure: true,
971        }),
972        "__buf_append" | "__buf_append_sep_unless_first" => Some(FnSigInfo {
973            return_type: crate::types::Type::named("Buffer"),
974            is_pure: true,
975        }),
976        "__buf_finalize" => Some(FnSigInfo {
977            return_type: crate::types::Type::Str,
978            is_pure: true,
979        }),
980        _ => None,
981    }
982}
983
984impl crate::verify_law::FnSigOracle for CodegenContext {
985    fn fn_sig(&self, name: &str) -> Option<crate::verify_law::FnSigInfo> {
986        codegen_ctx_fn_sig(self, name)
987    }
988}