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;
10pub(crate) mod recurrence;
11mod shared;
12mod toplevel;
13mod types;
14
15use std::collections::{HashMap, HashSet};
16
17use crate::ast::{Expr, FnDef, Spanned, TopLevel, TypeDef, VerifyKind};
18use crate::call_graph;
19use crate::codegen::{CodegenContext, ProjectOutput};
20
21/// How verify blocks should be emitted in generated Lean.
22#[derive(Clone, Copy, Debug, Eq, PartialEq)]
23pub enum VerifyEmitMode {
24    /// `example : lhs = rhs := by native_decide`
25    NativeDecide,
26    /// `example : lhs = rhs := by sorry`
27    Sorry,
28    /// Named theorem stubs:
29    /// `theorem <fn>_verify_<n> : lhs = rhs := by`
30    /// `  sorry`
31    TheoremSkeleton,
32}
33
34// RecursionPlan / ProofModeIssue moved to shared `crate::codegen::recursion`
35// so the Dafny backend can reuse the same classifier. Re-export here so
36// existing `lean::RecursionPlan` / `lean::ProofModeIssue` call sites keep
37// working without churn.
38pub use crate::codegen::recursion::{ProofModeIssue, RecursionPlan};
39
40const LEAN_PRELUDE_HEADER: &str = r#"-- Generated by the Aver → Lean 4 transpiler
41-- Pure core logic plus Oracle-lifted classified effects
42
43set_option linter.unusedVariables false
44
45-- Prelude: helper definitions for Aver builtins"#;
46
47const LEAN_PRELUDE_FLOAT_COE: &str = r#"instance : Coe Int Float := ⟨fun n => Float.ofInt n⟩
48
49def Float.fromInt (n : Int) : Float := Float.ofInt n
50
51-- Aver's Float-to-Int operations match the runtime semantics
52-- (`f64::floor() as i64` in VM, Rust codegen, WASM — all three use the
53-- same IEEE 754 floor/round/ceil followed by Rust's saturating
54-- `f64 as i64` cast):
55--   * finite values within [i64::MIN, i64::MAX]: truncate toward zero
56--   * finite > i64::MAX:              saturate to i64::MAX
57--   * finite < i64::MIN:              saturate to i64::MIN
58--   * +Inf:                           saturate to i64::MAX
59--   * -Inf:                           saturate to i64::MIN
60--   * NaN:                            0 (Rust 1.45+ defined behavior)
61--
62-- Lean's `Float.floor : Float → Float` doesn't directly satisfy Aver's
63-- `Float.floor : Float → Int`, so we synthesize via the saturating
64-- `Float.toUInt64` (returns 0 for NaN/negative) with sign handling and
65-- explicit bounds. Per-case correctness is asserted by `native_decide`
66-- examples below; total semantic agreement with `f64 as i64` would
67-- need a formal IEEE spec in Lean, which is out of scope.
68--
69-- Asymmetry with the Dafny backend: Lean has IEEE 754 `Float` natively
70-- (`double` at runtime), so we use it. Dafny only offers mathematical
71-- `real` (Cauchy-style, no NaN/Inf/overflow), which is a fundamental
72-- type mismatch with Aver's IEEE Float — Dafny operations stay opaque
73-- (`function FloatPi(): real` etc.) rather than synthesizing IEEE on
74-- top of `bv64`, which would mean implementing the entire IEEE
75-- arithmetic in Dafny by hand.
76namespace AverFloat
77def toInt (x : Float) : Int :=
78  if x.isNaN then 0
79  -- 2^63 is exactly representable in f64; values ≥ that saturate up.
80  else if x ≥ 9223372036854775808.0 then 9223372036854775807
81  -- -2^63 is exactly representable; values strictly below saturate down.
82  else if x < -9223372036854775808.0 then -9223372036854775808
83  else if x ≥ 0.0 then Int.ofNat x.toUInt64.toNat
84  else -(Int.ofNat (-x).toUInt64.toNat)
85
86def floor (x : Float) : Int := toInt x.floor
87def ceil  (x : Float) : Int := toInt x.ceil
88def round (x : Float) : Int := toInt x.round
89
90def pow (x y : Float) : Float := x ^ y
91
92-- Edge-case smoke checks: each `example` is discharged by reduction,
93-- so any drift from these documented values fails Lake build.
94example : AverFloat.toInt 0.0 = 0                                := by native_decide
95example : AverFloat.toInt 3.7 = 3                                := by native_decide
96example : AverFloat.toInt (-3.7) = -3                            := by native_decide
97example : AverFloat.toInt (1.0 / 0.0) = 9223372036854775807      := by native_decide
98example : AverFloat.toInt (-1.0 / 0.0) = -9223372036854775808    := by native_decide
99example : AverFloat.toInt (0.0 / 0.0) = 0                        := by native_decide
100example : AverFloat.floor 3.7 = 3                                := by native_decide
101example : AverFloat.floor (-3.7) = -4                            := by native_decide
102example : AverFloat.ceil  3.2 = 4                                := by native_decide
103example : AverFloat.ceil  (-3.2) = -3                            := by native_decide
104-- Rounding mode (half-away-from-zero, matching Rust's `f64::round`):
105example : AverFloat.round 0.5 = 1                                := by native_decide
106example : AverFloat.round (-0.5) = -1                            := by native_decide
107example : AverFloat.round 2.5 = 3                                := by native_decide
108example : AverFloat.round (-2.5) = -3                            := by native_decide
109end AverFloat"#;
110
111const LEAN_PRELUDE_FLOAT_DEC_EQ: &str = r#"private unsafe def Float.unsafeDecEq (a b : Float) : Decidable (a = b) :=
112  if a == b then isTrue (unsafeCast ()) else isFalse (unsafeCast ())
113@[implemented_by Float.unsafeDecEq]
114private opaque Float.compDecEq (a b : Float) : Decidable (a = b)
115instance : DecidableEq Float := Float.compDecEq"#;
116
117const LEAN_PRELUDE_EXCEPT_DEC_EQ: &str = r#"instance [DecidableEq ε] [DecidableEq α] : DecidableEq (Except ε α)
118  | .ok a, .ok b =>
119    if h : a = b then isTrue (h ▸ rfl) else isFalse (by intro h'; cases h'; exact h rfl)
120  | .error a, .error b =>
121    if h : a = b then isTrue (h ▸ rfl) else isFalse (by intro h'; cases h'; exact h rfl)
122  | .ok _, .error _ => isFalse (by intro h; cases h)
123  | .error _, .ok _ => isFalse (by intro h; cases h)"#;
124
125const LEAN_PRELUDE_EXCEPT_NS: &str = r#"namespace Except
126def withDefault (r : Except ε α) (d : α) : α :=
127  match r with
128  | .ok v => v
129  | .error _ => d
130end Except"#;
131
132const LEAN_PRELUDE_OPTION_TO_EXCEPT: &str = r#"def Option.toExcept (o : Option α) (e : ε) : Except ε α :=
133  match o with
134  | some v => .ok v
135  | none => .error e"#;
136
137const LEAN_PRELUDE_STRING_HADD: &str = r#"instance : HAdd String String String := ⟨String.append⟩"#;
138
139/// Oracle v1: BranchPath mirrors the Aver-source opaque builtin. The
140/// dewey-decimal string under the hood is not user-observable — users
141/// construct paths through `.root`, `.child`, `.parse`.
142const LEAN_PRELUDE_BRANCH_PATH: &str = r#"structure BranchPath where
143  dewey : String
144  deriving Repr, BEq, DecidableEq
145
146def BranchPath.Root : BranchPath := { dewey := "" }
147
148def BranchPath.child (p : BranchPath) (idx : Int) : BranchPath :=
149  if p.dewey.isEmpty then { dewey := toString idx }
150  else { dewey := p.dewey ++ "." ++ toString idx }
151
152def BranchPath.parse (s : String) : BranchPath := { dewey := s }"#;
153
154const LEAN_PRELUDE_PROOF_FUEL: &str = r#"def averStringPosFuel (s : String) (pos : Int) (rankBudget : Nat) : Nat :=
155  (((s.data.length) - pos.toNat) + 1) * rankBudget"#;
156
157const LEAN_PRELUDE_AVER_MEASURE: &str = r#"namespace AverMeasure
158def list (elemMeasure : α → Nat) : List α → Nat
159  | [] => 1
160  | x :: xs => elemMeasure x + list elemMeasure xs + 1
161def option (elemMeasure : α → Nat) : Option α → Nat
162  | none => 1
163  | some x => elemMeasure x + 1
164def except (errMeasure : ε → Nat) (okMeasure : α → Nat) : Except ε α → Nat
165  | .error e => errMeasure e + 1
166  | .ok v => okMeasure v + 1
167end AverMeasure"#;
168
169const AVER_MAP_PRELUDE_BASE: &str = r#"namespace AverMap
170def empty : List (α × β) := []
171def get [DecidableEq α] (m : List (α × β)) (k : α) : Option β :=
172  match m with
173  | [] => none
174  | (k', v) :: rest => if k = k' then some v else AverMap.get rest k
175def set [DecidableEq α] (m : List (α × β)) (k : α) (v : β) : List (α × β) :=
176  let rec go : List (α × β) → List (α × β)
177    | [] => [(k, v)]
178    | (k', v') :: rest => if k = k' then (k, v) :: rest else (k', v') :: go rest
179  go m
180def has [DecidableEq α] (m : List (α × β)) (k : α) : Bool :=
181  m.any (fun p => decide (k = p.1))
182def remove [DecidableEq α] (m : List (α × β)) (k : α) : List (α × β) :=
183  m.filter (fun p => !(decide (k = p.1)))
184def keys (m : List (α × β)) : List α := m.map Prod.fst
185def values (m : List (α × β)) : List β := m.map Prod.snd
186def entries (m : List (α × β)) : List (α × β) := m
187def len (m : List (α × β)) : Nat := m.length
188def fromList (entries : List (α × β)) : List (α × β) := entries"#;
189
190const AVER_MAP_PRELUDE_HAS_SET_SELF: &str = r#"private theorem any_set_go_self [DecidableEq α] (k : α) (v : β) :
191    ∀ (m : List (α × β)), List.any (AverMap.set.go k v m) (fun p => decide (k = p.1)) = true := by
192  intro m
193  induction m with
194  | nil =>
195      simp [AverMap.set.go, List.any]
196  | cons p tl ih =>
197      cases p with
198      | mk k' v' =>
199          by_cases h : k = k'
200          · simp [AverMap.set.go, List.any, h]
201          · simp [AverMap.set.go, List.any, h, ih]
202
203theorem has_set_self [DecidableEq α] (m : List (α × β)) (k : α) (v : β) :
204    AverMap.has (AverMap.set m k v) k = true := by
205  simpa [AverMap.has, AverMap.set] using any_set_go_self k v m"#;
206
207const AVER_MAP_PRELUDE_GET_SET_SELF: &str = r#"private theorem get_set_go_self [DecidableEq α] (k : α) (v : β) :
208    ∀ (m : List (α × β)), AverMap.get (AverMap.set.go k v m) k = some v := by
209  intro m
210  induction m with
211  | nil =>
212      simp [AverMap.set.go, AverMap.get]
213  | cons p tl ih =>
214      cases p with
215      | mk k' v' =>
216          by_cases h : k = k'
217          · simp [AverMap.set.go, AverMap.get, h]
218          · simp [AverMap.set.go, AverMap.get, h, ih]
219
220theorem get_set_self [DecidableEq α] (m : List (α × β)) (k : α) (v : β) :
221    AverMap.get (AverMap.set m k v) k = some v := by
222  simpa [AverMap.set] using get_set_go_self k v m"#;
223
224const AVER_MAP_PRELUDE_GET_SET_OTHER: &str = r#"private theorem get_set_go_other [DecidableEq α] (k key : α) (v : β) (h : key ≠ k) :
225    ∀ (m : List (α × β)), AverMap.get (AverMap.set.go k v m) key = AverMap.get m key := by
226  intro m
227  induction m with
228  | nil =>
229      simp [AverMap.set.go, AverMap.get, h]
230  | cons p tl ih =>
231      cases p with
232      | mk k' v' =>
233          by_cases hk : k = k'
234          · have hkey : key ≠ k' := by simpa [hk] using h
235            simp [AverMap.set.go, AverMap.get, hk, hkey]
236          · by_cases hkey : key = k'
237            · simp [AverMap.set.go, AverMap.get, hk, hkey]
238            · simp [AverMap.set.go, AverMap.get, hk, hkey, ih]
239
240theorem get_set_other [DecidableEq α] (m : List (α × β)) (k key : α) (v : β) (h : key ≠ k) :
241    AverMap.get (AverMap.set m k v) key = AverMap.get m key := by
242  simpa [AverMap.set] using get_set_go_other k key v h m"#;
243
244const AVER_MAP_PRELUDE_HAS_SET_OTHER: &str = r#"theorem has_eq_isSome_get [DecidableEq α] (m : List (α × β)) (k : α) :
245    AverMap.has m k = (AverMap.get m k).isSome := by
246  induction m with
247  | nil =>
248      simp [AverMap.has, AverMap.get]
249  | cons p tl ih =>
250      cases p with
251      | mk k' v' =>
252          by_cases h : k = k'
253          · simp [AverMap.has, AverMap.get, List.any, h]
254          · simpa [AverMap.has, AverMap.get, List.any, h] using ih
255
256theorem has_set_other [DecidableEq α] (m : List (α × β)) (k key : α) (v : β) (h : key ≠ k) :
257    AverMap.has (AverMap.set m k v) key = AverMap.has m key := by
258  rw [AverMap.has_eq_isSome_get, AverMap.has_eq_isSome_get]
259  simp [AverMap.get_set_other, h]"#;
260
261const AVER_MAP_PRELUDE_END: &str = r#"end AverMap"#;
262
263const LEAN_PRELUDE_AVER_LIST: &str = r#"namespace AverList
264def get (xs : List α) (i : Int) : Option α :=
265  if i < 0 then none else xs.get? i.toNat
266private def insertSorted [Ord α] (x : α) : List α → List α
267  | [] => [x]
268  | y :: ys =>
269    if compare x y == Ordering.lt || compare x y == Ordering.eq then
270      x :: y :: ys
271    else
272      y :: insertSorted x ys
273def sort [Ord α] (xs : List α) : List α :=
274  xs.foldl (fun acc x => insertSorted x acc) []
275end AverList"#;
276
277// Built-in record types (Header, HttpResponse, HttpRequest,
278// Tcp.Connection, Terminal.Size) used to live as hard-coded literals
279// here. They now live in `crate::codegen::builtin_records` —
280// declarative descriptions consumed by Lean, Dafny, and WASM via
281// shared `needed_records()` and `render_lean()`. Drift between
282// backends is no longer possible.
283
284const LEAN_PRELUDE_STRING_HELPERS: &str = r#"def String.charAt (s : String) (i : Int) : Option String :=
285  if i < 0 then none
286  else (s.toList.get? i.toNat).map Char.toString
287theorem String.charAt_length_none (s : String) : String.charAt s s.length = none := by
288  have hs : ¬ ((s.length : Int) < 0) := by omega
289  unfold String.charAt
290  simp [hs]
291  change s.data.length ≤ s.length
292  exact Nat.le_refl _
293def String.slice (s : String) (start stop : Int) : String :=
294  let startN := if start < 0 then 0 else start.toNat
295  let stopN := if stop < 0 then 0 else stop.toNat
296  let chars := s.toList
297  String.mk ((chars.drop startN).take (stopN - startN))
298private def trimFloatTrailingZerosChars (chars : List Char) : List Char :=
299  let noZeros := (chars.reverse.dropWhile (fun c => c == '0')).reverse
300  match noZeros.reverse with
301  | '.' :: rest => rest.reverse
302  | _ => noZeros
303private def normalizeFloatString (s : String) : String :=
304  if s.toList.any (fun c => c == '.') then
305    String.mk (trimFloatTrailingZerosChars s.toList)
306  else s
307def String.fromFloat (f : Float) : String := normalizeFloatString (toString f)
308def String.chars (s : String) : List String := s.toList.map Char.toString
309private theorem char_to_string_append_mk (c : Char) (chars : List Char) :
310    Char.toString c ++ String.mk chars = String.mk (c :: chars) := by
311  rfl
312private theorem string_intercalate_empty_char_strings_go (acc : String) (chars : List Char) :
313    String.intercalate.go acc "" (chars.map Char.toString) = acc ++ String.mk chars := by
314  induction chars generalizing acc with
315  | nil =>
316      simp [String.intercalate.go]
317  | cons c rest ih =>
318      calc
319        String.intercalate.go acc "" ((c :: rest).map Char.toString)
320            = String.intercalate.go (acc ++ Char.toString c) "" (rest.map Char.toString) := by
321                simp [String.intercalate.go]
322        _ = (acc ++ Char.toString c) ++ String.mk rest := by
323                simpa using ih (acc ++ Char.toString c)
324        _ = acc ++ String.mk (c :: rest) := by
325                simp [String.append_assoc, char_to_string_append_mk]
326private theorem string_intercalate_empty_char_strings (chars : List Char) :
327    String.intercalate "" (chars.map Char.toString) = String.mk chars := by
328  cases chars with
329  | nil =>
330      simp [String.intercalate]
331  | cons c rest =>
332      simpa [String.intercalate] using string_intercalate_empty_char_strings_go c.toString rest
333theorem String.intercalate_empty_chars (s : String) :
334    String.intercalate "" (String.chars s) = s := by
335  cases s with
336  | mk chars =>
337      simpa [String.chars] using string_intercalate_empty_char_strings chars
338namespace AverString
339def splitOnCharGo (currentRev : List Char) (sep : Char) : List Char → List String
340  | [] => [String.mk currentRev.reverse]
341  | c :: cs =>
342      if c == sep then
343        String.mk currentRev.reverse :: splitOnCharGo [] sep cs
344      else
345        splitOnCharGo (c :: currentRev) sep cs
346def splitOnChar (s : String) (sep : Char) : List String :=
347  splitOnCharGo [] sep s.toList
348def split (s delim : String) : List String :=
349  match delim.toList with
350  | [] => "" :: (s.toList.map Char.toString) ++ [""]
351  | [c] => splitOnChar s c
352  | _ => s.splitOn delim
353@[simp] private theorem char_toString_data (c : Char) : c.toString.data = [c] := by
354  rfl
355private theorem splitOnCharGo_until_sep
356    (prefixRev part tail : List Char) (sep : Char) :
357    part.all (fun c => c != sep) = true ->
358    splitOnCharGo prefixRev sep (part ++ sep :: tail) =
359      String.mk (prefixRev.reverse ++ part) :: splitOnCharGo [] sep tail := by
360  intro h_safe
361  induction part generalizing prefixRev with
362  | nil =>
363      simp [splitOnCharGo]
364  | cons c rest ih =>
365      simp at h_safe
366      have h_rest : (rest.all fun c => c != sep) = true := by
367        simpa using h_safe.2
368      simpa [splitOnCharGo, h_safe.1, List.reverse_cons, List.append_assoc] using
369        (ih (c :: prefixRev) h_rest)
370private theorem splitOnCharGo_no_sep
371    (prefixRev chars : List Char) (sep : Char) :
372    chars.all (fun c => c != sep) = true ->
373    splitOnCharGo prefixRev sep chars =
374      [String.mk (prefixRev.reverse ++ chars)] := by
375  intro h_safe
376  induction chars generalizing prefixRev with
377  | nil =>
378      simp [splitOnCharGo]
379  | cons c rest ih =>
380      simp at h_safe
381      have h_rest : (rest.all fun c => c != sep) = true := by
382        simpa using h_safe.2
383      simpa [splitOnCharGo, h_safe.1, List.reverse_cons, List.append_assoc] using
384        (ih (c :: prefixRev) h_rest)
385@[simp] theorem split_single_char_append
386    (head tail : String) (sep : Char) :
387    head.toList.all (fun c => c != sep) = true ->
388    split (head ++ Char.toString sep ++ tail) (Char.toString sep) =
389      head :: split tail (Char.toString sep) := by
390  intro h_safe
391  simpa [split, splitOnChar] using
392    (splitOnCharGo_until_sep [] head.data tail.data sep h_safe)
393@[simp] theorem split_single_char_no_sep
394    (s : String) (sep : Char) :
395    s.toList.all (fun c => c != sep) = true ->
396    split s (Char.toString sep) = [s] := by
397  intro h_safe
398  simpa [split, splitOnChar] using
399    (splitOnCharGo_no_sep [] s.data sep h_safe)
400private theorem intercalate_go_prefix
401    (pref acc sep : String) (rest : List String) :
402    String.intercalate.go (pref ++ sep ++ acc) sep rest =
403      pref ++ sep ++ String.intercalate.go acc sep rest := by
404  induction rest generalizing acc with
405  | nil =>
406      simp [String.intercalate.go, String.append_assoc]
407  | cons x xs ih =>
408      simpa [String.intercalate.go, String.append_assoc] using
409        (ih (acc ++ sep ++ x))
410@[simp] theorem split_intercalate_trailing_single_char
411    (parts : List String) (sep : Char) :
412    parts.all (fun part => part.toList.all (fun c => c != sep)) = true ->
413    split (String.intercalate (Char.toString sep) parts ++ Char.toString sep) (Char.toString sep) =
414      match parts with
415      | [] => ["", ""]
416      | _ => parts ++ [""] := by
417  intro h_safe
418  induction parts with
419  | nil =>
420      simp [split, splitOnChar, splitOnCharGo]
421  | cons part rest ih =>
422      simp at h_safe
423      have h_part : (part.toList.all fun c => c != sep) = true := by
424        simpa using h_safe.1
425      cases rest with
426      | nil =>
427          have h_empty : ("".toList.all fun c => c != sep) = true := by simp
428          calc
429            split (String.intercalate.go part (Char.toString sep) [] ++ Char.toString sep) (Char.toString sep)
430                = split (part ++ Char.toString sep) (Char.toString sep) := by
431                    simp [String.intercalate.go]
432            _ = part :: split "" (Char.toString sep) := by
433                    simpa using split_single_char_append part "" sep h_part
434            _ = [part, ""] := by
435                    simp [split_single_char_no_sep, h_empty]
436      | cons next rest' =>
437          have h_rest : ((next :: rest').all fun part => part.toList.all fun c => c != sep) = true := by
438            simpa using h_safe.2
439          calc
440            split
441                  (String.intercalate.go part (Char.toString sep) (next :: rest') ++ Char.toString sep)
442                  (Char.toString sep)
443                =
444                  split
445                    (part ++ Char.toString sep ++ (String.intercalate (Char.toString sep) (next :: rest') ++ Char.toString sep))
446                    (Char.toString sep) := by
447                    have h_join :
448                        String.intercalate.go part (Char.toString sep) (next :: rest') ++ Char.toString sep
449                          = part ++ Char.toString sep ++ (String.intercalate (Char.toString sep) (next :: rest') ++ Char.toString sep) := by
450                        calc
451                          String.intercalate.go part (Char.toString sep) (next :: rest') ++ Char.toString sep
452                              = String.intercalate.go (part ++ Char.toString sep ++ next) (Char.toString sep) rest' ++ Char.toString sep := by
453                                  simp [String.intercalate.go]
454                          _ = part ++ Char.toString sep ++ (String.intercalate.go next (Char.toString sep) rest' ++ Char.toString sep) := by
455                                  rw [intercalate_go_prefix part next (Char.toString sep) rest']
456                                  simp [String.append_assoc]
457                          _ = part ++ Char.toString sep ++ (String.intercalate (Char.toString sep) (next :: rest') ++ Char.toString sep) := by
458                                  simp [String.intercalate, String.intercalate.go]
459                    simpa using congrArg (fun s => split s (Char.toString sep)) h_join
460            _ = part :: split
461                    (String.intercalate (Char.toString sep) (next :: rest') ++ Char.toString sep)
462                    (Char.toString sep) := by
463                    simpa using split_single_char_append
464                      part
465                      (String.intercalate (Char.toString sep) (next :: rest') ++ Char.toString sep)
466                      sep
467                      h_part
468            _ = part :: (next :: rest' ++ [""]) := by
469                    simpa using ih h_rest
470end AverString"#;
471
472const LEAN_PRELUDE_NUMERIC_PARSE: &str = r#"namespace AverDigits
473def foldDigitsAcc (acc : Nat) : List Nat -> Nat
474  | [] => acc
475  | d :: ds => foldDigitsAcc (acc * 10 + d) ds
476
477def foldDigits (digits : List Nat) : Nat :=
478  foldDigitsAcc 0 digits
479
480private theorem foldDigitsAcc_append_singleton (acc : Nat) (xs : List Nat) (d : Nat) :
481    foldDigitsAcc acc (xs ++ [d]) = foldDigitsAcc acc xs * 10 + d := by
482  induction xs generalizing acc with
483  | nil =>
484      simp [foldDigitsAcc]
485  | cons x xs ih =>
486      simp [foldDigitsAcc, ih, Nat.left_distrib, Nat.add_assoc, Nat.add_left_comm]
487
488private theorem foldDigits_append_singleton (xs : List Nat) (d : Nat) :
489    foldDigits (xs ++ [d]) = foldDigits xs * 10 + d := by
490  simpa [foldDigits] using foldDigitsAcc_append_singleton 0 xs d
491
492def natDigits : Nat -> List Nat
493  | n =>
494      if n < 10 then
495        [n]
496      else
497        natDigits (n / 10) ++ [n % 10]
498termination_by
499  n => n
500
501theorem natDigits_nonempty (n : Nat) : natDigits n ≠ [] := by
502  by_cases h : n < 10
503  · rw [natDigits.eq_1]
504    simp [h]
505  · rw [natDigits.eq_1]
506    simp [h]
507
508theorem natDigits_digits_lt_ten : ∀ n : Nat, ∀ d ∈ natDigits n, d < 10 := by
509  intro n d hd
510  by_cases h : n < 10
511  · rw [natDigits.eq_1] at hd
512    simp [h] at hd
513    rcases hd with rfl
514    exact h
515  · rw [natDigits.eq_1] at hd
516    simp [h] at hd
517    rcases hd with hd | hd
518    · exact natDigits_digits_lt_ten (n / 10) d hd
519    · subst hd
520      exact Nat.mod_lt n (by omega)
521
522theorem foldDigits_natDigits : ∀ n : Nat, foldDigits (natDigits n) = n := by
523  intro n
524  by_cases h : n < 10
525  · rw [natDigits.eq_1]
526    simp [h, foldDigits, foldDigitsAcc]
527  · rw [natDigits.eq_1]
528    simp [h]
529    rw [foldDigits_append_singleton]
530    rw [foldDigits_natDigits (n / 10)]
531    omega
532
533def digitChar : Nat -> Char
534  | 0 => '0' | 1 => '1' | 2 => '2' | 3 => '3' | 4 => '4'
535  | 5 => '5' | 6 => '6' | 7 => '7' | 8 => '8' | 9 => '9'
536  | _ => '0'
537
538def charToDigit? : Char -> Option Nat
539  | '0' => some 0 | '1' => some 1 | '2' => some 2 | '3' => some 3 | '4' => some 4
540  | '5' => some 5 | '6' => some 6 | '7' => some 7 | '8' => some 8 | '9' => some 9
541  | _ => none
542
543theorem charToDigit_digitChar : ∀ d : Nat, d < 10 -> charToDigit? (digitChar d) = some d
544  | 0, _ => by simp [digitChar, charToDigit?]
545  | 1, _ => by simp [digitChar, charToDigit?]
546  | 2, _ => by simp [digitChar, charToDigit?]
547  | 3, _ => by simp [digitChar, charToDigit?]
548  | 4, _ => by simp [digitChar, charToDigit?]
549  | 5, _ => by simp [digitChar, charToDigit?]
550  | 6, _ => by simp [digitChar, charToDigit?]
551  | 7, _ => by simp [digitChar, charToDigit?]
552  | 8, _ => by simp [digitChar, charToDigit?]
553  | 9, _ => by simp [digitChar, charToDigit?]
554  | Nat.succ (Nat.succ (Nat.succ (Nat.succ (Nat.succ (Nat.succ (Nat.succ (Nat.succ (Nat.succ (Nat.succ n))))))))), h => by
555      omega
556
557theorem digitChar_ne_minus : ∀ d : Nat, d < 10 -> digitChar d ≠ '-'
558  | 0, _ => by decide
559  | 1, _ => by decide
560  | 2, _ => by decide
561  | 3, _ => by decide
562  | 4, _ => by decide
563  | 5, _ => by decide
564  | 6, _ => by decide
565  | 7, _ => by decide
566  | 8, _ => by decide
567  | 9, _ => by decide
568  | Nat.succ (Nat.succ (Nat.succ (Nat.succ (Nat.succ (Nat.succ (Nat.succ (Nat.succ (Nat.succ (Nat.succ n))))))))), h => by
569      omega
570
571theorem digitChar_not_ws : ∀ d : Nat, d < 10 ->
572    Char.toString (digitChar d) ≠ " " ∧
573    Char.toString (digitChar d) ≠ "\t" ∧
574    Char.toString (digitChar d) ≠ "\n" ∧
575    Char.toString (digitChar d) ≠ "\r"
576  | 0, _ => by decide
577  | 1, _ => by decide
578  | 2, _ => by decide
579  | 3, _ => by decide
580  | 4, _ => by decide
581  | 5, _ => by decide
582  | 6, _ => by decide
583  | 7, _ => by decide
584  | 8, _ => by decide
585  | 9, _ => by decide
586  | Nat.succ (Nat.succ (Nat.succ (Nat.succ (Nat.succ (Nat.succ (Nat.succ (Nat.succ (Nat.succ (Nat.succ n))))))))), h => by
587      omega
588
589theorem mapM_charToDigit_digits : ∀ ds : List Nat,
590    (∀ d ∈ ds, d < 10) -> List.mapM charToDigit? (ds.map digitChar) = some ds := by
591  intro ds hds
592  induction ds with
593  | nil =>
594      simp
595  | cons d ds ih =>
596      have hd : d < 10 := hds d (by simp)
597      have htail : ∀ x ∈ ds, x < 10 := by
598        intro x hx
599        exact hds x (by simp [hx])
600      simp [charToDigit_digitChar d hd, ih htail]
601
602def natDigitsChars (n : Nat) : List Char :=
603  (natDigits n).map digitChar
604
605def parseNatChars (chars : List Char) : Option Nat :=
606  match chars with
607  | [] => none
608  | _ => do
609      let digits <- List.mapM charToDigit? chars
610      pure (foldDigits digits)
611
612theorem parseNatChars_nat (n : Nat) :
613    parseNatChars (natDigitsChars n) = some n := by
614  unfold parseNatChars natDigitsChars
615  cases h : (natDigits n).map digitChar with
616  | nil =>
617      exfalso
618      exact natDigits_nonempty n (List.map_eq_nil_iff.mp h)
619  | cons hd tl =>
620      have hdigits : List.mapM charToDigit? (List.map digitChar (natDigits n)) = some (natDigits n) :=
621        mapM_charToDigit_digits (natDigits n) (fun d hd => natDigits_digits_lt_ten n d hd)
622      rw [h] at hdigits
623      simp [h, hdigits, foldDigits_natDigits]
624end AverDigits
625
626def String.fromInt (n : Int) : String :=
627  match n with
628  | .ofNat m => String.mk (AverDigits.natDigitsChars m)
629  | .negSucc m => String.mk ('-' :: AverDigits.natDigitsChars (m + 1))
630
631def Int.fromString (s : String) : Except String Int :=
632  match s.toList with
633  | [] => .error ("Cannot parse '" ++ s ++ "' as Int")
634  | '-' :: rest =>
635    match AverDigits.parseNatChars rest with
636    | some n => .ok (-Int.ofNat n)
637    | none => .error ("Cannot parse '" ++ s ++ "' as Int")
638  | chars =>
639    match AverDigits.parseNatChars chars with
640    | some n => .ok (Int.ofNat n)
641    | none => .error ("Cannot parse '" ++ s ++ "' as Int")
642
643theorem Int.fromString_fromInt : ∀ n : Int, Int.fromString (String.fromInt n) = .ok n
644  | .ofNat m => by
645      cases h : AverDigits.natDigits m with
646      | nil =>
647          exfalso
648          exact AverDigits.natDigits_nonempty m h
649      | cons d ds =>
650          have hd : d < 10 := AverDigits.natDigits_digits_lt_ten m d (by simp [h])
651          have hne : AverDigits.digitChar d ≠ '-' := AverDigits.digitChar_ne_minus d hd
652          have hparse : AverDigits.parseNatChars (AverDigits.digitChar d :: List.map AverDigits.digitChar ds) = some m := by
653            simpa [AverDigits.natDigitsChars, h] using AverDigits.parseNatChars_nat m
654          simp [String.fromInt, Int.fromString, AverDigits.natDigitsChars, h, hne, hparse]
655  | .negSucc m => by
656      simp [String.fromInt, Int.fromString, AverDigits.parseNatChars_nat]
657      rfl
658
659private def charDigitsToNat (cs : List Char) : Nat :=
660  cs.foldl (fun acc c => acc * 10 + (c.toNat - '0'.toNat)) 0
661
662private def parseExpPart : List Char → (Bool × List Char)
663  | '-' :: rest => (true, rest.takeWhile Char.isDigit)
664  | '+' :: rest => (false, rest.takeWhile Char.isDigit)
665  | rest => (false, rest.takeWhile Char.isDigit)
666
667def Float.fromString (s : String) : Except String Float :=
668  let chars := s.toList
669  let (neg, chars) := match chars with
670    | '-' :: rest => (true, rest)
671    | _ => (false, chars)
672  let intPart := chars.takeWhile Char.isDigit
673  let rest := chars.dropWhile Char.isDigit
674  let (fracPart, rest) := match rest with
675    | '.' :: rest => (rest.takeWhile Char.isDigit, rest.dropWhile Char.isDigit)
676    | _ => ([], rest)
677  let (expNeg, expDigits) := match rest with
678    | 'e' :: rest => parseExpPart rest
679    | 'E' :: rest => parseExpPart rest
680    | _ => (false, [])
681  if intPart.isEmpty && fracPart.isEmpty then .error ("Invalid float: " ++ s)
682  else
683    let mantissa := charDigitsToNat (intPart ++ fracPart)
684    let fracLen : Int := fracPart.length
685    let expVal : Int := charDigitsToNat expDigits
686    let shift : Int := (if expNeg then -expVal else expVal) - fracLen
687    let f := if shift >= 0 then Float.ofScientific mantissa false shift.toNat
688             else Float.ofScientific mantissa true ((-shift).toNat)
689    .ok (if neg then -f else f)"#;
690
691const LEAN_PRELUDE_CHAR_BYTE: &str = r#"def Char.toCode (s : String) : Int :=
692  match s.toList.head? with
693  | some c => (c.toNat : Int)
694  | none => panic! "Char.toCode: string is empty"
695def Char.fromCode (n : Int) : Option String :=
696  if n < 0 || n > 1114111 then none
697  else if n >= 55296 && n <= 57343 then none
698  else some (Char.toString (Char.ofNat n.toNat))
699
700def hexDigit (n : Int) : String :=
701  match n with
702  | 0 => "0" | 1 => "1" | 2 => "2" | 3 => "3"
703  | 4 => "4" | 5 => "5" | 6 => "6" | 7 => "7"
704  | 8 => "8" | 9 => "9" | 10 => "a" | 11 => "b"
705  | 12 => "c" | 13 => "d" | 14 => "e" | 15 => "f"
706  | _ => "?"
707
708def byteToHex (code : Int) : String :=
709  hexDigit (code / 16) ++ hexDigit (code % 16)
710
711namespace AverByte
712private def hexValue (c : Char) : Option Int :=
713  match c with
714  | '0' => some 0  | '1' => some 1  | '2' => some 2  | '3' => some 3
715  | '4' => some 4  | '5' => some 5  | '6' => some 6  | '7' => some 7
716  | '8' => some 8  | '9' => some 9  | 'a' => some 10 | 'b' => some 11
717  | 'c' => some 12 | 'd' => some 13 | 'e' => some 14 | 'f' => some 15
718  | 'A' => some 10 | 'B' => some 11 | 'C' => some 12 | 'D' => some 13
719  | 'E' => some 14 | 'F' => some 15
720  | _ => none
721def toHex (n : Int) : Except String String :=
722  if n < 0 || n > 255 then
723    .error ("Byte.toHex: " ++ toString n ++ " is out of range 0-255")
724  else
725    .ok (byteToHex n)
726def fromHex (s : String) : Except String Int :=
727  match s.toList with
728  | [hi, lo] =>
729    match hexValue hi, hexValue lo with
730    | some h, some l => .ok (h * 16 + l)
731    | _, _ => .error ("Byte.fromHex: invalid hex '" ++ s ++ "'")
732  | _ => .error ("Byte.fromHex: expected exactly 2 hex chars, got '" ++ s ++ "'")
733end AverByte"#;
734
735pub(crate) fn pure_fns(ctx: &CodegenContext) -> Vec<&FnDef> {
736    ctx.modules
737        .iter()
738        .flat_map(|m| m.fn_defs.iter())
739        .chain(ctx.fn_defs.iter())
740        .filter(|fd| toplevel::is_pure_fn(fd))
741        .collect()
742}
743
744pub(crate) fn recursive_type_names(ctx: &CodegenContext) -> HashSet<String> {
745    ctx.modules
746        .iter()
747        .flat_map(|m| m.type_defs.iter())
748        .chain(ctx.type_defs.iter())
749        .filter(|td| toplevel::is_recursive_type_def(td))
750        .map(|td| toplevel::type_def_name(td).to_string())
751        .collect()
752}
753
754pub(crate) fn recursive_pure_fn_names(ctx: &CodegenContext) -> HashSet<String> {
755    let pure_names: HashSet<String> = pure_fns(ctx)
756        .into_iter()
757        .map(|fd| fd.name.clone())
758        .collect();
759    let mut callgraph_items = ctx.items.clone();
760    for module in &ctx.modules {
761        for fd in &module.fn_defs {
762            callgraph_items.push(TopLevel::FnDef(fd.clone()));
763        }
764    }
765    call_graph::find_recursive_fns(&callgraph_items)
766        .into_iter()
767        .filter(|name| pure_names.contains(name))
768        .collect()
769}
770
771fn verify_counter_key(vb: &crate::ast::VerifyBlock) -> String {
772    match &vb.kind {
773        VerifyKind::Cases => format!("fn:{}", vb.fn_name),
774        VerifyKind::Law(law) => format!("law:{}::{}", vb.fn_name, law.name),
775    }
776}
777
778fn lean_project_name(ctx: &CodegenContext) -> String {
779    crate::codegen::common::entry_basename(ctx)
780}
781
782pub(crate) fn find_type_def<'a>(ctx: &'a CodegenContext, type_name: &str) -> Option<&'a TypeDef> {
783    ctx.modules
784        .iter()
785        .flat_map(|m| m.type_defs.iter())
786        .chain(ctx.type_defs.iter())
787        .find(|td| toplevel::type_def_name(td) == type_name)
788}
789
790pub(super) fn bound_expr_to_lean(expr: &Spanned<Expr>) -> String {
791    match &expr.node {
792        Expr::Literal(crate::ast::Literal::Int(n)) => format!("{}", n),
793        Expr::Ident(name) => expr::aver_name_to_lean(name),
794        Expr::FnCall(f, args) => {
795            if let Some(dotted) = crate::codegen::common::expr_to_dotted_name(&f.node) {
796                // List.len(xs) → xs.length in Lean
797                if dotted == "List.len" && args.len() == 1 {
798                    return format!("{}.length", bound_expr_to_lean(&args[0]));
799                }
800                let lean_args: Vec<String> = args.iter().map(bound_expr_to_lean).collect();
801                format!(
802                    "({} {})",
803                    expr::aver_name_to_lean(&dotted),
804                    lean_args.join(" ")
805                )
806            } else {
807                "0".to_string()
808            }
809        }
810        Expr::Attr(obj, field) => format!(
811            "{}.{}",
812            bound_expr_to_lean(obj),
813            expr::aver_name_to_lean(field)
814        ),
815        _ => "0".to_string(),
816    }
817}
818
819pub(crate) fn sizeof_measure_param_indices(fd: &FnDef) -> Vec<usize> {
820    fd.params
821        .iter()
822        .enumerate()
823        .filter_map(|(idx, (_, type_name))| {
824            (!crate::codegen::recursion::detect::is_scalar_like_type(type_name)).then_some(idx)
825        })
826        .collect()
827}
828
829/// Proof-mode diagnostics for Lean transpilation.
830///
831/// Returns human-readable notices for recursive shapes that still fall back to
832/// regular `partial` Lean defs instead of total proof-mode emission.
833pub fn proof_mode_findings(ctx: &CodegenContext) -> Vec<ProofModeIssue> {
834    let (_plans, issues) = crate::codegen::recursion::analyze_plans(ctx);
835    issues
836}
837
838pub fn proof_mode_issues(ctx: &CodegenContext) -> Vec<String> {
839    proof_mode_findings(ctx)
840        .into_iter()
841        .map(|issue| issue.message)
842        .collect()
843}
844
845/// Transpile an Aver program to a Lean 4 project.
846pub fn transpile(ctx: &CodegenContext) -> ProjectOutput {
847    transpile_with_verify_mode(ctx, VerifyEmitMode::NativeDecide)
848}
849
850/// Proof-mode transpilation.
851///
852/// Uses recursion plans validated by `proof_mode_issues` and emits supported
853/// recursive functions without `partial`, adding `termination_by` scaffolding.
854pub fn transpile_for_proof_mode(
855    ctx: &CodegenContext,
856    verify_mode: VerifyEmitMode,
857) -> ProjectOutput {
858    transpile_unified(ctx, verify_mode, LeanEmitMode::Proof)
859}
860
861/// Transpile an Aver program to a Lean 4 project with configurable verify proof mode.
862///
863/// - `NativeDecide` emits `example ... := by native_decide`
864/// - `Sorry` emits `example ... := by sorry`
865/// - `TheoremSkeleton` emits named theorem skeletons with `sorry`
866pub fn transpile_with_verify_mode(
867    ctx: &CodegenContext,
868    verify_mode: VerifyEmitMode,
869) -> ProjectOutput {
870    transpile_unified(ctx, verify_mode, LeanEmitMode::Standard)
871}
872
873/// Oracle v1: for each effectful FnDef whose effects are all classified,
874/// run effect_lifting::lift_fn_def to produce a pure (lifted) FnDef and
875/// emit it via the standard pure-fn path. Effectful functions that use
876/// unclassified (stateful / interactive / higher-order-callback) effects
877/// are still skipped entirely — matches the pre-Oracle behavior.
878///
879/// Mutual recursion among effectful fns is out of scope for v0: this
880/// emits each lifted fn independently.
881fn emit_lifted_effectful_functions(
882    ctx: &CodegenContext,
883    recursive_fns: &HashSet<String>,
884    sections: &mut Vec<String>,
885) {
886    use crate::types::checker::effect_classification::is_classified;
887
888    // Oracle v1: only emit effectful fns reachable from some verify
889    // block. Non-terminating effectful fns (e.g. REPL loops that loop
890    // forever on `Console.readLine`) would otherwise make Lean reject
891    // the whole module — and if nobody is proving anything about them,
892    // that's dead code in the proof output.
893    let reachable = crate::codegen::common::verify_reachable_fn_names(&ctx.items);
894
895    // Oracle v1: collect the effect list for every eligible
896    // effectful fn *first* — call sites to these helpers in any
897    // lifted body get `(path, oracle...)` injected so the arity
898    // matches the helper's lifted form.
899    let mut helpers: std::collections::HashMap<String, Vec<String>> =
900        std::collections::HashMap::new();
901    for item in &ctx.items {
902        let TopLevel::FnDef(fd) = item else { continue };
903        if fd.effects.is_empty() || fd.name == "main" {
904            continue;
905        }
906        if !fd.effects.iter().all(|e| is_classified(&e.node)) {
907            continue;
908        }
909        if !reachable.contains(&fd.name) {
910            continue;
911        }
912        helpers.insert(
913            fd.name.clone(),
914            fd.effects.iter().map(|e| e.node.clone()).collect(),
915        );
916    }
917
918    let mut lifted_fns: Vec<(String, crate::ast::FnDef)> = Vec::new();
919    for item in &ctx.items {
920        let TopLevel::FnDef(fd) = item else { continue };
921        if fd.effects.is_empty() || fd.name == "main" {
922            continue;
923        }
924        if !fd.effects.iter().all(|e| is_classified(&e.node)) {
925            continue;
926        }
927        if !reachable.contains(&fd.name) {
928            continue;
929        }
930        let Ok(Some(lifted)) =
931            crate::types::checker::effect_lifting::lift_fn_def_with_helpers(fd, &helpers)
932        else {
933            continue;
934        };
935        lifted_fns.push((fd.name.clone(), lifted));
936    }
937
938    // Oracle v1: topologically sort so callees are emitted before
939    // callers. Without this, a lifted effectful fn that calls another
940    // lifted effectful helper (e.g. `handle(msg) -> printErr(msg)`)
941    // can land before the helper and Lean complains about an unknown
942    // identifier. The pure-fn emission goes through SCC analysis for
943    // the same reason — this is a cheap approximation good enough
944    // for non-mutual effectful chains.
945    let eligible_names: std::collections::HashSet<String> =
946        lifted_fns.iter().map(|(n, _)| n.clone()).collect();
947    let mut emitted: std::collections::HashSet<String> = std::collections::HashSet::new();
948    let mut order: Vec<usize> = Vec::new();
949    let mut remaining: Vec<usize> = (0..lifted_fns.len()).collect();
950    while !remaining.is_empty() {
951        let before = remaining.len();
952        remaining.retain(|&idx| {
953            let body_calls = collect_called_idents_in_body(&lifted_fns[idx].1.body);
954            let ready = body_calls
955                .iter()
956                .all(|name| !eligible_names.contains(name) || emitted.contains(name));
957            if ready {
958                emitted.insert(lifted_fns[idx].0.clone());
959                order.push(idx);
960                false
961            } else {
962                true
963            }
964        });
965        if remaining.len() == before {
966            // Cycle or deadlock — fall back to source order for what's
967            // left rather than looping forever. Lean will complain at
968            // build time, which is the right signal for users.
969            order.append(&mut remaining);
970        }
971    }
972
973    for idx in order {
974        let (_, lifted) = &lifted_fns[idx];
975        if let Some(code) = toplevel::emit_fn_def(lifted, recursive_fns, ctx) {
976            sections.push(code);
977            sections.push(String::new());
978        }
979    }
980}
981
982fn collect_called_idents_in_body(body: &crate::ast::FnBody) -> std::collections::HashSet<String> {
983    use crate::ast::{Expr, Spanned, Stmt};
984    let mut out = std::collections::HashSet::new();
985    fn walk(expr: &Spanned<Expr>, out: &mut std::collections::HashSet<String>) {
986        match &expr.node {
987            Expr::FnCall(callee, args) => {
988                if let Expr::Ident(name) | Expr::Resolved { name, .. } = &callee.node {
989                    out.insert(name.clone());
990                }
991                walk(callee, out);
992                for a in args {
993                    walk(a, out);
994                }
995            }
996            Expr::BinOp(_, l, r) => {
997                walk(l, out);
998                walk(r, out);
999            }
1000            Expr::Match { subject, arms } => {
1001                walk(subject, out);
1002                for arm in arms {
1003                    walk(&arm.body, out);
1004                }
1005            }
1006            Expr::Attr(inner, _) | Expr::ErrorProp(inner) => walk(inner, out),
1007            Expr::Constructor(_, Some(inner)) => walk(inner, out),
1008            Expr::List(items) | Expr::Tuple(items) | Expr::IndependentProduct(items, _) => {
1009                for i in items {
1010                    walk(i, out);
1011                }
1012            }
1013            Expr::MapLiteral(pairs) => {
1014                for (k, v) in pairs {
1015                    walk(k, out);
1016                    walk(v, out);
1017                }
1018            }
1019            Expr::RecordCreate { fields, .. } => {
1020                for (_, v) in fields {
1021                    walk(v, out);
1022                }
1023            }
1024            Expr::RecordUpdate { base, updates, .. } => {
1025                walk(base, out);
1026                for (_, v) in updates {
1027                    walk(v, out);
1028                }
1029            }
1030            Expr::InterpolatedStr(parts) => {
1031                for part in parts {
1032                    if let crate::ast::StrPart::Parsed(inner) = part {
1033                        walk(inner, out);
1034                    }
1035                }
1036            }
1037            _ => {}
1038        }
1039    }
1040    for stmt in body.stmts() {
1041        match stmt {
1042            Stmt::Expr(e) => walk(e, &mut out),
1043            Stmt::Binding(_, _, e) => walk(e, &mut out),
1044        }
1045    }
1046    out
1047}
1048
1049#[cfg(test)]
1050fn generate_prelude() -> String {
1051    generate_prelude_for_body("", true)
1052}
1053
1054#[cfg(test)]
1055fn generate_prelude_for_body(body: &str, include_all_helpers: bool) -> String {
1056    // Oracle v1: trust-assumption header first so the emitted file opens with
1057    // the explicit claim block before any prelude or definitions. Skipped when
1058    // the body has no Oracle lifting at all — pure-math files don't depend on
1059    // any of the trust claims, so emitting the block would just add noise.
1060    let mut parts = vec![LEAN_PRELUDE_HEADER.to_string()];
1061    if include_all_helpers || crate::codegen::builtin_records::needs_trust_header(body) {
1062        // This branch is only reachable from #[cfg(test)] code that
1063        // calls `generate_prelude` without a real ctx; pass an empty
1064        // declared_effects set so the test fixture exercises the
1065        // "no effects" rendering. Production calls go through the
1066        // ctx-aware path in `transpile_unified`.
1067        let empty = crate::codegen::common::DeclaredEffects {
1068            bare_namespaces: std::collections::HashSet::new(),
1069            methods: std::collections::HashSet::new(),
1070        };
1071        let has_ip = body.contains("BranchPath");
1072        parts.push(
1073            crate::types::checker::proof_trust_header::generate_commented("-- ", &empty, has_ip),
1074        );
1075    }
1076    // Built-in record types — shared decision module decides which ones.
1077    for record in crate::codegen::builtin_records::needed_records(body, include_all_helpers) {
1078        parts.push(crate::codegen::builtin_records::render_lean(record));
1079    }
1080
1081    // Built-in helpers — same shared decision pattern. Each key has a
1082    // backend-native body resolved here (Lean preludes); other backends
1083    // use the same shared decision against their own implementations.
1084    for helper in crate::codegen::builtin_helpers::needed_helpers(body, include_all_helpers) {
1085        match helper.key {
1086            "BranchPath" => parts.push(LEAN_PRELUDE_BRANCH_PATH.to_string()),
1087            "AverList" => parts.push(LEAN_PRELUDE_AVER_LIST.to_string()),
1088            "StringHelpers" => parts.push(LEAN_PRELUDE_STRING_HELPERS.to_string()),
1089            "NumericParse" => parts.push(LEAN_PRELUDE_NUMERIC_PARSE.to_string()),
1090            "CharByte" => parts.push(LEAN_PRELUDE_CHAR_BYTE.to_string()),
1091            "AverMeasure" => parts.push(LEAN_PRELUDE_AVER_MEASURE.to_string()),
1092            "AverMap" => parts.push(generate_map_prelude(body, include_all_helpers)),
1093            "ProofFuel" => parts.push(LEAN_PRELUDE_PROOF_FUEL.to_string()),
1094            "FloatInstances" => parts.extend([
1095                LEAN_PRELUDE_FLOAT_COE.to_string(),
1096                LEAN_PRELUDE_FLOAT_DEC_EQ.to_string(),
1097            ]),
1098            "ExceptInstances" => parts.extend([
1099                LEAN_PRELUDE_EXCEPT_DEC_EQ.to_string(),
1100                LEAN_PRELUDE_EXCEPT_NS.to_string(),
1101                LEAN_PRELUDE_OPTION_TO_EXCEPT.to_string(),
1102            ]),
1103            "StringHadd" => parts.push(LEAN_PRELUDE_STRING_HADD.to_string()),
1104            // Dafny-side datatype declarations — Lean has Result/Option
1105            // natively (`Except`/`Option`) and BranchPath ships as part
1106            // of the BranchPath helper key, so all four are no-ops here.
1107            "ResultDatatype" | "OptionDatatype" | "OptionToResult" | "BranchPathDatatype" => {}
1108            other => panic!(
1109                "Lean backend has no implementation for builtin helper key '{}'. \
1110                 Add a match arm in generate_prelude_for_body or remove the key \
1111                 from BUILTIN_HELPERS.",
1112                other
1113            ),
1114        }
1115    }
1116
1117    parts.join("\n\n")
1118}
1119
1120fn generate_map_prelude(body: &str, include_all_helpers: bool) -> String {
1121    let mut parts = vec![AVER_MAP_PRELUDE_BASE.to_string()];
1122
1123    let needs_has_set_self = include_all_helpers || body.contains("AverMap.has_set_self");
1124    let needs_get_set_self = include_all_helpers || body.contains("AverMap.get_set_self");
1125    let needs_get_set_other = include_all_helpers
1126        || body.contains("AverMap.get_set_other")
1127        || body.contains("AverMap.has_set_other");
1128    let needs_has_set_other = include_all_helpers || body.contains("AverMap.has_set_other");
1129
1130    if needs_has_set_self {
1131        parts.push(AVER_MAP_PRELUDE_HAS_SET_SELF.to_string());
1132    }
1133    if needs_get_set_self {
1134        parts.push(AVER_MAP_PRELUDE_GET_SET_SELF.to_string());
1135    }
1136    if needs_get_set_other {
1137        parts.push(AVER_MAP_PRELUDE_GET_SET_OTHER.to_string());
1138    }
1139    if needs_has_set_other {
1140        parts.push(AVER_MAP_PRELUDE_HAS_SET_OTHER.to_string());
1141    }
1142
1143    parts.push(AVER_MAP_PRELUDE_END.to_string());
1144    parts.join("\n\n")
1145}
1146
1147fn generate_lakefile_with_roots(project_name: &str, extra_roots: &[String]) -> String {
1148    let mut roots: Vec<String> = vec![format!("`{}", project_name)];
1149    for r in extra_roots {
1150        roots.push(format!("`{}", r));
1151    }
1152    let roots_str = roots.join(", ");
1153    format!(
1154        r#"import Lake
1155open Lake DSL
1156
1157package «{}» where
1158  version := v!"0.1.0"
1159
1160@[default_target]
1161lean_lib «{}» where
1162  srcDir := "."
1163  roots := #[{}]
1164"#,
1165        project_name.to_lowercase(),
1166        project_name,
1167        roots_str
1168    )
1169}
1170
1171fn generate_toolchain() -> String {
1172    "leanprover/lean4:v4.15.0\n".to_string()
1173}
1174
1175#[derive(Clone, Copy)]
1176enum LeanEmitMode {
1177    Standard,
1178    Proof,
1179}
1180
1181/// Multi-file Lean output for multi-module Aver projects:
1182/// - `AverCommon.lean` carries built-in helpers + records (UNION decision
1183///   over every module + entry body, so a helper is included only if
1184///   something actually references it).
1185/// - `<Module>.lean` (one per `depends [...]` entry) wraps that module's
1186///   types and pure fns in `namespace M ... end M`. Submodules like
1187///   `Models.User` land at `Models/User.lean` to match Lean's path-as-
1188///   module-name convention.
1189/// - `<ProjectName>.lean` is the entry: trust header (here only),
1190///   top-level entry items, lifted effectful fns, decisions, verify
1191///   blocks. Imports `AverCommon` plus every dependent module.
1192fn transpile_unified(
1193    ctx: &CodegenContext,
1194    verify_mode: VerifyEmitMode,
1195    emit_mode: LeanEmitMode,
1196) -> ProjectOutput {
1197    use crate::codegen::recursion::RecursionPlan;
1198
1199    let recursive_fns = call_graph::find_recursive_fns(&ctx.items);
1200    let recursive_names = recursive_pure_fn_names(ctx);
1201    let recursive_types = recursive_type_names(ctx);
1202    let (plans, _proof_issues) = match emit_mode {
1203        LeanEmitMode::Proof => crate::codegen::recursion::analyze_plans(ctx),
1204        LeanEmitMode::Standard => (HashMap::<String, RecursionPlan>::new(), Vec::new()),
1205    };
1206
1207    // Pure fns are SCC-routed per scope (per dependent module + entry)
1208    // independently — shared `route_pure_components_per_scope` handles
1209    // the loop. A global SCC pass would conflate same-bare-name fns from
1210    // different modules (rogue's `Map.getT` vs `Fov.getT`).
1211    let pure_per_scope = crate::codegen::common::route_pure_components_per_scope(
1212        ctx,
1213        toplevel::is_pure_fn,
1214        |comp| {
1215            let mut out: Vec<String> = Vec::new();
1216            if comp.len() > 1 {
1217                let code = match emit_mode {
1218                    LeanEmitMode::Proof => {
1219                        let all_supported = comp.iter().all(|fd| plans.contains_key(&fd.name));
1220                        if all_supported {
1221                            toplevel::emit_mutual_group_proof(comp, ctx, &plans)
1222                        } else {
1223                            toplevel::emit_mutual_group(comp, ctx)
1224                        }
1225                    }
1226                    LeanEmitMode::Standard => toplevel::emit_mutual_group(comp, ctx),
1227                };
1228                out.push(code);
1229                out.push(String::new());
1230            } else if let Some(fd) = comp.first() {
1231                let emitted = match emit_mode {
1232                    LeanEmitMode::Proof => {
1233                        let is_recursive = recursive_names.contains(&fd.name);
1234                        if is_recursive && !plans.contains_key(&fd.name) {
1235                            toplevel::emit_fn_def(fd, &recursive_names, ctx)
1236                        } else {
1237                            toplevel::emit_fn_def_proof(fd, plans.get(&fd.name).cloned(), ctx)
1238                        }
1239                    }
1240                    LeanEmitMode::Standard => toplevel::emit_fn_def(fd, &recursive_fns, ctx),
1241                };
1242                if let Some(code) = emitted {
1243                    out.push(code);
1244                    out.push(String::new());
1245                }
1246            }
1247            out
1248        },
1249    );
1250
1251    // Lifted effectful fns + decisions + verifies remain entry-only.
1252    let mut entry_lifted_sections: Vec<String> = Vec::new();
1253    let lifted_recursive_names = match emit_mode {
1254        LeanEmitMode::Proof => &recursive_names,
1255        LeanEmitMode::Standard => &recursive_fns,
1256    };
1257    emit_lifted_effectful_functions(ctx, lifted_recursive_names, &mut entry_lifted_sections);
1258
1259    let mut entry_decision_sections: Vec<String> = Vec::new();
1260    for item in &ctx.items {
1261        if let TopLevel::Decision(db) = item {
1262            entry_decision_sections.push(toplevel::emit_decision(db));
1263            entry_decision_sections.push(String::new());
1264        }
1265    }
1266
1267    let mut entry_verify_sections: Vec<String> = Vec::new();
1268    let mut verify_case_counters: HashMap<String, usize> = HashMap::new();
1269    for item in &ctx.items {
1270        if let TopLevel::Verify(vb) = item {
1271            let key = verify_counter_key(vb);
1272            let start_idx = *verify_case_counters.get(&key).unwrap_or(&0);
1273            let (emitted, next_idx) = toplevel::emit_verify_block(vb, ctx, verify_mode, start_idx);
1274            verify_case_counters.insert(key, next_idx);
1275            entry_verify_sections.push(emitted);
1276            entry_verify_sections.push(String::new());
1277        }
1278    }
1279
1280    // ---- Per-module file bodies ----
1281    let mut module_files: Vec<(String, String)> = Vec::new();
1282    let mut union_body = String::new();
1283
1284    for module in &ctx.modules {
1285        let mut body_sections: Vec<String> = Vec::new();
1286        for td in &module.type_defs {
1287            body_sections.push(toplevel::emit_type_def(td));
1288            if toplevel::is_recursive_type_def(td) {
1289                body_sections.push(toplevel::emit_recursive_decidable_eq(
1290                    toplevel::type_def_name(td),
1291                ));
1292                if matches!(emit_mode, LeanEmitMode::Proof)
1293                    && let Some(measure) = toplevel::emit_recursive_measure(td, &recursive_types)
1294                {
1295                    body_sections.push(measure);
1296                }
1297            }
1298            body_sections.push(String::new());
1299        }
1300        if let Some(scope_sections) = pure_per_scope.by_scope.get(&module.prefix) {
1301            body_sections.extend(scope_sections.clone());
1302        }
1303        let body = body_sections.join("\n");
1304        union_body.push_str(&body);
1305        union_body.push('\n');
1306
1307        let mut imports = vec!["import AverCommon".to_string()];
1308        for d in &module.depends {
1309            imports.push(format!("import {}", d));
1310        }
1311        // AverCommon has no surrounding namespace (top-level helpers / instances),
1312        // so `import` already brings them into scope. We `open` only the
1313        // user-defined dependent modules.
1314        let opens: Vec<String> = module
1315            .depends
1316            .iter()
1317            .map(|d| format!("open {}", d))
1318            .collect();
1319
1320        let opens_str = if opens.is_empty() {
1321            String::new()
1322        } else {
1323            format!("\n{}\n", opens.join("\n"))
1324        };
1325        let content = format!(
1326            "{}\n{}\nnamespace {}\n\n{}\nend {}\n",
1327            imports.join("\n"),
1328            opens_str,
1329            module.prefix,
1330            body,
1331            module.prefix
1332        );
1333        let path = module.prefix.replace('.', "/");
1334        module_files.push((format!("{}.lean", path), content));
1335    }
1336
1337    // ---- Entry sections ----
1338    let mut entry_body_sections: Vec<String> = Vec::new();
1339    for td in &ctx.type_defs {
1340        entry_body_sections.push(toplevel::emit_type_def(td));
1341        if toplevel::is_recursive_type_def(td) {
1342            entry_body_sections.push(toplevel::emit_recursive_decidable_eq(
1343                toplevel::type_def_name(td),
1344            ));
1345            if matches!(emit_mode, LeanEmitMode::Proof)
1346                && let Some(measure) = toplevel::emit_recursive_measure(td, &recursive_types)
1347            {
1348                entry_body_sections.push(measure);
1349            }
1350        }
1351        entry_body_sections.push(String::new());
1352    }
1353    if let Some(entry_pure) = pure_per_scope.by_scope.get("") {
1354        entry_body_sections.extend(entry_pure.clone());
1355    }
1356    entry_body_sections.extend(entry_lifted_sections);
1357    entry_body_sections.extend(entry_decision_sections);
1358    entry_body_sections.extend(entry_verify_sections);
1359
1360    let entry_body = entry_body_sections.join("\n");
1361    union_body.push_str(&entry_body);
1362    union_body.push('\n');
1363
1364    let project_name = lean_project_name(ctx);
1365    let mut entry_imports = vec!["import AverCommon".to_string()];
1366    for m in &ctx.modules {
1367        entry_imports.push(format!("import {}", m.prefix));
1368    }
1369    let entry_opens: Vec<String> = ctx
1370        .modules
1371        .iter()
1372        .map(|m| format!("open {}", m.prefix))
1373        .collect();
1374    let mut entry_parts = vec![entry_imports.join("\n")];
1375    if !entry_opens.is_empty() {
1376        entry_parts.push(entry_opens.join("\n"));
1377    }
1378    let declared = crate::codegen::common::collect_declared_effects(ctx);
1379    let has_ip = union_body.contains("BranchPath");
1380    let has_classified =
1381        crate::types::checker::effect_classification::classifications_for_proof_subset()
1382            .iter()
1383            .any(|c| declared.includes(c.method));
1384    if has_ip || has_classified {
1385        entry_parts.push(
1386            crate::types::checker::proof_trust_header::generate_commented("-- ", &declared, has_ip),
1387        );
1388    }
1389    entry_parts.push(entry_body);
1390    let entry_content = entry_parts.join("\n\n");
1391
1392    // ---- AverCommon.lean ----
1393    let common_content = build_common_lean(&union_body);
1394
1395    // Project files
1396    let mut extra_roots: Vec<String> = vec!["AverCommon".to_string()];
1397    for m in &ctx.modules {
1398        extra_roots.push(m.prefix.clone());
1399    }
1400    let lakefile = generate_lakefile_with_roots(&project_name, &extra_roots);
1401    let toolchain = generate_toolchain();
1402
1403    let mut files = module_files;
1404    files.push((format!("{}.lean", project_name), entry_content));
1405    files.push(("AverCommon.lean".to_string(), common_content));
1406    files.push(("lakefile.lean".to_string(), lakefile));
1407    files.push(("lean-toolchain".to_string(), toolchain));
1408    ProjectOutput { files }
1409}
1410
1411fn build_common_lean(union_body: &str) -> String {
1412    let mut parts = vec![LEAN_PRELUDE_HEADER.to_string()];
1413    for record in crate::codegen::builtin_records::needed_records(union_body, false) {
1414        parts.push(crate::codegen::builtin_records::render_lean(record));
1415    }
1416    for helper in crate::codegen::builtin_helpers::needed_helpers(union_body, false) {
1417        match helper.key {
1418            "BranchPath" => parts.push(LEAN_PRELUDE_BRANCH_PATH.to_string()),
1419            "AverList" => parts.push(LEAN_PRELUDE_AVER_LIST.to_string()),
1420            "StringHelpers" => parts.push(LEAN_PRELUDE_STRING_HELPERS.to_string()),
1421            "NumericParse" => parts.push(LEAN_PRELUDE_NUMERIC_PARSE.to_string()),
1422            "CharByte" => parts.push(LEAN_PRELUDE_CHAR_BYTE.to_string()),
1423            "AverMeasure" => parts.push(LEAN_PRELUDE_AVER_MEASURE.to_string()),
1424            "AverMap" => parts.push(generate_map_prelude(union_body, false)),
1425            "ProofFuel" => parts.push(LEAN_PRELUDE_PROOF_FUEL.to_string()),
1426            "FloatInstances" => parts.extend([
1427                LEAN_PRELUDE_FLOAT_COE.to_string(),
1428                LEAN_PRELUDE_FLOAT_DEC_EQ.to_string(),
1429            ]),
1430            "ExceptInstances" => parts.extend([
1431                LEAN_PRELUDE_EXCEPT_DEC_EQ.to_string(),
1432                LEAN_PRELUDE_EXCEPT_NS.to_string(),
1433                LEAN_PRELUDE_OPTION_TO_EXCEPT.to_string(),
1434            ]),
1435            "StringHadd" => parts.push(LEAN_PRELUDE_STRING_HADD.to_string()),
1436            "ResultDatatype" | "OptionDatatype" | "OptionToResult" | "BranchPathDatatype" => {}
1437            other => panic!(
1438                "Lean backend has no implementation for builtin helper key '{}'. \
1439                 Add a match arm in build_common_lean or remove the key from BUILTIN_HELPERS.",
1440                other
1441            ),
1442        }
1443    }
1444    parts.join("\n\n")
1445}
1446
1447#[cfg(test)]
1448mod tests {
1449    use super::{
1450        VerifyEmitMode, generate_prelude, proof_mode_issues, recurrence, transpile,
1451        transpile_for_proof_mode, transpile_with_verify_mode,
1452    };
1453    use crate::ast::{
1454        BinOp, Expr, FnBody, FnDef, Literal, MatchArm, Pattern, Spanned, Stmt, TailCallData,
1455        TopLevel, TypeDef, TypeVariant, VerifyBlock, VerifyGiven, VerifyGivenDomain, VerifyKind,
1456        VerifyLaw,
1457    };
1458
1459    /// Shorthand: wrap an Expr in Spanned with line=0.
1460    fn sb(e: Expr) -> Spanned<Expr> {
1461        Spanned::bare(e)
1462    }
1463    /// Shorthand: wrap an Expr in Box<Spanned> with line=0.
1464    fn sbb(e: Expr) -> Box<Spanned<Expr>> {
1465        Box::new(Spanned::bare(e))
1466    }
1467    use crate::codegen::{CodegenContext, build_context};
1468    use crate::source::parse_source;
1469    use crate::tco;
1470    use crate::types::checker::run_type_check_full;
1471    use std::collections::{HashMap, HashSet};
1472    use std::sync::Arc as Rc;
1473
1474    fn empty_ctx() -> CodegenContext {
1475        CodegenContext {
1476            items: vec![],
1477            fn_sigs: HashMap::new(),
1478            memo_fns: HashSet::new(),
1479            memo_safe_types: HashSet::new(),
1480            type_defs: vec![],
1481            fn_defs: vec![],
1482            project_name: "verify_mode".to_string(),
1483            modules: vec![],
1484            module_prefixes: HashSet::new(),
1485            policy: None,
1486            emit_replay_runtime: false,
1487            runtime_policy_from_env: false,
1488            guest_entry: None,
1489            emit_self_host_support: false,
1490            extra_fn_defs: Vec::new(),
1491            mutual_tco_members: HashSet::new(),
1492        }
1493    }
1494
1495    fn ctx_from_source(source: &str, project_name: &str) -> CodegenContext {
1496        let mut items = parse_source(source).expect("source should parse");
1497        tco::transform_program(&mut items);
1498        let tc = run_type_check_full(&items, None);
1499        assert!(
1500            tc.errors.is_empty(),
1501            "source should typecheck without errors: {:?}",
1502            tc.errors
1503        );
1504        build_context(items, &tc, HashSet::new(), project_name.to_string(), vec![])
1505    }
1506
1507    /// Concatenate every emitted `.lean` source (entry + per-module +
1508    /// `AverCommon`) into a single string for content assertions. The
1509    /// unified emitter splits prelude (`AverCommon.lean`) and body
1510    /// (`<Project>.lean`) into separate files; tests originally checked
1511    /// for substrings against the legacy single-file output, so the
1512    /// helper now returns the concatenation so those substring assertions
1513    /// keep working regardless of which file the content lands in.
1514    fn generated_lean_file(out: &crate::codegen::ProjectOutput) -> String {
1515        out.files
1516            .iter()
1517            .filter_map(|(name, content)| {
1518                (name.ends_with(".lean") && name != "lakefile.lean").then_some(content.as_str())
1519            })
1520            .collect::<Vec<&str>>()
1521            .join("\n")
1522    }
1523
1524    fn empty_ctx_with_verify_case() -> CodegenContext {
1525        let mut ctx = empty_ctx();
1526        ctx.items.push(TopLevel::Verify(VerifyBlock {
1527            fn_name: "f".to_string(),
1528            line: 1,
1529            cases: vec![(
1530                sb(Expr::Literal(Literal::Int(1))),
1531                sb(Expr::Literal(Literal::Int(1))),
1532            )],
1533            case_spans: vec![],
1534            case_givens: vec![],
1535            kind: VerifyKind::Cases,
1536            trace: false,
1537            cases_givens: vec![],
1538        }));
1539        ctx
1540    }
1541
1542    fn empty_ctx_with_two_verify_blocks_same_fn() -> CodegenContext {
1543        let mut ctx = empty_ctx();
1544        ctx.items.push(TopLevel::Verify(VerifyBlock {
1545            fn_name: "f".to_string(),
1546            line: 1,
1547            cases: vec![(
1548                sb(Expr::Literal(Literal::Int(1))),
1549                sb(Expr::Literal(Literal::Int(1))),
1550            )],
1551            case_spans: vec![],
1552            case_givens: vec![],
1553            kind: VerifyKind::Cases,
1554            trace: false,
1555            cases_givens: vec![],
1556        }));
1557        ctx.items.push(TopLevel::Verify(VerifyBlock {
1558            fn_name: "f".to_string(),
1559            line: 2,
1560            cases: vec![(
1561                sb(Expr::Literal(Literal::Int(2))),
1562                sb(Expr::Literal(Literal::Int(2))),
1563            )],
1564            case_spans: vec![],
1565            case_givens: vec![],
1566            kind: VerifyKind::Cases,
1567            trace: false,
1568            cases_givens: vec![],
1569        }));
1570        ctx
1571    }
1572
1573    fn empty_ctx_with_verify_law() -> CodegenContext {
1574        let mut ctx = empty_ctx();
1575        let add = FnDef {
1576            name: "add".to_string(),
1577            line: 1,
1578            params: vec![
1579                ("a".to_string(), "Int".to_string()),
1580                ("b".to_string(), "Int".to_string()),
1581            ],
1582            return_type: "Int".to_string(),
1583            effects: vec![],
1584            desc: None,
1585            body: Rc::new(FnBody::from_expr(sb(Expr::BinOp(
1586                BinOp::Add,
1587                sbb(Expr::Ident("a".to_string())),
1588                sbb(Expr::Ident("b".to_string())),
1589            )))),
1590            resolution: None,
1591        };
1592        ctx.fn_defs.push(add.clone());
1593        ctx.items.push(TopLevel::FnDef(add));
1594        ctx.items.push(TopLevel::Verify(VerifyBlock {
1595            fn_name: "add".to_string(),
1596            line: 1,
1597            cases: vec![
1598                (
1599                    sb(Expr::FnCall(
1600                        sbb(Expr::Ident("add".to_string())),
1601                        vec![
1602                            sb(Expr::Literal(Literal::Int(1))),
1603                            sb(Expr::Literal(Literal::Int(2))),
1604                        ],
1605                    )),
1606                    sb(Expr::FnCall(
1607                        sbb(Expr::Ident("add".to_string())),
1608                        vec![
1609                            sb(Expr::Literal(Literal::Int(2))),
1610                            sb(Expr::Literal(Literal::Int(1))),
1611                        ],
1612                    )),
1613                ),
1614                (
1615                    sb(Expr::FnCall(
1616                        sbb(Expr::Ident("add".to_string())),
1617                        vec![
1618                            sb(Expr::Literal(Literal::Int(2))),
1619                            sb(Expr::Literal(Literal::Int(3))),
1620                        ],
1621                    )),
1622                    sb(Expr::FnCall(
1623                        sbb(Expr::Ident("add".to_string())),
1624                        vec![
1625                            sb(Expr::Literal(Literal::Int(3))),
1626                            sb(Expr::Literal(Literal::Int(2))),
1627                        ],
1628                    )),
1629                ),
1630            ],
1631            case_spans: vec![],
1632            case_givens: vec![],
1633            kind: VerifyKind::Law(Box::new(VerifyLaw {
1634                name: "commutative".to_string(),
1635                givens: vec![
1636                    VerifyGiven {
1637                        name: "a".to_string(),
1638                        type_name: "Int".to_string(),
1639                        domain: VerifyGivenDomain::IntRange { start: 1, end: 2 },
1640                    },
1641                    VerifyGiven {
1642                        name: "b".to_string(),
1643                        type_name: "Int".to_string(),
1644                        domain: VerifyGivenDomain::Explicit(vec![
1645                            sb(Expr::Literal(Literal::Int(2))),
1646                            sb(Expr::Literal(Literal::Int(3))),
1647                        ]),
1648                    },
1649                ],
1650                when: None,
1651                lhs: sb(Expr::FnCall(
1652                    sbb(Expr::Ident("add".to_string())),
1653                    vec![
1654                        sb(Expr::Ident("a".to_string())),
1655                        sb(Expr::Ident("b".to_string())),
1656                    ],
1657                )),
1658                rhs: sb(Expr::FnCall(
1659                    sbb(Expr::Ident("add".to_string())),
1660                    vec![
1661                        sb(Expr::Ident("b".to_string())),
1662                        sb(Expr::Ident("a".to_string())),
1663                    ],
1664                )),
1665                sample_guards: vec![],
1666            })),
1667            trace: false,
1668            cases_givens: vec![],
1669        }));
1670        ctx
1671    }
1672
1673    #[test]
1674    fn prelude_normalizes_float_string_format() {
1675        let prelude = generate_prelude();
1676        assert!(
1677            prelude.contains("private def normalizeFloatString (s : String) : String :="),
1678            "missing normalizeFloatString helper in prelude"
1679        );
1680        assert!(
1681            prelude.contains(
1682                "def String.fromFloat (f : Float) : String := normalizeFloatString (toString f)"
1683            ),
1684            "String.fromFloat should normalize Lean float formatting"
1685        );
1686    }
1687
1688    #[test]
1689    fn prelude_validates_char_from_code_unicode_bounds() {
1690        let prelude = generate_prelude();
1691        assert!(
1692            prelude.contains("if n < 0 || n > 1114111 then none"),
1693            "Char.fromCode should reject code points above Unicode max"
1694        );
1695        assert!(
1696            prelude.contains("else if n >= 55296 && n <= 57343 then none"),
1697            "Char.fromCode should reject surrogate code points"
1698        );
1699    }
1700
1701    #[test]
1702    fn prelude_includes_map_set_helper_lemmas() {
1703        let prelude = generate_prelude();
1704        assert!(
1705            prelude.contains("theorem has_set_self [DecidableEq α]"),
1706            "missing AverMap.has_set_self helper theorem"
1707        );
1708        assert!(
1709            prelude.contains("theorem get_set_self [DecidableEq α]"),
1710            "missing AverMap.get_set_self helper theorem"
1711        );
1712    }
1713
1714    #[test]
1715    fn lean_output_without_map_usage_omits_map_prelude() {
1716        let ctx = ctx_from_source(
1717            r#"
1718module NoMap
1719    intent = "Simple pure program without maps."
1720
1721fn addOne(n: Int) -> Int
1722    n + 1
1723
1724verify addOne
1725    addOne(1) => 2
1726"#,
1727            "nomap",
1728        );
1729        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
1730        let lean = generated_lean_file(&out);
1731
1732        assert!(
1733            !lean.contains("namespace AverMap"),
1734            "did not expect AverMap prelude in program without map usage:\n{}",
1735            lean
1736        );
1737    }
1738
1739    #[test]
1740    fn transpile_emits_native_decide_for_verify_by_default() {
1741        let out = transpile(&empty_ctx_with_verify_case());
1742        let lean = out
1743            .files
1744            .iter()
1745            .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
1746            .expect("expected generated Lean file");
1747        assert!(lean.contains("example : 1 = 1 := by native_decide"));
1748    }
1749
1750    #[test]
1751    fn transpile_can_emit_sorry_for_verify_when_requested() {
1752        let out = transpile_with_verify_mode(&empty_ctx_with_verify_case(), VerifyEmitMode::Sorry);
1753        let lean = out
1754            .files
1755            .iter()
1756            .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
1757            .expect("expected generated Lean file");
1758        assert!(lean.contains("example : 1 = 1 := by sorry"));
1759    }
1760
1761    #[test]
1762    fn transpile_can_emit_theorem_skeletons_for_verify() {
1763        let out = transpile_with_verify_mode(
1764            &empty_ctx_with_verify_case(),
1765            VerifyEmitMode::TheoremSkeleton,
1766        );
1767        let lean = out
1768            .files
1769            .iter()
1770            .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
1771            .expect("expected generated Lean file");
1772        assert!(lean.contains("theorem f_verify_1 : 1 = 1 := by"));
1773        assert!(lean.contains("  sorry"));
1774    }
1775
1776    #[test]
1777    fn theorem_skeleton_numbering_is_global_per_function_across_verify_blocks() {
1778        let out = transpile_with_verify_mode(
1779            &empty_ctx_with_two_verify_blocks_same_fn(),
1780            VerifyEmitMode::TheoremSkeleton,
1781        );
1782        let lean = out
1783            .files
1784            .iter()
1785            .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
1786            .expect("expected generated Lean file");
1787        assert!(lean.contains("theorem f_verify_1 : 1 = 1 := by"));
1788        assert!(lean.contains("theorem f_verify_2 : 2 = 2 := by"));
1789    }
1790
1791    #[test]
1792    fn transpile_emits_named_theorems_for_verify_law() {
1793        let out = transpile(&empty_ctx_with_verify_law());
1794        let lean = out
1795            .files
1796            .iter()
1797            .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
1798            .expect("expected generated Lean file");
1799        assert!(lean.contains("-- verify law add.commutative (2 cases)"));
1800        assert!(lean.contains("-- given a: Int = 1..2"));
1801        assert!(lean.contains("-- given b: Int = [2, 3]"));
1802        assert!(lean.contains(
1803            "theorem add_law_commutative : ∀ (a : Int) (b : Int), add a b = add b a := by"
1804        ));
1805        assert!(lean.contains("  intro a b"));
1806        assert!(lean.contains("  simp [add, Int.add_comm]"));
1807        assert!(lean.contains(
1808            "theorem add_law_commutative_sample_1 : add 1 2 = add 2 1 := by native_decide"
1809        ));
1810        assert!(lean.contains(
1811            "theorem add_law_commutative_sample_2 : add 2 3 = add 3 2 := by native_decide"
1812        ));
1813    }
1814
1815    #[test]
1816    fn generate_prelude_emits_int_roundtrip_theorem() {
1817        let lean = generate_prelude();
1818        assert!(lean.contains(
1819            "theorem Int.fromString_fromInt : ∀ n : Int, Int.fromString (String.fromInt n) = .ok n"
1820        ));
1821        assert!(lean.contains("theorem String.intercalate_empty_chars (s : String) :"));
1822        assert!(lean.contains("def splitOnCharGo"));
1823        assert!(lean.contains("theorem split_single_char_append"));
1824        assert!(lean.contains("theorem split_intercalate_trailing_single_char"));
1825        assert!(lean.contains("namespace AverDigits"));
1826        assert!(lean.contains("theorem String.charAt_length_none (s : String)"));
1827        assert!(lean.contains("theorem digitChar_not_ws : ∀ d : Nat, d < 10 ->"));
1828    }
1829
1830    #[test]
1831    fn transpile_emits_guarded_theorems_for_verify_law_when_clause() {
1832        let ctx = ctx_from_source(
1833            r#"
1834module GuardedLaw
1835    intent =
1836        "verify law with precondition"
1837
1838fn pickGreater(a: Int, b: Int) -> Int
1839    match a > b
1840        true -> a
1841        false -> b
1842
1843verify pickGreater law ordered
1844    given a: Int = [1, 2]
1845    given b: Int = [1, 2]
1846    when a > b
1847    pickGreater(a, b) => a
1848"#,
1849            "guarded_law",
1850        );
1851        let out = transpile_with_verify_mode(&ctx, VerifyEmitMode::TheoremSkeleton);
1852        let lean = generated_lean_file(&out);
1853
1854        assert!(lean.contains("-- when (a > b)"));
1855        assert!(lean.contains(
1856            "theorem pickGreater_law_ordered : ∀ (a : Int) (b : Int), a = 1 ∨ a = 2 -> b = 1 ∨ b = 2 -> (a > b) = true -> pickGreater a b = a := by"
1857        ));
1858        assert!(lean.contains(
1859            "theorem pickGreater_law_ordered_sample_1 : (1 > 1) = true -> pickGreater 1 1 = 1 := by"
1860        ));
1861        assert!(lean.contains(
1862            "theorem pickGreater_law_ordered_sample_4 : (2 > 2) = true -> pickGreater 2 2 = 2 := by"
1863        ));
1864    }
1865
1866    #[test]
1867    fn transpile_uses_spec_theorem_names_for_declared_spec_laws() {
1868        let ctx = ctx_from_source(
1869            r#"
1870module SpecDemo
1871    intent =
1872        "spec demo"
1873
1874fn absVal(x: Int) -> Int
1875    match x < 0
1876        true -> 0 - x
1877        false -> x
1878
1879fn absValSpec(x: Int) -> Int
1880    match x < 0
1881        true -> 0 - x
1882        false -> x
1883
1884verify absVal law absValSpec
1885    given x: Int = [-2, -1, 0, 1, 2]
1886    absVal(x) => absValSpec(x)
1887"#,
1888            "spec_demo",
1889        );
1890        let out = transpile_with_verify_mode(&ctx, VerifyEmitMode::TheoremSkeleton);
1891        let lean = generated_lean_file(&out);
1892
1893        assert!(lean.contains("-- verify law absVal.spec absValSpec (5 cases)"));
1894        assert!(
1895            lean.contains(
1896                "theorem absVal_eq_absValSpec : ∀ (x : Int), absVal x = absValSpec x := by"
1897            )
1898        );
1899        assert!(lean.contains("theorem absVal_eq_absValSpec_checked_domain :"));
1900        assert!(lean.contains("theorem absVal_eq_absValSpec_sample_1 :"));
1901        assert!(!lean.contains("theorem absVal_law_absValSpec :"));
1902    }
1903
1904    #[test]
1905    fn transpile_keeps_noncanonical_spec_laws_as_regular_law_names() {
1906        let ctx = ctx_from_source(
1907            r#"
1908module SpecLawShape
1909    intent =
1910        "shape probe"
1911
1912fn foo(x: Int) -> Int
1913    x + 1
1914
1915fn fooSpec(seed: Int, x: Int) -> Int
1916    x + seed
1917
1918verify foo law fooSpec
1919    given x: Int = [1, 2]
1920    foo(x) => fooSpec(1, x)
1921"#,
1922            "spec_law_shape",
1923        );
1924        let out = transpile_with_verify_mode(&ctx, VerifyEmitMode::TheoremSkeleton);
1925        let lean = generated_lean_file(&out);
1926
1927        assert!(lean.contains("-- verify law foo.fooSpec (2 cases)"));
1928        assert!(lean.contains("theorem foo_law_fooSpec : ∀ (x : Int), foo x = fooSpec 1 x := by"));
1929        assert!(!lean.contains("theorem foo_eq_fooSpec :"));
1930    }
1931
1932    #[test]
1933    fn transpile_auto_proves_linear_int_canonical_spec_law_in_auto_mode() {
1934        let ctx = ctx_from_source(
1935            r#"
1936module SpecGap
1937    intent =
1938        "nontrivial canonical spec law"
1939
1940fn inc(x: Int) -> Int
1941    x + 1
1942
1943fn incSpec(x: Int) -> Int
1944    x + 2 - 1
1945
1946verify inc law incSpec
1947    given x: Int = [0, 1, 2]
1948    inc(x) => incSpec(x)
1949"#,
1950            "spec_gap",
1951        );
1952        let out = transpile(&ctx);
1953        let lean = generated_lean_file(&out);
1954
1955        assert!(lean.contains("-- verify law inc.spec incSpec (3 cases)"));
1956        assert!(lean.contains("theorem inc_eq_incSpec : ∀ (x : Int), inc x = incSpec x := by"));
1957        assert!(lean.contains("change (x + 1) = ((x + 2) - 1)"));
1958        assert!(lean.contains("omega"));
1959        assert!(!lean.contains(
1960            "-- universal theorem inc_eq_incSpec omitted: sampled law shape is not auto-proved yet"
1961        ));
1962        assert!(lean.contains("theorem inc_eq_incSpec_checked_domain :"));
1963    }
1964
1965    #[test]
1966    fn transpile_auto_proves_guarded_canonical_spec_law_in_auto_mode() {
1967        let ctx = ctx_from_source(
1968            r#"
1969module GuardedSpecGap
1970    intent =
1971        "guarded canonical spec law"
1972
1973fn clampNonNegative(x: Int) -> Int
1974    match x < 0
1975        true -> 0
1976        false -> x
1977
1978fn clampNonNegativeSpec(x: Int) -> Int
1979    match x < 0
1980        true -> 0
1981        false -> x
1982
1983verify clampNonNegative law clampNonNegativeSpec
1984    given x: Int = [-2, -1, 0, 1, 2]
1985    when x >= 0
1986    clampNonNegative(x) => clampNonNegativeSpec(x)
1987"#,
1988            "guarded_spec_gap",
1989        );
1990        let out = transpile(&ctx);
1991        let lean = generated_lean_file(&out);
1992
1993        assert!(lean.contains("-- when (x >= 0)"));
1994        assert!(lean.contains(
1995            "theorem clampNonNegative_eq_clampNonNegativeSpec : ∀ (x : Int), x = (-2) ∨ x = (-1) ∨ x = 0 ∨ x = 1 ∨ x = 2 -> (x >= 0) = true -> clampNonNegative x = clampNonNegativeSpec x := by"
1996        ));
1997        assert!(lean.contains("intro x h_x h_when"));
1998        assert!(lean.contains("simpa [clampNonNegative, clampNonNegativeSpec]"));
1999        assert!(!lean.contains(
2000            "-- universal theorem clampNonNegative_eq_clampNonNegativeSpec omitted: sampled law shape is not auto-proved yet"
2001        ));
2002        assert!(!lean.contains("cases h_x"));
2003    }
2004
2005    #[test]
2006    fn transpile_auto_proves_simp_normalized_canonical_spec_law_in_auto_mode() {
2007        let ctx = ctx_from_source(
2008            r#"
2009module SpecGapNonlinear
2010    intent =
2011        "nonlinear canonical spec law"
2012
2013fn square(x: Int) -> Int
2014    x * x
2015
2016fn squareSpec(x: Int) -> Int
2017    x * x + 0
2018
2019verify square law squareSpec
2020    given x: Int = [0, 1, 2]
2021    square(x) => squareSpec(x)
2022"#,
2023            "spec_gap_nonlinear",
2024        );
2025        let out = transpile(&ctx);
2026        let lean = generated_lean_file(&out);
2027
2028        assert!(lean.contains("-- verify law square.spec squareSpec (3 cases)"));
2029        assert!(
2030            lean.contains(
2031                "theorem square_eq_squareSpec : ∀ (x : Int), square x = squareSpec x := by"
2032            )
2033        );
2034        assert!(lean.contains("simp [square, squareSpec]"));
2035        assert!(!lean.contains(
2036            "-- universal theorem square_eq_squareSpec omitted: sampled law shape is not auto-proved yet"
2037        ));
2038        assert!(lean.contains("theorem square_eq_squareSpec_checked_domain :"));
2039        assert!(lean.contains("theorem square_eq_squareSpec_sample_1 :"));
2040    }
2041
2042    #[test]
2043    fn transpile_auto_proves_reflexive_law_with_rfl() {
2044        let mut ctx = empty_ctx();
2045        ctx.items.push(TopLevel::Verify(VerifyBlock {
2046            fn_name: "idLaw".to_string(),
2047            line: 1,
2048            cases: vec![(
2049                sb(Expr::Literal(Literal::Int(1))),
2050                sb(Expr::Literal(Literal::Int(1))),
2051            )],
2052            case_spans: vec![],
2053            case_givens: vec![],
2054            kind: VerifyKind::Law(Box::new(VerifyLaw {
2055                name: "reflexive".to_string(),
2056                givens: vec![VerifyGiven {
2057                    name: "x".to_string(),
2058                    type_name: "Int".to_string(),
2059                    domain: VerifyGivenDomain::IntRange { start: 1, end: 2 },
2060                }],
2061                when: None,
2062                lhs: sb(Expr::Ident("x".to_string())),
2063                rhs: sb(Expr::Ident("x".to_string())),
2064                sample_guards: vec![],
2065            })),
2066            trace: false,
2067            cases_givens: vec![],
2068        }));
2069        let out = transpile(&ctx);
2070        let lean = out
2071            .files
2072            .iter()
2073            .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
2074            .expect("expected generated Lean file");
2075        assert!(lean.contains("theorem idLaw_law_reflexive : ∀ (x : Int), x = x := by"));
2076        assert!(lean.contains("  intro x"));
2077        assert!(lean.contains("  rfl"));
2078    }
2079
2080    #[test]
2081    fn transpile_auto_proves_identity_law_for_int_add_wrapper() {
2082        let mut ctx = empty_ctx_with_verify_law();
2083        ctx.items.push(TopLevel::Verify(VerifyBlock {
2084            fn_name: "add".to_string(),
2085            line: 10,
2086            cases: vec![(
2087                sb(Expr::FnCall(
2088                    sbb(Expr::Ident("add".to_string())),
2089                    vec![
2090                        sb(Expr::Literal(Literal::Int(1))),
2091                        sb(Expr::Literal(Literal::Int(0))),
2092                    ],
2093                )),
2094                sb(Expr::Literal(Literal::Int(1))),
2095            )],
2096            case_spans: vec![],
2097            case_givens: vec![],
2098            kind: VerifyKind::Law(Box::new(VerifyLaw {
2099                name: "identityZero".to_string(),
2100                givens: vec![VerifyGiven {
2101                    name: "a".to_string(),
2102                    type_name: "Int".to_string(),
2103                    domain: VerifyGivenDomain::Explicit(vec![
2104                        sb(Expr::Literal(Literal::Int(0))),
2105                        sb(Expr::Literal(Literal::Int(1))),
2106                    ]),
2107                }],
2108                when: None,
2109                lhs: sb(Expr::FnCall(
2110                    sbb(Expr::Ident("add".to_string())),
2111                    vec![
2112                        sb(Expr::Ident("a".to_string())),
2113                        sb(Expr::Literal(Literal::Int(0))),
2114                    ],
2115                )),
2116                rhs: sb(Expr::Ident("a".to_string())),
2117                sample_guards: vec![],
2118            })),
2119            trace: false,
2120            cases_givens: vec![],
2121        }));
2122        let out = transpile(&ctx);
2123        let lean = out
2124            .files
2125            .iter()
2126            .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
2127            .expect("expected generated Lean file");
2128        assert!(lean.contains("theorem add_law_identityZero : ∀ (a : Int), add a 0 = a := by"));
2129        assert!(lean.contains("  intro a"));
2130        assert!(lean.contains("  simp [add]"));
2131    }
2132
2133    #[test]
2134    fn transpile_auto_proves_associative_law_for_int_add_wrapper() {
2135        let mut ctx = empty_ctx_with_verify_law();
2136        ctx.items.push(TopLevel::Verify(VerifyBlock {
2137            fn_name: "add".to_string(),
2138            line: 20,
2139            cases: vec![(
2140                sb(Expr::FnCall(
2141                    sbb(Expr::Ident("add".to_string())),
2142                    vec![
2143                        sb(Expr::FnCall(
2144                            sbb(Expr::Ident("add".to_string())),
2145                            vec![
2146                                sb(Expr::Literal(Literal::Int(1))),
2147                                sb(Expr::Literal(Literal::Int(2))),
2148                            ],
2149                        )),
2150                        sb(Expr::Literal(Literal::Int(3))),
2151                    ],
2152                )),
2153                sb(Expr::FnCall(
2154                    sbb(Expr::Ident("add".to_string())),
2155                    vec![
2156                        sb(Expr::Literal(Literal::Int(1))),
2157                        sb(Expr::FnCall(
2158                            sbb(Expr::Ident("add".to_string())),
2159                            vec![
2160                                sb(Expr::Literal(Literal::Int(2))),
2161                                sb(Expr::Literal(Literal::Int(3))),
2162                            ],
2163                        )),
2164                    ],
2165                )),
2166            )],
2167            case_spans: vec![],
2168            case_givens: vec![],
2169            kind: VerifyKind::Law(Box::new(VerifyLaw {
2170                name: "associative".to_string(),
2171                givens: vec![
2172                    VerifyGiven {
2173                        name: "a".to_string(),
2174                        type_name: "Int".to_string(),
2175                        domain: VerifyGivenDomain::Explicit(vec![sb(Expr::Literal(Literal::Int(
2176                            1,
2177                        )))]),
2178                    },
2179                    VerifyGiven {
2180                        name: "b".to_string(),
2181                        type_name: "Int".to_string(),
2182                        domain: VerifyGivenDomain::Explicit(vec![sb(Expr::Literal(Literal::Int(
2183                            2,
2184                        )))]),
2185                    },
2186                    VerifyGiven {
2187                        name: "c".to_string(),
2188                        type_name: "Int".to_string(),
2189                        domain: VerifyGivenDomain::Explicit(vec![sb(Expr::Literal(Literal::Int(
2190                            3,
2191                        )))]),
2192                    },
2193                ],
2194                when: None,
2195                lhs: sb(Expr::FnCall(
2196                    sbb(Expr::Ident("add".to_string())),
2197                    vec![
2198                        sb(Expr::FnCall(
2199                            sbb(Expr::Ident("add".to_string())),
2200                            vec![
2201                                sb(Expr::Ident("a".to_string())),
2202                                sb(Expr::Ident("b".to_string())),
2203                            ],
2204                        )),
2205                        sb(Expr::Ident("c".to_string())),
2206                    ],
2207                )),
2208                rhs: sb(Expr::FnCall(
2209                    sbb(Expr::Ident("add".to_string())),
2210                    vec![
2211                        sb(Expr::Ident("a".to_string())),
2212                        sb(Expr::FnCall(
2213                            sbb(Expr::Ident("add".to_string())),
2214                            vec![
2215                                sb(Expr::Ident("b".to_string())),
2216                                sb(Expr::Ident("c".to_string())),
2217                            ],
2218                        )),
2219                    ],
2220                )),
2221                sample_guards: vec![],
2222            })),
2223            trace: false,
2224            cases_givens: vec![],
2225        }));
2226        let out = transpile(&ctx);
2227        let lean = out
2228            .files
2229            .iter()
2230            .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
2231            .expect("expected generated Lean file");
2232        assert!(lean.contains(
2233            "theorem add_law_associative : ∀ (a : Int) (b : Int) (c : Int), add (add a b) c = add a (add b c) := by"
2234        ));
2235        assert!(lean.contains("  intro a b c"));
2236        assert!(lean.contains("  simp [add, Int.add_assoc]"));
2237    }
2238
2239    #[test]
2240    fn transpile_auto_proves_sub_laws() {
2241        let mut ctx = empty_ctx();
2242        let sub = FnDef {
2243            name: "sub".to_string(),
2244            line: 1,
2245            params: vec![
2246                ("a".to_string(), "Int".to_string()),
2247                ("b".to_string(), "Int".to_string()),
2248            ],
2249            return_type: "Int".to_string(),
2250            effects: vec![],
2251            desc: None,
2252            body: Rc::new(FnBody::from_expr(sb(Expr::BinOp(
2253                BinOp::Sub,
2254                sbb(Expr::Ident("a".to_string())),
2255                sbb(Expr::Ident("b".to_string())),
2256            )))),
2257            resolution: None,
2258        };
2259        ctx.fn_defs.push(sub.clone());
2260        ctx.items.push(TopLevel::FnDef(sub));
2261
2262        ctx.items.push(TopLevel::Verify(VerifyBlock {
2263            fn_name: "sub".to_string(),
2264            line: 10,
2265            cases: vec![(
2266                sb(Expr::FnCall(
2267                    sbb(Expr::Ident("sub".to_string())),
2268                    vec![
2269                        sb(Expr::Literal(Literal::Int(2))),
2270                        sb(Expr::Literal(Literal::Int(0))),
2271                    ],
2272                )),
2273                sb(Expr::Literal(Literal::Int(2))),
2274            )],
2275            case_spans: vec![],
2276            case_givens: vec![],
2277            kind: VerifyKind::Law(Box::new(VerifyLaw {
2278                name: "rightIdentity".to_string(),
2279                givens: vec![VerifyGiven {
2280                    name: "a".to_string(),
2281                    type_name: "Int".to_string(),
2282                    domain: VerifyGivenDomain::Explicit(vec![sb(Expr::Literal(Literal::Int(2)))]),
2283                }],
2284                when: None,
2285                lhs: sb(Expr::FnCall(
2286                    sbb(Expr::Ident("sub".to_string())),
2287                    vec![
2288                        sb(Expr::Ident("a".to_string())),
2289                        sb(Expr::Literal(Literal::Int(0))),
2290                    ],
2291                )),
2292                rhs: sb(Expr::Ident("a".to_string())),
2293                sample_guards: vec![],
2294            })),
2295            trace: false,
2296            cases_givens: vec![],
2297        }));
2298        ctx.items.push(TopLevel::Verify(VerifyBlock {
2299            fn_name: "sub".to_string(),
2300            line: 20,
2301            cases: vec![(
2302                sb(Expr::FnCall(
2303                    sbb(Expr::Ident("sub".to_string())),
2304                    vec![
2305                        sb(Expr::Literal(Literal::Int(2))),
2306                        sb(Expr::Literal(Literal::Int(1))),
2307                    ],
2308                )),
2309                sb(Expr::BinOp(
2310                    BinOp::Sub,
2311                    sbb(Expr::Literal(Literal::Int(0))),
2312                    sbb(Expr::FnCall(
2313                        sbb(Expr::Ident("sub".to_string())),
2314                        vec![
2315                            sb(Expr::Literal(Literal::Int(1))),
2316                            sb(Expr::Literal(Literal::Int(2))),
2317                        ],
2318                    )),
2319                )),
2320            )],
2321            case_spans: vec![],
2322            case_givens: vec![],
2323            kind: VerifyKind::Law(Box::new(VerifyLaw {
2324                name: "antiCommutative".to_string(),
2325                givens: vec![
2326                    VerifyGiven {
2327                        name: "a".to_string(),
2328                        type_name: "Int".to_string(),
2329                        domain: VerifyGivenDomain::Explicit(vec![sb(Expr::Literal(Literal::Int(
2330                            2,
2331                        )))]),
2332                    },
2333                    VerifyGiven {
2334                        name: "b".to_string(),
2335                        type_name: "Int".to_string(),
2336                        domain: VerifyGivenDomain::Explicit(vec![sb(Expr::Literal(Literal::Int(
2337                            1,
2338                        )))]),
2339                    },
2340                ],
2341                when: None,
2342                lhs: sb(Expr::FnCall(
2343                    sbb(Expr::Ident("sub".to_string())),
2344                    vec![
2345                        sb(Expr::Ident("a".to_string())),
2346                        sb(Expr::Ident("b".to_string())),
2347                    ],
2348                )),
2349                rhs: sb(Expr::BinOp(
2350                    BinOp::Sub,
2351                    sbb(Expr::Literal(Literal::Int(0))),
2352                    sbb(Expr::FnCall(
2353                        sbb(Expr::Ident("sub".to_string())),
2354                        vec![
2355                            sb(Expr::Ident("b".to_string())),
2356                            sb(Expr::Ident("a".to_string())),
2357                        ],
2358                    )),
2359                )),
2360                sample_guards: vec![],
2361            })),
2362            trace: false,
2363            cases_givens: vec![],
2364        }));
2365
2366        let out = transpile(&ctx);
2367        let lean = out
2368            .files
2369            .iter()
2370            .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
2371            .expect("expected generated Lean file");
2372        assert!(lean.contains("theorem sub_law_rightIdentity : ∀ (a : Int), sub a 0 = a := by"));
2373        assert!(lean.contains("  simp [sub]"));
2374        assert!(lean.contains(
2375            "theorem sub_law_antiCommutative : ∀ (a : Int) (b : Int), sub a b = (-sub b a) := by"
2376        ));
2377        assert!(lean.contains("  simpa [sub] using (Int.neg_sub b a).symm"));
2378    }
2379
2380    #[test]
2381    fn transpile_auto_proves_unary_wrapper_equivalence_law() {
2382        let mut ctx = empty_ctx();
2383        let add = FnDef {
2384            name: "add".to_string(),
2385            line: 1,
2386            params: vec![
2387                ("a".to_string(), "Int".to_string()),
2388                ("b".to_string(), "Int".to_string()),
2389            ],
2390            return_type: "Int".to_string(),
2391            effects: vec![],
2392            desc: None,
2393            body: Rc::new(FnBody::from_expr(sb(Expr::BinOp(
2394                BinOp::Add,
2395                sbb(Expr::Ident("a".to_string())),
2396                sbb(Expr::Ident("b".to_string())),
2397            )))),
2398            resolution: None,
2399        };
2400        let add_one = FnDef {
2401            name: "addOne".to_string(),
2402            line: 2,
2403            params: vec![("n".to_string(), "Int".to_string())],
2404            return_type: "Int".to_string(),
2405            effects: vec![],
2406            desc: None,
2407            body: Rc::new(FnBody::from_expr(sb(Expr::BinOp(
2408                BinOp::Add,
2409                sbb(Expr::Ident("n".to_string())),
2410                sbb(Expr::Literal(Literal::Int(1))),
2411            )))),
2412            resolution: None,
2413        };
2414        ctx.fn_defs.push(add.clone());
2415        ctx.fn_defs.push(add_one.clone());
2416        ctx.items.push(TopLevel::FnDef(add));
2417        ctx.items.push(TopLevel::FnDef(add_one));
2418        ctx.items.push(TopLevel::Verify(VerifyBlock {
2419            fn_name: "addOne".to_string(),
2420            line: 3,
2421            cases: vec![(
2422                sb(Expr::FnCall(
2423                    sbb(Expr::Ident("addOne".to_string())),
2424                    vec![sb(Expr::Literal(Literal::Int(2)))],
2425                )),
2426                sb(Expr::FnCall(
2427                    sbb(Expr::Ident("add".to_string())),
2428                    vec![
2429                        sb(Expr::Literal(Literal::Int(2))),
2430                        sb(Expr::Literal(Literal::Int(1))),
2431                    ],
2432                )),
2433            )],
2434            case_spans: vec![],
2435            case_givens: vec![],
2436            kind: VerifyKind::Law(Box::new(VerifyLaw {
2437                name: "identityViaAdd".to_string(),
2438                givens: vec![VerifyGiven {
2439                    name: "n".to_string(),
2440                    type_name: "Int".to_string(),
2441                    domain: VerifyGivenDomain::Explicit(vec![sb(Expr::Literal(Literal::Int(2)))]),
2442                }],
2443                when: None,
2444                lhs: sb(Expr::FnCall(
2445                    sbb(Expr::Ident("addOne".to_string())),
2446                    vec![sb(Expr::Ident("n".to_string()))],
2447                )),
2448                rhs: sb(Expr::FnCall(
2449                    sbb(Expr::Ident("add".to_string())),
2450                    vec![
2451                        sb(Expr::Ident("n".to_string())),
2452                        sb(Expr::Literal(Literal::Int(1))),
2453                    ],
2454                )),
2455                sample_guards: vec![],
2456            })),
2457            trace: false,
2458            cases_givens: vec![],
2459        }));
2460        let out = transpile(&ctx);
2461        let lean = out
2462            .files
2463            .iter()
2464            .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
2465            .expect("expected generated Lean file");
2466        assert!(
2467            lean.contains(
2468                "theorem addOne_law_identityViaAdd : ∀ (n : Int), addOne n = add n 1 := by"
2469            )
2470        );
2471        assert!(lean.contains("  simp [addOne, add]"));
2472    }
2473
2474    #[test]
2475    fn transpile_auto_proves_direct_map_set_laws() {
2476        let mut ctx = empty_ctx();
2477
2478        let map_set = |m: Spanned<Expr>, k: Spanned<Expr>, v: Spanned<Expr>| {
2479            sb(Expr::FnCall(
2480                sbb(Expr::Attr(
2481                    sbb(Expr::Ident("Map".to_string())),
2482                    "set".to_string(),
2483                )),
2484                vec![m, k, v],
2485            ))
2486        };
2487        let map_has = |m: Spanned<Expr>, k: Spanned<Expr>| {
2488            sb(Expr::FnCall(
2489                sbb(Expr::Attr(
2490                    sbb(Expr::Ident("Map".to_string())),
2491                    "has".to_string(),
2492                )),
2493                vec![m, k],
2494            ))
2495        };
2496        let map_get = |m: Spanned<Expr>, k: Spanned<Expr>| {
2497            sb(Expr::FnCall(
2498                sbb(Expr::Attr(
2499                    sbb(Expr::Ident("Map".to_string())),
2500                    "get".to_string(),
2501                )),
2502                vec![m, k],
2503            ))
2504        };
2505        let some = |v: Spanned<Expr>| {
2506            sb(Expr::FnCall(
2507                sbb(Expr::Attr(
2508                    sbb(Expr::Ident("Option".to_string())),
2509                    "Some".to_string(),
2510                )),
2511                vec![v],
2512            ))
2513        };
2514        let map_empty = || {
2515            sb(Expr::FnCall(
2516                sbb(Expr::Attr(
2517                    sbb(Expr::Ident("Map".to_string())),
2518                    "empty".to_string(),
2519                )),
2520                vec![],
2521            ))
2522        };
2523
2524        ctx.items.push(TopLevel::Verify(VerifyBlock {
2525            fn_name: "map".to_string(),
2526            line: 1,
2527            cases: vec![(
2528                map_has(
2529                    map_set(
2530                        sb(Expr::Ident("m".to_string())),
2531                        sb(Expr::Ident("k".to_string())),
2532                        sb(Expr::Ident("v".to_string())),
2533                    ),
2534                    sb(Expr::Ident("k".to_string())),
2535                ),
2536                sb(Expr::Literal(Literal::Bool(true))),
2537            )],
2538            case_spans: vec![],
2539            case_givens: vec![],
2540            kind: VerifyKind::Law(Box::new(VerifyLaw {
2541                name: "setHasKey".to_string(),
2542                givens: vec![
2543                    VerifyGiven {
2544                        name: "m".to_string(),
2545                        type_name: "Map<String, Int>".to_string(),
2546                        domain: VerifyGivenDomain::Explicit(vec![map_empty()]),
2547                    },
2548                    VerifyGiven {
2549                        name: "k".to_string(),
2550                        type_name: "String".to_string(),
2551                        domain: VerifyGivenDomain::Explicit(vec![sb(Expr::Literal(Literal::Str(
2552                            "a".to_string(),
2553                        )))]),
2554                    },
2555                    VerifyGiven {
2556                        name: "v".to_string(),
2557                        type_name: "Int".to_string(),
2558                        domain: VerifyGivenDomain::Explicit(vec![sb(Expr::Literal(Literal::Int(
2559                            1,
2560                        )))]),
2561                    },
2562                ],
2563                when: None,
2564                lhs: map_has(
2565                    map_set(
2566                        sb(Expr::Ident("m".to_string())),
2567                        sb(Expr::Ident("k".to_string())),
2568                        sb(Expr::Ident("v".to_string())),
2569                    ),
2570                    sb(Expr::Ident("k".to_string())),
2571                ),
2572                rhs: sb(Expr::Literal(Literal::Bool(true))),
2573                sample_guards: vec![],
2574            })),
2575            trace: false,
2576            cases_givens: vec![],
2577        }));
2578
2579        ctx.items.push(TopLevel::Verify(VerifyBlock {
2580            fn_name: "map".to_string(),
2581            line: 2,
2582            cases: vec![(
2583                map_get(
2584                    map_set(
2585                        sb(Expr::Ident("m".to_string())),
2586                        sb(Expr::Ident("k".to_string())),
2587                        sb(Expr::Ident("v".to_string())),
2588                    ),
2589                    sb(Expr::Ident("k".to_string())),
2590                ),
2591                some(sb(Expr::Ident("v".to_string()))),
2592            )],
2593            case_spans: vec![],
2594            case_givens: vec![],
2595            kind: VerifyKind::Law(Box::new(VerifyLaw {
2596                name: "setGetKey".to_string(),
2597                givens: vec![
2598                    VerifyGiven {
2599                        name: "m".to_string(),
2600                        type_name: "Map<String, Int>".to_string(),
2601                        domain: VerifyGivenDomain::Explicit(vec![map_empty()]),
2602                    },
2603                    VerifyGiven {
2604                        name: "k".to_string(),
2605                        type_name: "String".to_string(),
2606                        domain: VerifyGivenDomain::Explicit(vec![sb(Expr::Literal(Literal::Str(
2607                            "a".to_string(),
2608                        )))]),
2609                    },
2610                    VerifyGiven {
2611                        name: "v".to_string(),
2612                        type_name: "Int".to_string(),
2613                        domain: VerifyGivenDomain::Explicit(vec![sb(Expr::Literal(Literal::Int(
2614                            1,
2615                        )))]),
2616                    },
2617                ],
2618                when: None,
2619                lhs: map_get(
2620                    map_set(
2621                        sb(Expr::Ident("m".to_string())),
2622                        sb(Expr::Ident("k".to_string())),
2623                        sb(Expr::Ident("v".to_string())),
2624                    ),
2625                    sb(Expr::Ident("k".to_string())),
2626                ),
2627                rhs: some(sb(Expr::Ident("v".to_string()))),
2628                sample_guards: vec![],
2629            })),
2630            trace: false,
2631            cases_givens: vec![],
2632        }));
2633
2634        let out = transpile(&ctx);
2635        let lean = out
2636            .files
2637            .iter()
2638            .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
2639            .expect("expected generated Lean file");
2640        assert!(lean.contains("simpa using AverMap.has_set_self m k v"));
2641        assert!(lean.contains("simpa using AverMap.get_set_self m k v"));
2642    }
2643
2644    #[test]
2645    fn transpile_auto_proves_direct_recursive_sum_law_by_structural_induction() {
2646        let ctx = ctx_from_source(
2647            r#"
2648module Mirror
2649    intent =
2650        "direct recursive sum induction probe"
2651
2652type Tree
2653    Leaf(Int)
2654    Node(Tree, Tree)
2655
2656fn mirror(t: Tree) -> Tree
2657    match t
2658        Tree.Leaf(v) -> Tree.Leaf(v)
2659        Tree.Node(left, right) -> Tree.Node(mirror(right), mirror(left))
2660
2661verify mirror law involutive
2662    given t: Tree = [Tree.Leaf(1), Tree.Node(Tree.Leaf(1), Tree.Leaf(2))]
2663    mirror(mirror(t)) => t
2664"#,
2665            "mirror",
2666        );
2667        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
2668        let lean = generated_lean_file(&out);
2669
2670        assert!(
2671            lean.contains(
2672                "theorem mirror_law_involutive : ∀ (t : Tree), mirror (mirror t) = t := by"
2673            )
2674        );
2675        assert!(lean.contains("  induction t with"));
2676        assert!(lean.contains("  | leaf f0 => simp [mirror]"));
2677        assert!(lean.contains("  | node f0 f1 ih0 ih1 => simp_all [mirror]"));
2678        assert!(!lean.contains(
2679            "-- universal theorem mirror_law_involutive omitted: sampled law shape is not auto-proved yet"
2680        ));
2681    }
2682
2683    #[test]
2684    fn transpile_auto_proves_map_update_laws() {
2685        let mut ctx = empty_ctx();
2686
2687        let map_get = |m: Spanned<Expr>, k: Spanned<Expr>| {
2688            sb(Expr::FnCall(
2689                sbb(Expr::Attr(
2690                    sbb(Expr::Ident("Map".to_string())),
2691                    "get".to_string(),
2692                )),
2693                vec![m, k],
2694            ))
2695        };
2696        let map_set = |m: Spanned<Expr>, k: Spanned<Expr>, v: Spanned<Expr>| {
2697            sb(Expr::FnCall(
2698                sbb(Expr::Attr(
2699                    sbb(Expr::Ident("Map".to_string())),
2700                    "set".to_string(),
2701                )),
2702                vec![m, k, v],
2703            ))
2704        };
2705        let map_has = |m: Spanned<Expr>, k: Spanned<Expr>| {
2706            sb(Expr::FnCall(
2707                sbb(Expr::Attr(
2708                    sbb(Expr::Ident("Map".to_string())),
2709                    "has".to_string(),
2710                )),
2711                vec![m, k],
2712            ))
2713        };
2714        let option_some = |v: Spanned<Expr>| {
2715            sb(Expr::FnCall(
2716                sbb(Expr::Attr(
2717                    sbb(Expr::Ident("Option".to_string())),
2718                    "Some".to_string(),
2719                )),
2720                vec![v],
2721            ))
2722        };
2723        let option_with_default = |opt: Spanned<Expr>, def: Spanned<Expr>| {
2724            sb(Expr::FnCall(
2725                sbb(Expr::Attr(
2726                    sbb(Expr::Ident("Option".to_string())),
2727                    "withDefault".to_string(),
2728                )),
2729                vec![opt, def],
2730            ))
2731        };
2732        let map_empty = || {
2733            sb(Expr::FnCall(
2734                sbb(Expr::Attr(
2735                    sbb(Expr::Ident("Map".to_string())),
2736                    "empty".to_string(),
2737                )),
2738                vec![],
2739            ))
2740        };
2741
2742        let add_one = FnDef {
2743            name: "addOne".to_string(),
2744            line: 1,
2745            params: vec![("n".to_string(), "Int".to_string())],
2746            return_type: "Int".to_string(),
2747            effects: vec![],
2748            desc: None,
2749            body: Rc::new(FnBody::from_expr(sb(Expr::BinOp(
2750                BinOp::Add,
2751                sbb(Expr::Ident("n".to_string())),
2752                sbb(Expr::Literal(Literal::Int(1))),
2753            )))),
2754            resolution: None,
2755        };
2756        ctx.fn_defs.push(add_one.clone());
2757        ctx.items.push(TopLevel::FnDef(add_one));
2758
2759        let inc_count = FnDef {
2760            name: "incCount".to_string(),
2761            line: 2,
2762            params: vec![
2763                ("counts".to_string(), "Map<String, Int>".to_string()),
2764                ("word".to_string(), "String".to_string()),
2765            ],
2766            return_type: "Map<String, Int>".to_string(),
2767            effects: vec![],
2768            desc: None,
2769            body: Rc::new(FnBody::Block(vec![
2770                Stmt::Binding(
2771                    "current".to_string(),
2772                    None,
2773                    map_get(
2774                        sb(Expr::Ident("counts".to_string())),
2775                        sb(Expr::Ident("word".to_string())),
2776                    ),
2777                ),
2778                Stmt::Expr(sb(Expr::Match {
2779                    subject: sbb(Expr::Ident("current".to_string())),
2780                    arms: vec![
2781                        MatchArm {
2782                            pattern: Pattern::Constructor(
2783                                "Option.Some".to_string(),
2784                                vec!["n".to_string()],
2785                            ),
2786                            body: Box::new(map_set(
2787                                sb(Expr::Ident("counts".to_string())),
2788                                sb(Expr::Ident("word".to_string())),
2789                                sb(Expr::BinOp(
2790                                    BinOp::Add,
2791                                    sbb(Expr::Ident("n".to_string())),
2792                                    sbb(Expr::Literal(Literal::Int(1))),
2793                                )),
2794                            )),
2795                        },
2796                        MatchArm {
2797                            pattern: Pattern::Constructor("Option.None".to_string(), vec![]),
2798                            body: Box::new(map_set(
2799                                sb(Expr::Ident("counts".to_string())),
2800                                sb(Expr::Ident("word".to_string())),
2801                                sb(Expr::Literal(Literal::Int(1))),
2802                            )),
2803                        },
2804                    ],
2805                })),
2806            ])),
2807            resolution: None,
2808        };
2809        ctx.fn_defs.push(inc_count.clone());
2810        ctx.items.push(TopLevel::FnDef(inc_count));
2811
2812        ctx.items.push(TopLevel::Verify(VerifyBlock {
2813            fn_name: "incCount".to_string(),
2814            line: 10,
2815            cases: vec![(
2816                map_has(
2817                    sb(Expr::FnCall(
2818                        sbb(Expr::Ident("incCount".to_string())),
2819                        vec![
2820                            sb(Expr::Ident("counts".to_string())),
2821                            sb(Expr::Ident("word".to_string())),
2822                        ],
2823                    )),
2824                    sb(Expr::Ident("word".to_string())),
2825                ),
2826                sb(Expr::Literal(Literal::Bool(true))),
2827            )],
2828            case_spans: vec![],
2829            case_givens: vec![],
2830            kind: VerifyKind::Law(Box::new(VerifyLaw {
2831                name: "keyPresent".to_string(),
2832                givens: vec![
2833                    VerifyGiven {
2834                        name: "counts".to_string(),
2835                        type_name: "Map<String, Int>".to_string(),
2836                        domain: VerifyGivenDomain::Explicit(vec![map_empty()]),
2837                    },
2838                    VerifyGiven {
2839                        name: "word".to_string(),
2840                        type_name: "String".to_string(),
2841                        domain: VerifyGivenDomain::Explicit(vec![sb(Expr::Literal(Literal::Str(
2842                            "a".to_string(),
2843                        )))]),
2844                    },
2845                ],
2846                when: None,
2847                lhs: map_has(
2848                    sb(Expr::FnCall(
2849                        sbb(Expr::Ident("incCount".to_string())),
2850                        vec![
2851                            sb(Expr::Ident("counts".to_string())),
2852                            sb(Expr::Ident("word".to_string())),
2853                        ],
2854                    )),
2855                    sb(Expr::Ident("word".to_string())),
2856                ),
2857                rhs: sb(Expr::Literal(Literal::Bool(true))),
2858                sample_guards: vec![],
2859            })),
2860            trace: false,
2861            cases_givens: vec![],
2862        }));
2863
2864        ctx.items.push(TopLevel::Verify(VerifyBlock {
2865            fn_name: "incCount".to_string(),
2866            line: 20,
2867            cases: vec![(
2868                map_get(
2869                    sb(Expr::FnCall(
2870                        sbb(Expr::Ident("incCount".to_string())),
2871                        vec![
2872                            sb(Expr::Ident("counts".to_string())),
2873                            sb(Expr::Literal(Literal::Str("a".to_string()))),
2874                        ],
2875                    )),
2876                    sb(Expr::Literal(Literal::Str("a".to_string()))),
2877                ),
2878                option_some(sb(Expr::FnCall(
2879                    sbb(Expr::Ident("addOne".to_string())),
2880                    vec![option_with_default(
2881                        map_get(
2882                            sb(Expr::Ident("counts".to_string())),
2883                            sb(Expr::Literal(Literal::Str("a".to_string()))),
2884                        ),
2885                        sb(Expr::Literal(Literal::Int(0))),
2886                    )],
2887                ))),
2888            )],
2889            case_spans: vec![],
2890            case_givens: vec![],
2891            kind: VerifyKind::Law(Box::new(VerifyLaw {
2892                name: "existingKeyIncrements".to_string(),
2893                givens: vec![VerifyGiven {
2894                    name: "counts".to_string(),
2895                    type_name: "Map<String, Int>".to_string(),
2896                    domain: VerifyGivenDomain::Explicit(vec![map_empty()]),
2897                }],
2898                when: None,
2899                lhs: map_get(
2900                    sb(Expr::FnCall(
2901                        sbb(Expr::Ident("incCount".to_string())),
2902                        vec![
2903                            sb(Expr::Ident("counts".to_string())),
2904                            sb(Expr::Literal(Literal::Str("a".to_string()))),
2905                        ],
2906                    )),
2907                    sb(Expr::Literal(Literal::Str("a".to_string()))),
2908                ),
2909                rhs: option_some(sb(Expr::FnCall(
2910                    sbb(Expr::Ident("addOne".to_string())),
2911                    vec![option_with_default(
2912                        map_get(
2913                            sb(Expr::Ident("counts".to_string())),
2914                            sb(Expr::Literal(Literal::Str("a".to_string()))),
2915                        ),
2916                        sb(Expr::Literal(Literal::Int(0))),
2917                    )],
2918                ))),
2919                sample_guards: vec![],
2920            })),
2921            trace: false,
2922            cases_givens: vec![],
2923        }));
2924
2925        let out = transpile(&ctx);
2926        let lean = out
2927            .files
2928            .iter()
2929            .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
2930            .expect("expected generated Lean file");
2931        assert!(
2932            lean.contains("cases h : AverMap.get counts word <;> simp [AverMap.has_set_self]"),
2933            "expected keyPresent auto-proof with has_set_self"
2934        );
2935        assert!(
2936            lean.contains("cases h : AverMap.get counts \"a\" <;> simp [AverMap.get_set_self, addOne, incCount]"),
2937            "expected existingKeyIncrements auto-proof with get_set_self"
2938        );
2939    }
2940
2941    #[test]
2942    fn transpile_parenthesizes_negative_int_call_args_in_law_samples() {
2943        let mut ctx = empty_ctx();
2944        let add = FnDef {
2945            name: "add".to_string(),
2946            line: 1,
2947            params: vec![
2948                ("a".to_string(), "Int".to_string()),
2949                ("b".to_string(), "Int".to_string()),
2950            ],
2951            return_type: "Int".to_string(),
2952            effects: vec![],
2953            desc: None,
2954            body: Rc::new(FnBody::from_expr(sb(Expr::BinOp(
2955                BinOp::Add,
2956                sbb(Expr::Ident("a".to_string())),
2957                sbb(Expr::Ident("b".to_string())),
2958            )))),
2959            resolution: None,
2960        };
2961        ctx.fn_defs.push(add.clone());
2962        ctx.items.push(TopLevel::FnDef(add));
2963        ctx.items.push(TopLevel::Verify(VerifyBlock {
2964            fn_name: "add".to_string(),
2965            line: 1,
2966            cases: vec![(
2967                sb(Expr::FnCall(
2968                    sbb(Expr::Ident("add".to_string())),
2969                    vec![
2970                        sb(Expr::Literal(Literal::Int(-2))),
2971                        sb(Expr::Literal(Literal::Int(-1))),
2972                    ],
2973                )),
2974                sb(Expr::FnCall(
2975                    sbb(Expr::Ident("add".to_string())),
2976                    vec![
2977                        sb(Expr::Literal(Literal::Int(-1))),
2978                        sb(Expr::Literal(Literal::Int(-2))),
2979                    ],
2980                )),
2981            )],
2982            case_spans: vec![],
2983            case_givens: vec![],
2984            kind: VerifyKind::Law(Box::new(VerifyLaw {
2985                name: "commutative".to_string(),
2986                givens: vec![
2987                    VerifyGiven {
2988                        name: "a".to_string(),
2989                        type_name: "Int".to_string(),
2990                        domain: VerifyGivenDomain::Explicit(vec![sb(Expr::Literal(Literal::Int(
2991                            -2,
2992                        )))]),
2993                    },
2994                    VerifyGiven {
2995                        name: "b".to_string(),
2996                        type_name: "Int".to_string(),
2997                        domain: VerifyGivenDomain::Explicit(vec![sb(Expr::Literal(Literal::Int(
2998                            -1,
2999                        )))]),
3000                    },
3001                ],
3002                when: None,
3003                lhs: sb(Expr::FnCall(
3004                    sbb(Expr::Ident("add".to_string())),
3005                    vec![
3006                        sb(Expr::Ident("a".to_string())),
3007                        sb(Expr::Ident("b".to_string())),
3008                    ],
3009                )),
3010                rhs: sb(Expr::FnCall(
3011                    sbb(Expr::Ident("add".to_string())),
3012                    vec![
3013                        sb(Expr::Ident("b".to_string())),
3014                        sb(Expr::Ident("a".to_string())),
3015                    ],
3016                )),
3017                sample_guards: vec![],
3018            })),
3019            trace: false,
3020            cases_givens: vec![],
3021        }));
3022
3023        let out = transpile(&ctx);
3024        let lean = out
3025            .files
3026            .iter()
3027            .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
3028            .expect("expected generated Lean file");
3029        assert!(lean.contains(
3030            "theorem add_law_commutative_sample_1 : add (-2) (-1) = add (-1) (-2) := by native_decide"
3031        ));
3032    }
3033
3034    #[test]
3035    fn verify_law_numbering_is_scoped_per_law_name() {
3036        let mut ctx = empty_ctx();
3037        let f = FnDef {
3038            name: "f".to_string(),
3039            line: 1,
3040            params: vec![("x".to_string(), "Int".to_string())],
3041            return_type: "Int".to_string(),
3042            effects: vec![],
3043            desc: None,
3044            body: Rc::new(FnBody::from_expr(sb(Expr::Ident("x".to_string())))),
3045            resolution: None,
3046        };
3047        ctx.fn_defs.push(f.clone());
3048        ctx.items.push(TopLevel::FnDef(f));
3049        ctx.items.push(TopLevel::Verify(VerifyBlock {
3050            fn_name: "f".to_string(),
3051            line: 1,
3052            cases: vec![(
3053                sb(Expr::Literal(Literal::Int(1))),
3054                sb(Expr::Literal(Literal::Int(1))),
3055            )],
3056            case_spans: vec![],
3057            case_givens: vec![],
3058            kind: VerifyKind::Cases,
3059            trace: false,
3060            cases_givens: vec![],
3061        }));
3062        ctx.items.push(TopLevel::Verify(VerifyBlock {
3063            fn_name: "f".to_string(),
3064            line: 2,
3065            cases: vec![(
3066                sb(Expr::Literal(Literal::Int(2))),
3067                sb(Expr::Literal(Literal::Int(2))),
3068            )],
3069            case_spans: vec![],
3070            case_givens: vec![],
3071            kind: VerifyKind::Law(Box::new(VerifyLaw {
3072                name: "identity".to_string(),
3073                givens: vec![VerifyGiven {
3074                    name: "x".to_string(),
3075                    type_name: "Int".to_string(),
3076                    domain: VerifyGivenDomain::Explicit(vec![sb(Expr::Literal(Literal::Int(2)))]),
3077                }],
3078                when: None,
3079                lhs: sb(Expr::Ident("x".to_string())),
3080                rhs: sb(Expr::Ident("x".to_string())),
3081                sample_guards: vec![],
3082            })),
3083            trace: false,
3084            cases_givens: vec![],
3085        }));
3086        let out = transpile_with_verify_mode(&ctx, VerifyEmitMode::TheoremSkeleton);
3087        let lean = out
3088            .files
3089            .iter()
3090            .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
3091            .expect("expected generated Lean file");
3092        assert!(lean.contains("theorem f_verify_1 : 1 = 1 := by"));
3093        assert!(lean.contains("theorem f_law_identity : ∀ (x : Int), x = x := by"));
3094        assert!(lean.contains("theorem f_law_identity_sample_1 : 2 = 2 := by"));
3095        assert!(!lean.contains("theorem f_law_identity_sample_2 : 2 = 2 := by"));
3096    }
3097
3098    #[test]
3099    fn proof_mode_accepts_single_int_countdown_recursion() {
3100        let mut ctx = empty_ctx();
3101        let down = FnDef {
3102            name: "down".to_string(),
3103            line: 1,
3104            params: vec![("n".to_string(), "Int".to_string())],
3105            return_type: "Int".to_string(),
3106            effects: vec![],
3107            desc: None,
3108            body: Rc::new(FnBody::from_expr(sb(Expr::Match {
3109                subject: sbb(Expr::Ident("n".to_string())),
3110                arms: vec![
3111                    MatchArm {
3112                        pattern: Pattern::Literal(Literal::Int(0)),
3113                        body: sbb(Expr::Literal(Literal::Int(0))),
3114                    },
3115                    MatchArm {
3116                        pattern: Pattern::Wildcard,
3117                        body: sbb(Expr::TailCall(Box::new(TailCallData::new(
3118                            "down".to_string(),
3119                            vec![sb(Expr::BinOp(
3120                                BinOp::Sub,
3121                                sbb(Expr::Ident("n".to_string())),
3122                                sbb(Expr::Literal(Literal::Int(1))),
3123                            ))],
3124                        )))),
3125                    },
3126                ],
3127            }))),
3128            resolution: None,
3129        };
3130        ctx.items.push(TopLevel::FnDef(down.clone()));
3131        ctx.fn_defs.push(down);
3132
3133        let issues = proof_mode_issues(&ctx);
3134        assert!(
3135            issues.is_empty(),
3136            "expected Int countdown recursion to be accepted, got: {:?}",
3137            issues
3138        );
3139
3140        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
3141        let lean = out
3142            .files
3143            .iter()
3144            .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
3145            .expect("expected generated Lean file");
3146        assert!(lean.contains("def down__fuel"));
3147        assert!(lean.contains("def down (n : Int) : Int :="));
3148        assert!(lean.contains("down__fuel ((Int.natAbs n) + 1) n"));
3149    }
3150
3151    #[test]
3152    fn proof_mode_accepts_single_int_countdown_on_nonfirst_param() {
3153        let mut ctx = empty_ctx();
3154        let repeat_like = FnDef {
3155            name: "repeatLike".to_string(),
3156            line: 1,
3157            params: vec![
3158                ("char".to_string(), "String".to_string()),
3159                ("n".to_string(), "Int".to_string()),
3160            ],
3161            return_type: "List<String>".to_string(),
3162            effects: vec![],
3163            desc: None,
3164            body: Rc::new(FnBody::from_expr(sb(Expr::Match {
3165                subject: sbb(Expr::BinOp(
3166                    BinOp::Lte,
3167                    sbb(Expr::Ident("n".to_string())),
3168                    sbb(Expr::Literal(Literal::Int(0))),
3169                )),
3170                arms: vec![
3171                    MatchArm {
3172                        pattern: Pattern::Literal(Literal::Bool(true)),
3173                        body: sbb(Expr::List(vec![])),
3174                    },
3175                    MatchArm {
3176                        pattern: Pattern::Literal(Literal::Bool(false)),
3177                        body: sbb(Expr::TailCall(Box::new(TailCallData::new(
3178                            "repeatLike".to_string(),
3179                            vec![
3180                                sb(Expr::Ident("char".to_string())),
3181                                sb(Expr::BinOp(
3182                                    BinOp::Sub,
3183                                    sbb(Expr::Ident("n".to_string())),
3184                                    sbb(Expr::Literal(Literal::Int(1))),
3185                                )),
3186                            ],
3187                        )))),
3188                    },
3189                ],
3190            }))),
3191            resolution: None,
3192        };
3193        ctx.items.push(TopLevel::FnDef(repeat_like.clone()));
3194        ctx.fn_defs.push(repeat_like);
3195
3196        let issues = proof_mode_issues(&ctx);
3197        assert!(
3198            issues.is_empty(),
3199            "expected non-first Int countdown recursion to be accepted, got: {:?}",
3200            issues
3201        );
3202
3203        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
3204        let lean = out
3205            .files
3206            .iter()
3207            .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
3208            .expect("expected generated Lean file");
3209        assert!(lean.contains("def repeatLike__fuel"));
3210        assert!(lean.contains("def repeatLike (char : String) (n : Int) : List String :="));
3211        assert!(lean.contains("repeatLike__fuel ((Int.natAbs n) + 1) char n"));
3212    }
3213
3214    #[test]
3215    fn proof_mode_accepts_negative_guarded_int_ascent() {
3216        let mut ctx = empty_ctx();
3217        let normalize = FnDef {
3218            name: "normalize".to_string(),
3219            line: 1,
3220            params: vec![("angle".to_string(), "Int".to_string())],
3221            return_type: "Int".to_string(),
3222            effects: vec![],
3223            desc: None,
3224            body: Rc::new(FnBody::from_expr(sb(Expr::Match {
3225                subject: sbb(Expr::BinOp(
3226                    BinOp::Lt,
3227                    sbb(Expr::Ident("angle".to_string())),
3228                    sbb(Expr::Literal(Literal::Int(0))),
3229                )),
3230                arms: vec![
3231                    MatchArm {
3232                        pattern: Pattern::Literal(Literal::Bool(true)),
3233                        body: sbb(Expr::TailCall(Box::new(TailCallData::new(
3234                            "normalize".to_string(),
3235                            vec![sb(Expr::BinOp(
3236                                BinOp::Add,
3237                                sbb(Expr::Ident("angle".to_string())),
3238                                sbb(Expr::Literal(Literal::Int(360))),
3239                            ))],
3240                        )))),
3241                    },
3242                    MatchArm {
3243                        pattern: Pattern::Literal(Literal::Bool(false)),
3244                        body: sbb(Expr::Ident("angle".to_string())),
3245                    },
3246                ],
3247            }))),
3248            resolution: None,
3249        };
3250        ctx.items.push(TopLevel::FnDef(normalize.clone()));
3251        ctx.fn_defs.push(normalize);
3252
3253        let issues = proof_mode_issues(&ctx);
3254        assert!(
3255            issues.is_empty(),
3256            "expected negative-guarded Int ascent recursion to be accepted, got: {:?}",
3257            issues
3258        );
3259
3260        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
3261        let lean = out
3262            .files
3263            .iter()
3264            .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
3265            .expect("expected generated Lean file");
3266        assert!(lean.contains("def normalize__fuel"));
3267        assert!(lean.contains("normalize__fuel ((Int.natAbs angle) + 1) angle"));
3268    }
3269
3270    #[test]
3271    fn proof_mode_accepts_single_list_structural_recursion() {
3272        let mut ctx = empty_ctx();
3273        let len = FnDef {
3274            name: "len".to_string(),
3275            line: 1,
3276            params: vec![("xs".to_string(), "List<Int>".to_string())],
3277            return_type: "Int".to_string(),
3278            effects: vec![],
3279            desc: None,
3280            body: Rc::new(FnBody::from_expr(sb(Expr::Match {
3281                subject: sbb(Expr::Ident("xs".to_string())),
3282                arms: vec![
3283                    MatchArm {
3284                        pattern: Pattern::EmptyList,
3285                        body: sbb(Expr::Literal(Literal::Int(0))),
3286                    },
3287                    MatchArm {
3288                        pattern: Pattern::Cons("h".to_string(), "t".to_string()),
3289                        body: sbb(Expr::TailCall(Box::new(TailCallData::new(
3290                            "len".to_string(),
3291                            vec![sb(Expr::Ident("t".to_string()))],
3292                        )))),
3293                    },
3294                ],
3295            }))),
3296            resolution: None,
3297        };
3298        ctx.items.push(TopLevel::FnDef(len.clone()));
3299        ctx.fn_defs.push(len);
3300
3301        let issues = proof_mode_issues(&ctx);
3302        assert!(
3303            issues.is_empty(),
3304            "expected List structural recursion to be accepted, got: {:?}",
3305            issues
3306        );
3307    }
3308
3309    #[test]
3310    fn proof_mode_accepts_single_list_structural_recursion_on_nonfirst_param() {
3311        let mut ctx = empty_ctx();
3312        let len_from = FnDef {
3313            name: "lenFrom".to_string(),
3314            line: 1,
3315            params: vec![
3316                ("count".to_string(), "Int".to_string()),
3317                ("xs".to_string(), "List<Int>".to_string()),
3318            ],
3319            return_type: "Int".to_string(),
3320            effects: vec![],
3321            desc: None,
3322            body: Rc::new(FnBody::from_expr(sb(Expr::Match {
3323                subject: sbb(Expr::Ident("xs".to_string())),
3324                arms: vec![
3325                    MatchArm {
3326                        pattern: Pattern::EmptyList,
3327                        body: sbb(Expr::Ident("count".to_string())),
3328                    },
3329                    MatchArm {
3330                        pattern: Pattern::Cons("h".to_string(), "t".to_string()),
3331                        body: sbb(Expr::TailCall(Box::new(TailCallData::new(
3332                            "lenFrom".to_string(),
3333                            vec![
3334                                sb(Expr::BinOp(
3335                                    BinOp::Add,
3336                                    sbb(Expr::Ident("count".to_string())),
3337                                    sbb(Expr::Literal(Literal::Int(1))),
3338                                )),
3339                                sb(Expr::Ident("t".to_string())),
3340                            ],
3341                        )))),
3342                    },
3343                ],
3344            }))),
3345            resolution: None,
3346        };
3347        ctx.items.push(TopLevel::FnDef(len_from.clone()));
3348        ctx.fn_defs.push(len_from);
3349
3350        let issues = proof_mode_issues(&ctx);
3351        assert!(
3352            issues.is_empty(),
3353            "expected non-first List structural recursion to be accepted, got: {:?}",
3354            issues
3355        );
3356
3357        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
3358        let lean = generated_lean_file(&out);
3359        assert!(lean.contains("termination_by xs.length"));
3360        assert!(!lean.contains("partial def lenFrom"));
3361    }
3362
3363    #[test]
3364    fn proof_mode_accepts_single_string_pos_advance_recursion() {
3365        let mut ctx = empty_ctx();
3366        let skip_ws = FnDef {
3367            name: "skipWs".to_string(),
3368            line: 1,
3369            params: vec![
3370                ("s".to_string(), "String".to_string()),
3371                ("pos".to_string(), "Int".to_string()),
3372            ],
3373            return_type: "Int".to_string(),
3374            effects: vec![],
3375            desc: None,
3376            body: Rc::new(FnBody::from_expr(sb(Expr::Match {
3377                subject: sbb(Expr::FnCall(
3378                    sbb(Expr::Attr(
3379                        sbb(Expr::Ident("String".to_string())),
3380                        "charAt".to_string(),
3381                    )),
3382                    vec![
3383                        sb(Expr::Ident("s".to_string())),
3384                        sb(Expr::Ident("pos".to_string())),
3385                    ],
3386                )),
3387                arms: vec![
3388                    MatchArm {
3389                        pattern: Pattern::Constructor("Option.None".to_string(), vec![]),
3390                        body: sbb(Expr::Ident("pos".to_string())),
3391                    },
3392                    MatchArm {
3393                        pattern: Pattern::Wildcard,
3394                        body: sbb(Expr::TailCall(Box::new(TailCallData::new(
3395                            "skipWs".to_string(),
3396                            vec![
3397                                sb(Expr::Ident("s".to_string())),
3398                                sb(Expr::BinOp(
3399                                    BinOp::Add,
3400                                    sbb(Expr::Ident("pos".to_string())),
3401                                    sbb(Expr::Literal(Literal::Int(1))),
3402                                )),
3403                            ],
3404                        )))),
3405                    },
3406                ],
3407            }))),
3408            resolution: None,
3409        };
3410        ctx.items.push(TopLevel::FnDef(skip_ws.clone()));
3411        ctx.fn_defs.push(skip_ws);
3412
3413        let issues = proof_mode_issues(&ctx);
3414        assert!(
3415            issues.is_empty(),
3416            "expected String+pos recursion to be accepted, got: {:?}",
3417            issues
3418        );
3419
3420        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
3421        let lean = generated_lean_file(&out);
3422        assert!(lean.contains("def skipWs__fuel"));
3423        assert!(!lean.contains("partial def skipWs"));
3424    }
3425
3426    #[test]
3427    fn proof_mode_accepts_mutual_int_countdown_recursion() {
3428        let mut ctx = empty_ctx();
3429        let even = FnDef {
3430            name: "even".to_string(),
3431            line: 1,
3432            params: vec![("n".to_string(), "Int".to_string())],
3433            return_type: "Bool".to_string(),
3434            effects: vec![],
3435            desc: None,
3436            body: Rc::new(FnBody::from_expr(sb(Expr::Match {
3437                subject: sbb(Expr::Ident("n".to_string())),
3438                arms: vec![
3439                    MatchArm {
3440                        pattern: Pattern::Literal(Literal::Int(0)),
3441                        body: sbb(Expr::Literal(Literal::Bool(true))),
3442                    },
3443                    MatchArm {
3444                        pattern: Pattern::Wildcard,
3445                        body: sbb(Expr::TailCall(Box::new(TailCallData::new(
3446                            "odd".to_string(),
3447                            vec![sb(Expr::BinOp(
3448                                BinOp::Sub,
3449                                sbb(Expr::Ident("n".to_string())),
3450                                sbb(Expr::Literal(Literal::Int(1))),
3451                            ))],
3452                        )))),
3453                    },
3454                ],
3455            }))),
3456            resolution: None,
3457        };
3458        let odd = FnDef {
3459            name: "odd".to_string(),
3460            line: 2,
3461            params: vec![("n".to_string(), "Int".to_string())],
3462            return_type: "Bool".to_string(),
3463            effects: vec![],
3464            desc: None,
3465            body: Rc::new(FnBody::from_expr(sb(Expr::Match {
3466                subject: sbb(Expr::Ident("n".to_string())),
3467                arms: vec![
3468                    MatchArm {
3469                        pattern: Pattern::Literal(Literal::Int(0)),
3470                        body: sbb(Expr::Literal(Literal::Bool(false))),
3471                    },
3472                    MatchArm {
3473                        pattern: Pattern::Wildcard,
3474                        body: sbb(Expr::TailCall(Box::new(TailCallData::new(
3475                            "even".to_string(),
3476                            vec![sb(Expr::BinOp(
3477                                BinOp::Sub,
3478                                sbb(Expr::Ident("n".to_string())),
3479                                sbb(Expr::Literal(Literal::Int(1))),
3480                            ))],
3481                        )))),
3482                    },
3483                ],
3484            }))),
3485            resolution: None,
3486        };
3487        ctx.items.push(TopLevel::FnDef(even.clone()));
3488        ctx.items.push(TopLevel::FnDef(odd.clone()));
3489        ctx.fn_defs.push(even);
3490        ctx.fn_defs.push(odd);
3491
3492        let issues = proof_mode_issues(&ctx);
3493        assert!(
3494            issues.is_empty(),
3495            "expected mutual Int countdown recursion to be accepted, got: {:?}",
3496            issues
3497        );
3498
3499        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
3500        let lean = generated_lean_file(&out);
3501        assert!(lean.contains("def even__fuel"));
3502        assert!(lean.contains("def odd__fuel"));
3503        assert!(lean.contains("def even (n : Int) : Bool :="));
3504        assert!(lean.contains("even__fuel ((Int.natAbs n) + 1) n"));
3505    }
3506
3507    #[test]
3508    fn proof_mode_accepts_mutual_string_pos_recursion_with_ranked_same_edges() {
3509        let mut ctx = empty_ctx();
3510        let f = FnDef {
3511            name: "f".to_string(),
3512            line: 1,
3513            params: vec![
3514                ("s".to_string(), "String".to_string()),
3515                ("pos".to_string(), "Int".to_string()),
3516            ],
3517            return_type: "Int".to_string(),
3518            effects: vec![],
3519            desc: None,
3520            body: Rc::new(FnBody::from_expr(sb(Expr::Match {
3521                subject: sbb(Expr::BinOp(
3522                    BinOp::Gte,
3523                    sbb(Expr::Ident("pos".to_string())),
3524                    sbb(Expr::Literal(Literal::Int(3))),
3525                )),
3526                arms: vec![
3527                    MatchArm {
3528                        pattern: Pattern::Literal(Literal::Bool(true)),
3529                        body: sbb(Expr::Ident("pos".to_string())),
3530                    },
3531                    MatchArm {
3532                        pattern: Pattern::Wildcard,
3533                        body: sbb(Expr::TailCall(Box::new(TailCallData::new(
3534                            "g".to_string(),
3535                            vec![
3536                                sb(Expr::Ident("s".to_string())),
3537                                sb(Expr::Ident("pos".to_string())),
3538                            ],
3539                        )))),
3540                    },
3541                ],
3542            }))),
3543            resolution: None,
3544        };
3545        let g = FnDef {
3546            name: "g".to_string(),
3547            line: 2,
3548            params: vec![
3549                ("s".to_string(), "String".to_string()),
3550                ("pos".to_string(), "Int".to_string()),
3551            ],
3552            return_type: "Int".to_string(),
3553            effects: vec![],
3554            desc: None,
3555            body: Rc::new(FnBody::from_expr(sb(Expr::Match {
3556                subject: sbb(Expr::BinOp(
3557                    BinOp::Gte,
3558                    sbb(Expr::Ident("pos".to_string())),
3559                    sbb(Expr::Literal(Literal::Int(3))),
3560                )),
3561                arms: vec![
3562                    MatchArm {
3563                        pattern: Pattern::Literal(Literal::Bool(true)),
3564                        body: sbb(Expr::Ident("pos".to_string())),
3565                    },
3566                    MatchArm {
3567                        pattern: Pattern::Wildcard,
3568                        body: sbb(Expr::TailCall(Box::new(TailCallData::new(
3569                            "f".to_string(),
3570                            vec![
3571                                sb(Expr::Ident("s".to_string())),
3572                                sb(Expr::BinOp(
3573                                    BinOp::Add,
3574                                    sbb(Expr::Ident("pos".to_string())),
3575                                    sbb(Expr::Literal(Literal::Int(1))),
3576                                )),
3577                            ],
3578                        )))),
3579                    },
3580                ],
3581            }))),
3582            resolution: None,
3583        };
3584        ctx.items.push(TopLevel::FnDef(f.clone()));
3585        ctx.items.push(TopLevel::FnDef(g.clone()));
3586        ctx.fn_defs.push(f);
3587        ctx.fn_defs.push(g);
3588
3589        let issues = proof_mode_issues(&ctx);
3590        assert!(
3591            issues.is_empty(),
3592            "expected mutual String+pos recursion to be accepted, got: {:?}",
3593            issues
3594        );
3595
3596        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
3597        let lean = generated_lean_file(&out);
3598        assert!(lean.contains("def f__fuel"));
3599        assert!(lean.contains("def g__fuel"));
3600        assert!(!lean.contains("partial def f"));
3601    }
3602
3603    #[test]
3604    fn proof_mode_accepts_mutual_ranked_sizeof_recursion() {
3605        let mut ctx = empty_ctx();
3606        let f = FnDef {
3607            name: "f".to_string(),
3608            line: 1,
3609            params: vec![("xs".to_string(), "List<Int>".to_string())],
3610            return_type: "Int".to_string(),
3611            effects: vec![],
3612            desc: None,
3613            body: Rc::new(FnBody::from_expr(sb(Expr::TailCall(Box::new(
3614                TailCallData::new(
3615                    "g".to_string(),
3616                    vec![
3617                        sb(Expr::Literal(Literal::Str("acc".to_string()))),
3618                        sb(Expr::Ident("xs".to_string())),
3619                    ],
3620                ),
3621            ))))),
3622            resolution: None,
3623        };
3624        let g = FnDef {
3625            name: "g".to_string(),
3626            line: 2,
3627            params: vec![
3628                ("acc".to_string(), "String".to_string()),
3629                ("xs".to_string(), "List<Int>".to_string()),
3630            ],
3631            return_type: "Int".to_string(),
3632            effects: vec![],
3633            desc: None,
3634            body: Rc::new(FnBody::from_expr(sb(Expr::Match {
3635                subject: sbb(Expr::Ident("xs".to_string())),
3636                arms: vec![
3637                    MatchArm {
3638                        pattern: Pattern::EmptyList,
3639                        body: sbb(Expr::Literal(Literal::Int(0))),
3640                    },
3641                    MatchArm {
3642                        pattern: Pattern::Cons("h".to_string(), "t".to_string()),
3643                        body: sbb(Expr::TailCall(Box::new(TailCallData::new(
3644                            "f".to_string(),
3645                            vec![sb(Expr::Ident("t".to_string()))],
3646                        )))),
3647                    },
3648                ],
3649            }))),
3650            resolution: None,
3651        };
3652        ctx.items.push(TopLevel::FnDef(f.clone()));
3653        ctx.items.push(TopLevel::FnDef(g.clone()));
3654        ctx.fn_defs.push(f);
3655        ctx.fn_defs.push(g);
3656
3657        let issues = proof_mode_issues(&ctx);
3658        assert!(
3659            issues.is_empty(),
3660            "expected mutual ranked-sizeOf recursion to be accepted, got: {:?}",
3661            issues
3662        );
3663
3664        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
3665        let lean = generated_lean_file(&out);
3666        assert!(lean.contains("mutual"));
3667        assert!(lean.contains("def f__fuel"));
3668        assert!(lean.contains("def g__fuel"));
3669        assert!(!lean.contains("partial def f"));
3670        assert!(!lean.contains("partial def g"));
3671    }
3672
3673    #[test]
3674    fn proof_mode_rejects_recursive_pure_functions() {
3675        let mut ctx = empty_ctx();
3676        let recursive_fn = FnDef {
3677            name: "loop".to_string(),
3678            line: 1,
3679            params: vec![("n".to_string(), "Int".to_string())],
3680            return_type: "Int".to_string(),
3681            effects: vec![],
3682            desc: None,
3683            body: Rc::new(FnBody::from_expr(sb(Expr::FnCall(
3684                sbb(Expr::Ident("loop".to_string())),
3685                vec![sb(Expr::Ident("n".to_string()))],
3686            )))),
3687            resolution: None,
3688        };
3689        ctx.items.push(TopLevel::FnDef(recursive_fn.clone()));
3690        ctx.fn_defs.push(recursive_fn);
3691
3692        let issues = proof_mode_issues(&ctx);
3693        assert!(
3694            issues.iter().any(|i| i.contains("outside proof subset")),
3695            "expected recursive function blocker, got: {:?}",
3696            issues
3697        );
3698    }
3699
3700    #[test]
3701    fn proof_mode_allows_recursive_types() {
3702        let mut ctx = empty_ctx();
3703        let recursive_type = TypeDef::Sum {
3704            name: "Node".to_string(),
3705            variants: vec![TypeVariant {
3706                name: "Cons".to_string(),
3707                fields: vec!["Node".to_string()],
3708            }],
3709            line: 1,
3710        };
3711        ctx.items.push(TopLevel::TypeDef(recursive_type.clone()));
3712        ctx.type_defs.push(recursive_type);
3713
3714        let issues = proof_mode_issues(&ctx);
3715        assert!(
3716            issues
3717                .iter()
3718                .all(|i| !i.contains("recursive types require unsafe DecidableEq shim")),
3719            "did not expect recursive type blocker, got: {:?}",
3720            issues
3721        );
3722    }
3723
3724    #[test]
3725    fn law_auto_example_exports_real_proof_artifacts() {
3726        let ctx = ctx_from_source(
3727            include_str!("../../../examples/formal/law_auto.av"),
3728            "law_auto",
3729        );
3730        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
3731        let lean = generated_lean_file(&out);
3732
3733        assert!(lean.contains("theorem add_law_commutative :"));
3734        assert!(lean.contains("theorem id'_law_reflexive : ∀ (x : Int), x = x := by"));
3735        assert!(lean.contains("theorem incCount_law_keyPresent :"));
3736        assert!(lean.contains("AverMap.has_set_self"));
3737        assert!(lean.contains("theorem add_law_commutative_sample_1 :"));
3738        assert!(lean.contains(":= by native_decide"));
3739    }
3740
3741    #[test]
3742    fn json_example_stays_inside_proof_subset() {
3743        let ctx = ctx_from_source(include_str!("../../../examples/data/json.av"), "json");
3744        let issues = proof_mode_issues(&ctx);
3745        assert!(
3746            issues.is_empty(),
3747            "expected json example to stay inside proof subset, got: {:?}",
3748            issues
3749        );
3750    }
3751
3752    #[test]
3753    fn json_example_uses_total_defs_and_domain_guarded_laws_in_proof_mode() {
3754        let ctx = ctx_from_source(include_str!("../../../examples/data/json.av"), "json");
3755        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
3756        let lean = generated_lean_file(&out);
3757
3758        assert!(!lean.contains("partial def"));
3759        assert!(lean.contains("def skipWs__fuel"));
3760        assert!(lean.contains("def parseValue__fuel"));
3761        assert!(lean.contains("def toString' (j : Json) : String :="));
3762        assert!(
3763            lean.contains(
3764                "def averMeasureJsonEntries_String (items : List (String × Json)) : Nat :="
3765            )
3766        );
3767        assert!(lean.contains(
3768            "| .jsonObject x0 => (averMeasureJsonEntries_String (AverMap.entries x0)) + 1"
3769        ));
3770        assert!(lean.contains("-- when jsonRoundtripSafe j"));
3771        assert!(!lean.contains("-- hint: verify law '"));
3772        assert!(!lean.contains("private theorem toString'_law_parseRoundtrip_aux"));
3773        assert!(
3774            lean.contains(
3775                "theorem toString'_law_parseRoundtrip : ∀ (j : Json), j = Json.jsonNull ∨"
3776            )
3777        );
3778        assert!(lean.contains(
3779            "jsonRoundtripSafe j = true -> fromString (toString' j) = Except.ok j := by"
3780        ));
3781        assert!(
3782            lean.contains("theorem finishFloat_law_fromCanonicalFloat : ∀ (f : Float), f = 3.5 ∨")
3783        );
3784        assert!(lean.contains("theorem finishInt_law_fromCanonicalInt_checked_domain :"));
3785        assert!(lean.contains(
3786            "theorem toString'_law_parseValueRoundtrip : ∀ (j : Json), j = Json.jsonNull ∨"
3787        ));
3788        assert!(lean.contains("theorem toString'_law_parseRoundtrip_sample_1 :"));
3789        assert!(lean.contains(
3790            "example : fromString \"null\" = Except.ok Json.jsonNull := by native_decide"
3791        ));
3792    }
3793
3794    #[test]
3795    fn transpile_injects_builtin_network_types_and_vector_get_support() {
3796        let ctx = ctx_from_source(
3797            r#"
3798fn firstOrMissing(xs: Vector<String>) -> Result<String, String>
3799    Option.toResult(Vector.get(xs, 0), "missing")
3800
3801fn defaultHeader() -> Header
3802    Header(name = "Content-Type", value = "application/json")
3803
3804fn mkResponse(body: String) -> HttpResponse
3805    HttpResponse(status = 200, body = body, headers = [defaultHeader()])
3806
3807fn requestPath(req: HttpRequest) -> String
3808    req.path
3809
3810fn connPort(conn: Tcp.Connection) -> Int
3811    conn.port
3812"#,
3813            "network_helpers",
3814        );
3815        let out = transpile(&ctx);
3816        let lean = generated_lean_file(&out);
3817
3818        assert!(lean.contains("structure Header where"));
3819        assert!(lean.contains("structure HttpResponse where"));
3820        assert!(lean.contains("structure HttpRequest where"));
3821        assert!(lean.contains("structure Tcp_Connection where"));
3822        assert!(lean.contains("port : Int"));
3823    }
3824
3825    #[test]
3826    fn law_auto_example_has_no_sorry_in_proof_mode() {
3827        let ctx = ctx_from_source(
3828            include_str!("../../../examples/formal/law_auto.av"),
3829            "law_auto",
3830        );
3831        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
3832        let lean = generated_lean_file(&out);
3833        assert!(
3834            !lean.contains("sorry"),
3835            "expected law_auto proof export to avoid sorry, got:\n{}",
3836            lean
3837        );
3838    }
3839
3840    #[test]
3841    fn map_example_has_no_sorry_in_proof_mode() {
3842        let ctx = ctx_from_source(include_str!("../../../examples/data/map.av"), "map");
3843        let issues = proof_mode_issues(&ctx);
3844        assert!(
3845            issues.is_empty(),
3846            "expected map example to stay inside proof subset, got: {:?}",
3847            issues
3848        );
3849
3850        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
3851        let lean = generated_lean_file(&out);
3852        // After codegen change: universal theorems that can't be auto-proved get sorry
3853        assert!(lean.contains("theorem incCount_law_trackedCountStepsByOne :"));
3854        assert!(lean.contains("sorry"));
3855        // Universal theorems that can't be auto-proved now get sorry instead of being omitted
3856        assert!(lean.contains("theorem countWords_law_presenceMatchesContains_sample_1 :"));
3857        assert!(lean.contains("theorem countWords_law_trackedWordCount_sample_1 :"));
3858        assert!(lean.contains("AverMap.has_set_self"));
3859        assert!(lean.contains("AverMap.get_set_self"));
3860    }
3861
3862    #[test]
3863    fn spec_laws_example_has_no_sorry_in_proof_mode() {
3864        let ctx = ctx_from_source(
3865            include_str!("../../../examples/formal/spec_laws.av"),
3866            "spec_laws",
3867        );
3868        let issues = proof_mode_issues(&ctx);
3869        assert!(
3870            issues.is_empty(),
3871            "expected spec_laws example to stay inside proof subset, got: {:?}",
3872            issues
3873        );
3874
3875        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
3876        let lean = generated_lean_file(&out);
3877        assert!(
3878            !lean.contains("sorry"),
3879            "expected spec_laws proof export to avoid sorry, got:\n{}",
3880            lean
3881        );
3882        assert!(lean.contains("theorem absVal_eq_absValSpec :"));
3883        assert!(lean.contains("theorem clampNonNegative_eq_clampNonNegativeSpec :"));
3884    }
3885
3886    #[test]
3887    fn rle_example_exports_sampled_roundtrip_laws_without_sorry() {
3888        let ctx = ctx_from_source(include_str!("../../../examples/data/rle.av"), "rle");
3889        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
3890        let lean = generated_lean_file(&out);
3891
3892        assert!(
3893            lean.contains("sorry"),
3894            "expected rle proof export to contain sorry for unproved universal theorems"
3895        );
3896        assert!(lean.contains(
3897            "theorem encode_law_roundtrip_sample_1 : decode (encode []) = [] := by native_decide"
3898        ));
3899        assert!(lean.contains(
3900            "theorem encodeString_law_string_roundtrip_sample_1 : decodeString (encodeString \"\") = \"\" := by native_decide"
3901        ));
3902    }
3903
3904    #[test]
3905    fn fibonacci_example_uses_fuelized_int_countdown_in_proof_mode() {
3906        let ctx = ctx_from_source(
3907            include_str!("../../../examples/data/fibonacci.av"),
3908            "fibonacci",
3909        );
3910        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
3911        let lean = generated_lean_file(&out);
3912
3913        assert!(lean.contains("def fibTR__fuel"));
3914        assert!(lean.contains("def fibTR (n : Int) (a : Int) (b : Int) : Int :="));
3915        assert!(lean.contains("fibTR__fuel ((Int.natAbs n) + 1) n a b"));
3916        assert!(!lean.contains("partial def fibTR"));
3917    }
3918
3919    #[test]
3920    fn fibonacci_example_stays_inside_proof_subset() {
3921        let ctx = ctx_from_source(
3922            include_str!("../../../examples/data/fibonacci.av"),
3923            "fibonacci",
3924        );
3925        let issues = proof_mode_issues(&ctx);
3926        assert!(
3927            issues.is_empty(),
3928            "expected fibonacci example to stay inside proof subset, got: {:?}",
3929            issues
3930        );
3931    }
3932
3933    #[test]
3934    fn fibonacci_example_matches_general_linear_recurrence_shapes() {
3935        let ctx = ctx_from_source(
3936            include_str!("../../../examples/data/fibonacci.av"),
3937            "fibonacci",
3938        );
3939        let fib = ctx.fn_defs.iter().find(|fd| fd.name == "fib").unwrap();
3940        let fib_tr = ctx.fn_defs.iter().find(|fd| fd.name == "fibTR").unwrap();
3941        let fib_spec = ctx.fn_defs.iter().find(|fd| fd.name == "fibSpec").unwrap();
3942
3943        assert!(recurrence::detect_tailrec_int_linear_pair_wrapper(fib).is_some());
3944        assert!(recurrence::detect_tailrec_int_linear_pair_worker(fib_tr).is_some());
3945        assert!(recurrence::detect_second_order_int_linear_recurrence(fib_spec).is_some());
3946    }
3947
3948    #[test]
3949    fn fibonacci_example_auto_proves_general_linear_recurrence_spec_law() {
3950        let ctx = ctx_from_source(
3951            include_str!("../../../examples/data/fibonacci.av"),
3952            "fibonacci",
3953        );
3954        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
3955        let lean = generated_lean_file(&out);
3956
3957        assert!(lean.contains("private def fibSpec__nat : Nat -> Int"));
3958        assert!(!lean.contains("partial def fibSpec"));
3959        assert!(lean.contains("private theorem fib_eq_fibSpec__worker_nat_shift"));
3960        assert!(lean.contains("private theorem fib_eq_fibSpec__helper_nat"));
3961        assert!(lean.contains("private theorem fib_eq_fibSpec__helper_seed"));
3962        assert!(lean.contains("theorem fib_eq_fibSpec : ∀ (n : Int), fib n = fibSpec n := by"));
3963        assert!(!lean.contains(
3964            "-- universal theorem fib_eq_fibSpec omitted: sampled law shape is not auto-proved yet"
3965        ));
3966    }
3967
3968    #[test]
3969    fn pell_like_example_auto_proves_same_general_shape() {
3970        let ctx = ctx_from_source(
3971            r#"
3972module Pell
3973    intent =
3974        "linear recurrence probe"
3975
3976fn pellTR(n: Int, a: Int, b: Int) -> Int
3977    match n
3978        0 -> a
3979        _ -> pellTR(n - 1, b, a + 2 * b)
3980
3981fn pell(n: Int) -> Int
3982    match n < 0
3983        true -> 0
3984        false -> pellTR(n, 0, 1)
3985
3986fn pellSpec(n: Int) -> Int
3987    match n < 0
3988        true -> 0
3989        false -> match n
3990            0 -> 0
3991            1 -> 1
3992            _ -> pellSpec(n - 2) + 2 * pellSpec(n - 1)
3993
3994verify pell law pellSpec
3995    given n: Int = [0, 1, 2, 3]
3996    pell(n) => pellSpec(n)
3997"#,
3998            "pell",
3999        );
4000        let issues = proof_mode_issues(&ctx);
4001        assert!(
4002            issues.is_empty(),
4003            "expected pell example to stay inside proof subset, got: {:?}",
4004            issues
4005        );
4006
4007        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
4008        let lean = generated_lean_file(&out);
4009        assert!(lean.contains("private def pellSpec__nat : Nat -> Int"));
4010        assert!(lean.contains("private theorem pell_eq_pellSpec__worker_nat_shift"));
4011        assert!(lean.contains("theorem pell_eq_pellSpec : ∀ (n : Int), pell n = pellSpec n := by"));
4012        assert!(!lean.contains(
4013            "-- universal theorem pell_eq_pellSpec omitted: sampled law shape is not auto-proved yet"
4014        ));
4015    }
4016
4017    #[test]
4018    fn nonlinear_pair_state_recurrence_is_not_auto_proved_as_linear_shape() {
4019        let ctx = ctx_from_source(
4020            r#"
4021module WeirdRec
4022    intent =
4023        "reject nonlinear pair-state recurrence from linear recurrence prover"
4024
4025fn weirdTR(n: Int, a: Int, b: Int) -> Int
4026    match n
4027        0 -> a
4028        _ -> weirdTR(n - 1, b, a * b)
4029
4030fn weird(n: Int) -> Int
4031    match n < 0
4032        true -> 0
4033        false -> weirdTR(n, 0, 1)
4034
4035fn weirdSpec(n: Int) -> Int
4036    match n < 0
4037        true -> 0
4038        false -> match n
4039            0 -> 0
4040            1 -> 1
4041            _ -> weirdSpec(n - 1) * weirdSpec(n - 2)
4042
4043verify weird law weirdSpec
4044    given n: Int = [0, 1, 2, 3]
4045    weird(n) => weirdSpec(n)
4046"#,
4047            "weirdrec",
4048        );
4049        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
4050        let lean = generated_lean_file(&out);
4051
4052        // After codegen change: emit sorry instead of omitting universal theorems
4053        assert!(lean.contains("sorry"));
4054        assert!(!lean.contains("private theorem weird_eq_weirdSpec__worker_nat_shift"));
4055        assert!(lean.contains("theorem weird_eq_weirdSpec_sample_1 :"));
4056    }
4057
4058    #[test]
4059    fn date_example_stays_inside_proof_subset() {
4060        let ctx = ctx_from_source(include_str!("../../../examples/data/date.av"), "date");
4061        let issues = proof_mode_issues(&ctx);
4062        assert!(
4063            issues.is_empty(),
4064            "expected date example to stay inside proof subset, got: {:?}",
4065            issues
4066        );
4067
4068        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
4069        let lean = generated_lean_file(&out);
4070        assert!(!lean.contains("partial def"));
4071        assert!(lean.contains("def parseIntSlice (s : String) (from' : Int) (to : Int) : Int :="));
4072    }
4073
4074    #[test]
4075    fn temperature_example_stays_inside_proof_subset() {
4076        let ctx = ctx_from_source(
4077            include_str!("../../../examples/core/temperature.av"),
4078            "temperature",
4079        );
4080        let issues = proof_mode_issues(&ctx);
4081        assert!(
4082            issues.is_empty(),
4083            "expected temperature example to stay inside proof subset, got: {:?}",
4084            issues
4085        );
4086
4087        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
4088        let lean = generated_lean_file(&out);
4089        assert!(!lean.contains("partial def"));
4090        assert!(
4091            lean.contains("example : celsiusToFahr 0.0 = 32.0 := by native_decide"),
4092            "expected verify examples to survive proof export, got:\n{}",
4093            lean
4094        );
4095    }
4096
4097    #[test]
4098    fn quicksort_example_stays_inside_proof_subset() {
4099        let ctx = ctx_from_source(
4100            include_str!("../../../examples/data/quicksort.av"),
4101            "quicksort",
4102        );
4103        let issues = proof_mode_issues(&ctx);
4104        assert!(
4105            issues.is_empty(),
4106            "expected quicksort example to stay inside proof subset, got: {:?}",
4107            issues
4108        );
4109
4110        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
4111        let lean = generated_lean_file(&out);
4112        assert!(lean.contains("def isOrderedFrom"));
4113        assert!(!lean.contains("partial def isOrderedFrom"));
4114        assert!(lean.contains("termination_by xs.length"));
4115    }
4116
4117    #[test]
4118    fn grok_s_language_example_uses_total_ranked_sizeof_mutual_recursion() {
4119        let ctx = ctx_from_source(
4120            include_str!("../../../examples/core/grok_s_language.av"),
4121            "grok_s_language",
4122        );
4123        let issues = proof_mode_issues(&ctx);
4124        assert!(
4125            issues.is_empty(),
4126            "expected grok_s_language example to stay inside proof subset, got: {:?}",
4127            issues
4128        );
4129
4130        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
4131        let lean = generated_lean_file(&out);
4132        assert!(lean.contains("mutual"));
4133        assert!(lean.contains("def eval__fuel"));
4134        assert!(lean.contains("def parseListItems__fuel"));
4135        assert!(!lean.contains("partial def eval"));
4136        assert!(!lean.contains("termination_by (sizeOf e,"));
4137        assert!(lean.contains("-- when validSymbolNames e"));
4138        assert!(!lean.contains("private theorem toString'_law_parseRoundtrip_aux"));
4139        assert!(lean.contains(
4140            "theorem toString'_law_parseRoundtrip : ∀ (e : Sexpr), e = Sexpr.atomNum 42 ∨"
4141        ));
4142        assert!(
4143            lean.contains("validSymbolNames e = true -> parse (toString' e) = Except.ok e := by")
4144        );
4145        assert!(lean.contains("theorem toString'_law_parseSexprRoundtrip :"));
4146        assert!(lean.contains("theorem toString'_law_parseRoundtrip_sample_1 :"));
4147    }
4148
4149    #[test]
4150    fn lambda_example_keeps_only_eval_outside_proof_subset() {
4151        let ctx = ctx_from_source(include_str!("../../../examples/core/lambda.av"), "lambda");
4152        let issues = proof_mode_issues(&ctx);
4153        assert_eq!(
4154            issues,
4155            vec!["recursive function 'eval' is outside proof subset (currently supported: Int countdown, second-order affine Int recurrences with pair-state worker, structural recursion on List/recursive ADTs, String+position, mutual Int countdown, mutual String+position, and ranked sizeOf recursion)".to_string()]
4156        );
4157
4158        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
4159        let lean = generated_lean_file(&out);
4160        assert!(lean.contains("def termToString__fuel"));
4161        assert!(lean.contains("def subst__fuel"));
4162        assert!(lean.contains("def countS__fuel"));
4163        assert!(!lean.contains("partial def termToString"));
4164        assert!(!lean.contains("partial def subst"));
4165        assert!(!lean.contains("partial def countS"));
4166        assert!(lean.contains("partial def eval"));
4167    }
4168
4169    #[test]
4170    fn mission_control_example_stays_inside_proof_subset() {
4171        let ctx = ctx_from_source(
4172            include_str!("../../../examples/apps/mission_control.av"),
4173            "mission_control",
4174        );
4175        let issues = proof_mode_issues(&ctx);
4176        assert!(
4177            issues.is_empty(),
4178            "expected mission_control example to stay inside proof subset, got: {:?}",
4179            issues
4180        );
4181
4182        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
4183        let lean = generated_lean_file(&out);
4184        assert!(!lean.contains("partial def normalizeAngle"));
4185        assert!(lean.contains("def normalizeAngle__fuel"));
4186    }
4187
4188    #[test]
4189    fn notepad_store_example_stays_inside_proof_subset() {
4190        let ctx = ctx_from_source(
4191            include_str!("../../../examples/apps/notepad/store.av"),
4192            "notepad_store",
4193        );
4194        let issues = proof_mode_issues(&ctx);
4195        assert!(
4196            issues.is_empty(),
4197            "expected notepad/store example to stay inside proof subset, got: {:?}",
4198            issues
4199        );
4200
4201        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
4202        let lean = generated_lean_file(&out);
4203        assert!(lean.contains("def deserializeLine (line : String) : Except String Note :="));
4204        assert!(lean.contains("Except String (List Note)"));
4205        assert!(!lean.contains("partial def deserializeLine"));
4206        assert!(lean.contains("-- when noteRoundtripSafe note"));
4207        assert!(lean.contains("-- when notesRoundtripSafe notes"));
4208        assert!(lean.contains(
4209            "theorem serializeLine_law_lineRoundtrip : ∀ (note : Note), note = { id' := 1, title := \"Hello\", body := \"World\" : Note } ∨"
4210        ));
4211        assert!(lean.contains(
4212            "theorem serializeLines_law_notesRoundtrip : ∀ (notes : List Note), notes = [] ∨"
4213        ));
4214        assert!(lean.contains("notesRoundtripSafe notes = true ->"));
4215        assert!(lean.contains("parseNotes (s!\"{String.intercalate \"\\n\" (serializeLines notes)}\\n\") = Except.ok notes"));
4216        assert!(lean.contains("theorem serializeLine_law_lineRoundtrip_sample_1 :"));
4217        assert!(lean.contains("theorem serializeLines_law_notesRoundtrip_sample_1 :"));
4218    }
4219}