Skip to main content

aver/codegen/lean/
mod.rs

1/// Lean 4 backend for the Aver transpiler.
2///
3/// Transpiles only pure core logic: functions without effects, type definitions,
4/// verify blocks (as `example` proofs), and decision blocks (as comments).
5/// Effectful functions and `main` are skipped.
6mod builtins;
7mod expr;
8mod law_auto;
9mod pattern;
10mod prelude;
11pub(crate) mod recurrence;
12mod sample_literal;
13mod shared;
14#[cfg(test)]
15mod tests;
16mod toplevel;
17mod transpile;
18mod types;
19pub mod universal_lane;
20
21// Re-exports for the lemma-discovery pass (`codegen::lemma_discovery`), which
22// renders discovered candidate lemmas to Lean theorem text using the SAME
23// name/type mapping the program defs are emitted with — so a discovered
24// theorem references `decode` / `Run` / `++` exactly as generated.
25pub(crate) use expr::aver_name_to_lean;
26pub(crate) use types::type_to_lean;
27
28// `law_auto` cites the prelude spec lemma names via `super::`; the
29// `transpile*` entry points below drive the unified emitter.
30pub(crate) use prelude::prelude_spec_lemmas_for_builtins;
31#[cfg(test)]
32use prelude::{generate_lakefile_with_roots, generate_prelude};
33use transpile::{LeanEmitMode, transpile_unified};
34
35use std::collections::HashSet;
36
37use crate::ast::{FnDef, Spanned};
38use crate::codegen::{CodegenContext, ProjectOutput};
39
40/// Statement-class channel for emitted law theorems.
41///
42/// `aver proof --check`'s `universal` metric must know, per law theorem,
43/// whether the emitted STATEMENT is genuinely universal or bounded: for a
44/// `when`-law over non-refinement-lifted givens, `law_theorem_prop` prepends
45/// sampled-domain disjunction premises (`a = 0 ∨ a = 1 ∨ …`) — the theorem
46/// then only claims the law on the finite sample domain, even when it is
47/// proven by real tactics with a kernel-clean axiom profile. Refinement-lifted
48/// `when`-laws drop those premises (the Subtype carries the invariant) and
49/// stay genuinely universal.
50///
51/// Only the code that BUILDS the statement knows which premises it prepended,
52/// so the emitter records the class as one structured marker comment per
53/// emitted law theorem, preceding it in the generated `.lean` source
54/// (self-contained artifact — the classification travels with the export):
55///
56/// ```text
57/// -- aver:law-class <theorem_name> universal
58/// -- aver:law-class <theorem_name> bounded-domain
59/// ```
60///
61/// The checker (`lean_universal_proof` in the CLI) consumes these markers and
62/// must NEVER re-derive the class from theorem names or by re-parsing
63/// statements. A law theorem without a marker earns no universal credit
64/// (fail-closed for stale/foreign export dirs).
65pub const LAW_CLASS_MARKER_PREFIX: &str = "-- aver:law-class ";
66/// Marker class tag: no sampled-domain premises — the `∀`-statement is the
67/// law's genuine universal claim.
68pub const LAW_CLASS_UNIVERSAL: &str = "universal";
69/// Marker class tag: sampled-domain disjunction premises bound the statement
70/// to the finite sample domain.
71pub const LAW_CLASS_BOUNDED_DOMAIN: &str = "bounded-domain";
72
73/// How verify blocks should be emitted in generated Lean.
74#[derive(Clone, Copy, Debug, Eq, PartialEq)]
75pub enum VerifyEmitMode {
76    /// `example : lhs = rhs := by native_decide`
77    NativeDecide,
78    /// `example : lhs = rhs := by sorry`
79    Sorry,
80    /// Named theorem stubs:
81    /// `theorem <fn>_verify_<n> : lhs = rhs := by`
82    /// `  sorry`
83    TheoremSkeleton,
84}
85
86// RecursionPlan / ProofModeIssue moved to shared `crate::codegen::recursion`
87// so the Dafny backend can reuse the same classifier. Re-export here so
88// existing `lean::RecursionPlan` / `lean::ProofModeIssue` call sites keep
89// working without churn.
90pub use crate::codegen::recursion::{ProofModeIssue, RecursionPlan};
91
92pub use toplevel::PROOF_FUEL_EXHAUSTED_MSG;
93
94/// The marker every Lean runtime panic prints into captured build output.
95/// Empirically pinned against real `lake build` transcripts (both panic
96/// sites below produce it):
97///
98/// ```text
99/// info: ././././FuelProbe.lean:27:0: PANIC at stepSum__fuel FuelProbe:8:9: Aver proof fuel exhausted
100/// PANIC at stepSumAcc__fuel FuelProbe:19:9: Aver proof fuel exhausted
101/// info: ././././PanicProbe.lean:11:0: PANIC at Char.toCode AverCommon:11:12: Char.toCode: string is empty
102/// ```
103///
104/// (lake prefixes the first diagnostic of a build step with `info: <loc>:`,
105/// later ones print raw — both carry `PANIC at `.)
106pub const LEAN_PANIC_LINE_MARKER: &str = "PANIC at ";
107
108/// Count model panic lines in captured `lake build` output.
109///
110/// Lean's `panic!` does NOT abort: at `native_decide` evaluation time it
111/// prints `PANIC at <fn> <file>:<line>: <msg>` (to lake's captured output)
112/// and returns the result type's `default` value. When BOTH sides of a
113/// bounded sample route through the model (`verify f(x) => g(x)` cases,
114/// every `_sample_N` / `_checked_domain` theorem), a panicking evaluation
115/// reduces both sides to `default` and the kernel certifies a vacuous —
116/// possibly FALSE — equation while `lake` exits 0 with zero sorries. The
117/// panic line in the build output is the only trace, so `aver proof --check`
118/// charges ANY hit as a hard failure.
119///
120/// Scans for the generic `PANIC at ` line marker, not a per-site message:
121/// the emitted exports contain `panic!` only at compiler-generated sites —
122/// the fuel wrappers' exhaustion arm ([`PROOF_FUEL_EXHAUSTED_MSG`]) and
123/// partial prelude builtins (e.g. `Char.toCode` on an empty string) — and
124/// every one of them shares the same panic-returns-`default` vacuity vector.
125/// A green check has no legitimate panic, and the generic marker also
126/// catches panics raised inside Lean's own stdlib (e.g. a `get!` deep in a
127/// future prelude helper) that a per-message scan could never enumerate.
128/// Counts matching LINES (one panic prints exactly one line; the same site
129/// can fire on several theorems).
130///
131/// Known false-positive boundary, accepted: on an ALREADY-FAILING build, a
132/// native_decide error can echo the false proposition, and a user string
133/// literal containing `PANIC at ` inside it would inflate the count (and
134/// set `model_panicked`). The verdict stays correct — the build already
135/// failed on exit status — so a spurious match can only turn a red redder,
136/// never a green red.
137pub fn count_model_panic_lines(output: &str) -> usize {
138    output
139        .lines()
140        .filter(|l| l.contains(LEAN_PANIC_LINE_MARKER))
141        .count()
142}
143
144pub(crate) fn pure_fns(ctx: &CodegenContext) -> Vec<&FnDef> {
145    ctx.modules
146        .iter()
147        .flat_map(|m| m.fn_defs.iter())
148        .chain(ctx.fn_defs.iter())
149        .filter(|fd| toplevel::is_pure_fn(fd))
150        .collect()
151}
152
153pub(crate) fn recursive_type_names(ctx: &CodegenContext) -> HashSet<String> {
154    ctx.modules
155        .iter()
156        .flat_map(|m| m.type_defs.iter())
157        .chain(ctx.type_defs.iter())
158        .filter(|td| toplevel::is_recursive_type_def(td))
159        .map(|td| toplevel::type_def_name(td).to_string())
160        .collect()
161}
162
163pub(crate) fn recursive_pure_fn_names(ctx: &CodegenContext) -> HashSet<String> {
164    // `ctx.recursive_fns` is the single source of truth — populated
165    // by `build_context` from analyze in production, by
166    // `refresh_facts()` (called from each `transpile*` entry point)
167    // in test stubs. After phase C it's keyed by opaque `FnId`;
168    // project pure-fn ids back through the symbol table and surface
169    // bare names for Lean's downstream scope-local classifiers.
170    let symbols = &ctx.symbol_table;
171    let pure_ids: HashSet<crate::ir::FnId> = pure_fns(ctx)
172        .into_iter()
173        .filter_map(|fd| crate::codegen::common::fn_id_for_decl(ctx, fd))
174        .collect();
175    ctx.recursive_fns
176        .intersection(&pure_ids)
177        .map(|id| symbols.fn_entry(*id).key.name.clone())
178        .collect()
179}
180
181fn verify_counter_key(vb: &crate::ast::VerifyBlock) -> String {
182    // Shared with the CLI's VM ground-truth collection — see the doc on
183    // `verify_block_counter_key` for why the two sides must not drift.
184    crate::codegen::common::verify_block_counter_key(vb)
185}
186
187fn lean_project_name(ctx: &CodegenContext) -> String {
188    crate::codegen::common::entry_basename(ctx)
189}
190
191pub(super) fn bound_expr_to_lean(expr: &Spanned<crate::ir::hir::ResolvedExpr>) -> String {
192    use crate::ir::hir::{ResolvedCallee, ResolvedExpr};
193    match &expr.node {
194        ResolvedExpr::Literal(crate::ast::Literal::Int(n)) => format!("{}", n),
195        ResolvedExpr::Ident(name) | ResolvedExpr::Resolved { name, .. } => {
196            expr::aver_name_to_lean(name)
197        }
198        ResolvedExpr::Call(callee, args) => {
199            // Bound expressions are linear arithmetic over the param —
200            // typically `List.len(xs)` or an int constant. The resolver
201            // lifts `List.len(...)` to `ResolvedCallee::Builtin`; user-fn
202            // refs in a bound expression would be a malformed metric
203            // anyway, so we only render builtins and fall through to
204            // `"0"` (the same fallback the original AST helper used for
205            // shapes it couldn't classify).
206            let dotted = match callee {
207                ResolvedCallee::Builtin(name) => Some(name.clone()),
208                _ => None,
209            };
210            if let Some(dotted) = dotted {
211                // List.len(xs) → xs.length in Lean
212                if dotted == "List.len" && args.len() == 1 {
213                    return format!("{}.length", bound_expr_to_lean(&args[0]));
214                }
215                let lean_args: Vec<String> = args.iter().map(bound_expr_to_lean).collect();
216                format!(
217                    "({} {})",
218                    expr::aver_name_to_lean(&dotted),
219                    lean_args.join(" ")
220                )
221            } else {
222                "0".to_string()
223            }
224        }
225        ResolvedExpr::Attr(obj, field) => format!(
226            "{}.{}",
227            bound_expr_to_lean(obj),
228            expr::aver_name_to_lean(field)
229        ),
230        _ => "0".to_string(),
231    }
232}
233
234pub(crate) use crate::codegen::recursion::detect::sizeof_measure_param_indices;
235
236/// Proof-mode diagnostics for Lean transpilation.
237///
238/// Returns human-readable notices for recursive shapes that still fall back to
239/// regular `partial` Lean defs instead of total proof-mode emission.
240pub fn proof_mode_findings(ctx: &CodegenContext) -> Vec<ProofModeIssue> {
241    // ProofIR carries `unclassified_fns` populated by the ContractLower
242    // pipeline stage — same data analyze_plans used to return, just
243    // read off the IR instead of re-running the classifier.
244    ctx.proof_ir
245        .unclassified_fns
246        .iter()
247        .map(|uf| ProofModeIssue {
248            line: uf.line,
249            message: uf.message.clone(),
250        })
251        .collect()
252}
253
254pub fn proof_mode_issues(ctx: &CodegenContext) -> Vec<String> {
255    proof_mode_findings(ctx)
256        .into_iter()
257        .map(|issue| issue.message)
258        .collect()
259}
260
261/// Transpile an Aver program to a Lean 4 project.
262///
263/// Takes `&mut ctx` so it can run `ctx.refresh_facts()` upfront — keeps
264/// the derived sets (`mutual_tco_members`, `recursive_fns`) in sync with
265/// the current items + modules. Idempotent: production callers go through
266/// `build_context` which already populated them, so refresh recomputes
267/// the same answer; test stubs that build the ctx piecewise (push items
268/// in-place, bypass `build_context`) get the fresh sets they need.
269pub fn transpile(ctx: &mut CodegenContext) -> ProjectOutput {
270    transpile_with_verify_mode(ctx, VerifyEmitMode::NativeDecide)
271}
272
273/// Proof-mode transpilation.
274///
275/// Uses recursion plans validated by `proof_mode_issues` and emits supported
276/// recursive functions without `partial`, adding `termination_by` scaffolding.
277pub fn transpile_for_proof_mode(
278    ctx: &mut CodegenContext,
279    verify_mode: VerifyEmitMode,
280) -> ProjectOutput {
281    // No refresh_facts call here: production callers go through
282    // build_codegen_context → pipeline, which populates every derived
283    // fact (recursive_fns, mutual_tco_members, proof_ir) once.
284    // Synthetic-AST tests that bypass the pipeline call refresh_facts
285    // themselves before reaching this fn.
286    transpile_unified(ctx, verify_mode, LeanEmitMode::Proof)
287}
288
289/// Transpile an Aver program to a Lean 4 project with configurable verify proof mode.
290///
291/// - `NativeDecide` emits `example ... := by native_decide`
292/// - `Sorry` emits `example ... := by sorry`
293/// - `TheoremSkeleton` emits named theorem skeletons with `sorry`
294pub fn transpile_with_verify_mode(
295    ctx: &mut CodegenContext,
296    verify_mode: VerifyEmitMode,
297) -> ProjectOutput {
298    // No refresh_facts call here — same reasoning as
299    // `transpile_for_proof_mode`. Synthetic-AST tests refresh
300    // themselves; production paths come pre-populated.
301    transpile_unified(ctx, verify_mode, LeanEmitMode::Standard)
302}