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