Skip to main content

aver/codegen/lean/
mod.rs

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