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        }
2237    }
2238
2239    fn ctx_from_source(source: &str, project_name: &str) -> CodegenContext {
2240        let mut items = parse_source(source).expect("source should parse");
2241        tco::transform_program(&mut items);
2242        let tc = run_type_check_full(&items, None);
2243        assert!(
2244            tc.errors.is_empty(),
2245            "source should typecheck without errors: {:?}",
2246            tc.errors
2247        );
2248        build_context(items, &tc, HashSet::new(), project_name.to_string(), vec![])
2249    }
2250
2251    fn generated_lean_file(out: &crate::codegen::ProjectOutput) -> &str {
2252        out.files
2253            .iter()
2254            .find_map(|(name, content)| {
2255                (name.ends_with(".lean") && name != "lakefile.lean").then_some(content.as_str())
2256            })
2257            .expect("expected generated Lean file")
2258    }
2259
2260    fn empty_ctx_with_verify_case() -> CodegenContext {
2261        let mut ctx = empty_ctx();
2262        ctx.items.push(TopLevel::Verify(VerifyBlock {
2263            fn_name: "f".to_string(),
2264            line: 1,
2265            cases: vec![(
2266                Expr::Literal(Literal::Int(1)),
2267                Expr::Literal(Literal::Int(1)),
2268            )],
2269            kind: VerifyKind::Cases,
2270        }));
2271        ctx
2272    }
2273
2274    fn empty_ctx_with_two_verify_blocks_same_fn() -> CodegenContext {
2275        let mut ctx = empty_ctx();
2276        ctx.items.push(TopLevel::Verify(VerifyBlock {
2277            fn_name: "f".to_string(),
2278            line: 1,
2279            cases: vec![(
2280                Expr::Literal(Literal::Int(1)),
2281                Expr::Literal(Literal::Int(1)),
2282            )],
2283            kind: VerifyKind::Cases,
2284        }));
2285        ctx.items.push(TopLevel::Verify(VerifyBlock {
2286            fn_name: "f".to_string(),
2287            line: 2,
2288            cases: vec![(
2289                Expr::Literal(Literal::Int(2)),
2290                Expr::Literal(Literal::Int(2)),
2291            )],
2292            kind: VerifyKind::Cases,
2293        }));
2294        ctx
2295    }
2296
2297    fn empty_ctx_with_verify_law() -> CodegenContext {
2298        let mut ctx = empty_ctx();
2299        let add = FnDef {
2300            name: "add".to_string(),
2301            line: 1,
2302            params: vec![
2303                ("a".to_string(), "Int".to_string()),
2304                ("b".to_string(), "Int".to_string()),
2305            ],
2306            return_type: "Int".to_string(),
2307            effects: vec![],
2308            desc: None,
2309            body: Rc::new(FnBody::from_expr(Expr::BinOp(
2310                BinOp::Add,
2311                Box::new(Expr::Ident("a".to_string())),
2312                Box::new(Expr::Ident("b".to_string())),
2313            ))),
2314            resolution: None,
2315        };
2316        ctx.fn_defs.push(add.clone());
2317        ctx.items.push(TopLevel::FnDef(add));
2318        ctx.items.push(TopLevel::Verify(VerifyBlock {
2319            fn_name: "add".to_string(),
2320            line: 1,
2321            cases: vec![
2322                (
2323                    Expr::FnCall(
2324                        Box::new(Expr::Ident("add".to_string())),
2325                        vec![
2326                            Expr::Literal(Literal::Int(1)),
2327                            Expr::Literal(Literal::Int(2)),
2328                        ],
2329                    ),
2330                    Expr::FnCall(
2331                        Box::new(Expr::Ident("add".to_string())),
2332                        vec![
2333                            Expr::Literal(Literal::Int(2)),
2334                            Expr::Literal(Literal::Int(1)),
2335                        ],
2336                    ),
2337                ),
2338                (
2339                    Expr::FnCall(
2340                        Box::new(Expr::Ident("add".to_string())),
2341                        vec![
2342                            Expr::Literal(Literal::Int(2)),
2343                            Expr::Literal(Literal::Int(3)),
2344                        ],
2345                    ),
2346                    Expr::FnCall(
2347                        Box::new(Expr::Ident("add".to_string())),
2348                        vec![
2349                            Expr::Literal(Literal::Int(3)),
2350                            Expr::Literal(Literal::Int(2)),
2351                        ],
2352                    ),
2353                ),
2354            ],
2355            kind: VerifyKind::Law(Box::new(VerifyLaw {
2356                name: "commutative".to_string(),
2357                givens: vec![
2358                    VerifyGiven {
2359                        name: "a".to_string(),
2360                        type_name: "Int".to_string(),
2361                        domain: VerifyGivenDomain::IntRange { start: 1, end: 2 },
2362                    },
2363                    VerifyGiven {
2364                        name: "b".to_string(),
2365                        type_name: "Int".to_string(),
2366                        domain: VerifyGivenDomain::Explicit(vec![
2367                            Expr::Literal(Literal::Int(2)),
2368                            Expr::Literal(Literal::Int(3)),
2369                        ]),
2370                    },
2371                ],
2372                when: None,
2373                lhs: Expr::FnCall(
2374                    Box::new(Expr::Ident("add".to_string())),
2375                    vec![Expr::Ident("a".to_string()), Expr::Ident("b".to_string())],
2376                ),
2377                rhs: Expr::FnCall(
2378                    Box::new(Expr::Ident("add".to_string())),
2379                    vec![Expr::Ident("b".to_string()), Expr::Ident("a".to_string())],
2380                ),
2381                sample_guards: vec![],
2382            })),
2383        }));
2384        ctx
2385    }
2386
2387    #[test]
2388    fn prelude_normalizes_float_string_format() {
2389        let prelude = generate_prelude();
2390        assert!(
2391            prelude.contains("private def normalizeFloatString (s : String) : String :="),
2392            "missing normalizeFloatString helper in prelude"
2393        );
2394        assert!(
2395            prelude.contains(
2396                "def String.fromFloat (f : Float) : String := normalizeFloatString (toString f)"
2397            ),
2398            "String.fromFloat should normalize Lean float formatting"
2399        );
2400    }
2401
2402    #[test]
2403    fn prelude_validates_char_from_code_unicode_bounds() {
2404        let prelude = generate_prelude();
2405        assert!(
2406            prelude.contains("if n < 0 || n > 1114111 then none"),
2407            "Char.fromCode should reject code points above Unicode max"
2408        );
2409        assert!(
2410            prelude.contains("else if n >= 55296 && n <= 57343 then none"),
2411            "Char.fromCode should reject surrogate code points"
2412        );
2413    }
2414
2415    #[test]
2416    fn prelude_includes_map_set_helper_lemmas() {
2417        let prelude = generate_prelude();
2418        assert!(
2419            prelude.contains("theorem has_set_self [DecidableEq α]"),
2420            "missing AverMap.has_set_self helper theorem"
2421        );
2422        assert!(
2423            prelude.contains("theorem get_set_self [DecidableEq α]"),
2424            "missing AverMap.get_set_self helper theorem"
2425        );
2426    }
2427
2428    #[test]
2429    fn lean_output_without_map_usage_omits_map_prelude() {
2430        let ctx = ctx_from_source(
2431            r#"
2432module NoMap
2433    intent = "Simple pure program without maps."
2434
2435fn addOne(n: Int) -> Int
2436    n + 1
2437
2438verify addOne
2439    addOne(1) => 2
2440"#,
2441            "nomap",
2442        );
2443        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
2444        let lean = generated_lean_file(&out);
2445
2446        assert!(
2447            !lean.contains("namespace AverMap"),
2448            "did not expect AverMap prelude in program without map usage:\n{}",
2449            lean
2450        );
2451    }
2452
2453    #[test]
2454    fn transpile_emits_native_decide_for_verify_by_default() {
2455        let out = transpile(&empty_ctx_with_verify_case());
2456        let lean = out
2457            .files
2458            .iter()
2459            .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
2460            .expect("expected generated Lean file");
2461        assert!(lean.contains("example : 1 = 1 := by native_decide"));
2462    }
2463
2464    #[test]
2465    fn transpile_can_emit_sorry_for_verify_when_requested() {
2466        let out = transpile_with_verify_mode(&empty_ctx_with_verify_case(), VerifyEmitMode::Sorry);
2467        let lean = out
2468            .files
2469            .iter()
2470            .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
2471            .expect("expected generated Lean file");
2472        assert!(lean.contains("example : 1 = 1 := by sorry"));
2473    }
2474
2475    #[test]
2476    fn transpile_can_emit_theorem_skeletons_for_verify() {
2477        let out = transpile_with_verify_mode(
2478            &empty_ctx_with_verify_case(),
2479            VerifyEmitMode::TheoremSkeleton,
2480        );
2481        let lean = out
2482            .files
2483            .iter()
2484            .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
2485            .expect("expected generated Lean file");
2486        assert!(lean.contains("theorem f_verify_1 : 1 = 1 := by"));
2487        assert!(lean.contains("  sorry"));
2488    }
2489
2490    #[test]
2491    fn theorem_skeleton_numbering_is_global_per_function_across_verify_blocks() {
2492        let out = transpile_with_verify_mode(
2493            &empty_ctx_with_two_verify_blocks_same_fn(),
2494            VerifyEmitMode::TheoremSkeleton,
2495        );
2496        let lean = out
2497            .files
2498            .iter()
2499            .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
2500            .expect("expected generated Lean file");
2501        assert!(lean.contains("theorem f_verify_1 : 1 = 1 := by"));
2502        assert!(lean.contains("theorem f_verify_2 : 2 = 2 := by"));
2503    }
2504
2505    #[test]
2506    fn transpile_emits_named_theorems_for_verify_law() {
2507        let out = transpile(&empty_ctx_with_verify_law());
2508        let lean = out
2509            .files
2510            .iter()
2511            .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
2512            .expect("expected generated Lean file");
2513        assert!(lean.contains("-- verify law add.commutative (2 cases)"));
2514        assert!(lean.contains("-- given a: Int = 1..2"));
2515        assert!(lean.contains("-- given b: Int = [2, 3]"));
2516        assert!(lean.contains(
2517            "theorem add_law_commutative : ∀ (a : Int) (b : Int), add a b = add b a := by"
2518        ));
2519        assert!(lean.contains("  intro a b"));
2520        assert!(lean.contains("  simp [add, Int.add_comm]"));
2521        assert!(lean.contains(
2522            "theorem add_law_commutative_sample_1 : add 1 2 = add 2 1 := by native_decide"
2523        ));
2524        assert!(lean.contains(
2525            "theorem add_law_commutative_sample_2 : add 2 3 = add 3 2 := by native_decide"
2526        ));
2527    }
2528
2529    #[test]
2530    fn generate_prelude_emits_int_roundtrip_theorem() {
2531        let lean = generate_prelude();
2532        assert!(lean.contains(
2533            "theorem Int.fromString_fromInt : ∀ n : Int, Int.fromString (String.fromInt n) = .ok n"
2534        ));
2535        assert!(lean.contains("theorem String.intercalate_empty_chars (s : String) :"));
2536        assert!(lean.contains("def splitOnCharGo"));
2537        assert!(lean.contains("theorem split_single_char_append"));
2538        assert!(lean.contains("theorem split_intercalate_trailing_single_char"));
2539        assert!(lean.contains("namespace AverDigits"));
2540        assert!(lean.contains("theorem String.charAt_length_none (s : String)"));
2541        assert!(lean.contains("theorem digitChar_not_ws : ∀ d : Nat, d < 10 ->"));
2542    }
2543
2544    #[test]
2545    fn transpile_emits_guarded_theorems_for_verify_law_when_clause() {
2546        let ctx = ctx_from_source(
2547            r#"
2548module GuardedLaw
2549    intent =
2550        "verify law with precondition"
2551
2552fn pickGreater(a: Int, b: Int) -> Int
2553    match a > b
2554        true -> a
2555        false -> b
2556
2557verify pickGreater law ordered
2558    given a: Int = [1, 2]
2559    given b: Int = [1, 2]
2560    when a > b
2561    pickGreater(a, b) => a
2562"#,
2563            "guarded_law",
2564        );
2565        let out = transpile_with_verify_mode(&ctx, VerifyEmitMode::TheoremSkeleton);
2566        let lean = generated_lean_file(&out);
2567
2568        assert!(lean.contains("-- when (a > b)"));
2569        assert!(lean.contains(
2570            "theorem pickGreater_law_ordered : ∀ (a : Int) (b : Int), a = 1 ∨ a = 2 -> b = 1 ∨ b = 2 -> (a > b) = true -> pickGreater a b = a := by"
2571        ));
2572        assert!(lean.contains(
2573            "theorem pickGreater_law_ordered_sample_1 : (1 > 1) = true -> pickGreater 1 1 = 1 := by"
2574        ));
2575        assert!(lean.contains(
2576            "theorem pickGreater_law_ordered_sample_4 : (2 > 2) = true -> pickGreater 2 2 = 2 := by"
2577        ));
2578    }
2579
2580    #[test]
2581    fn transpile_uses_spec_theorem_names_for_declared_spec_laws() {
2582        let ctx = ctx_from_source(
2583            r#"
2584module SpecDemo
2585    intent =
2586        "spec demo"
2587
2588fn absVal(x: Int) -> Int
2589    match x < 0
2590        true -> 0 - x
2591        false -> x
2592
2593fn absValSpec(x: Int) -> Int
2594    match x < 0
2595        true -> 0 - x
2596        false -> x
2597
2598verify absVal law absValSpec
2599    given x: Int = [-2, -1, 0, 1, 2]
2600    absVal(x) => absValSpec(x)
2601"#,
2602            "spec_demo",
2603        );
2604        let out = transpile_with_verify_mode(&ctx, VerifyEmitMode::TheoremSkeleton);
2605        let lean = generated_lean_file(&out);
2606
2607        assert!(lean.contains("-- verify law absVal.spec absValSpec (5 cases)"));
2608        assert!(
2609            lean.contains(
2610                "theorem absVal_eq_absValSpec : ∀ (x : Int), absVal x = absValSpec x := by"
2611            )
2612        );
2613        assert!(lean.contains("theorem absVal_eq_absValSpec_checked_domain :"));
2614        assert!(lean.contains("theorem absVal_eq_absValSpec_sample_1 :"));
2615        assert!(!lean.contains("theorem absVal_law_absValSpec :"));
2616    }
2617
2618    #[test]
2619    fn transpile_keeps_noncanonical_spec_laws_as_regular_law_names() {
2620        let ctx = ctx_from_source(
2621            r#"
2622module SpecLawShape
2623    intent =
2624        "shape probe"
2625
2626fn foo(x: Int) -> Int
2627    x + 1
2628
2629fn fooSpec(seed: Int, x: Int) -> Int
2630    x + seed
2631
2632verify foo law fooSpec
2633    given x: Int = [1, 2]
2634    foo(x) => fooSpec(1, x)
2635"#,
2636            "spec_law_shape",
2637        );
2638        let out = transpile_with_verify_mode(&ctx, VerifyEmitMode::TheoremSkeleton);
2639        let lean = generated_lean_file(&out);
2640
2641        assert!(lean.contains("-- verify law foo.fooSpec (2 cases)"));
2642        assert!(lean.contains("theorem foo_law_fooSpec : ∀ (x : Int), foo x = fooSpec 1 x := by"));
2643        assert!(!lean.contains("theorem foo_eq_fooSpec :"));
2644    }
2645
2646    #[test]
2647    fn transpile_auto_proves_linear_int_canonical_spec_law_in_auto_mode() {
2648        let ctx = ctx_from_source(
2649            r#"
2650module SpecGap
2651    intent =
2652        "nontrivial canonical spec law"
2653
2654fn inc(x: Int) -> Int
2655    x + 1
2656
2657fn incSpec(x: Int) -> Int
2658    x + 2 - 1
2659
2660verify inc law incSpec
2661    given x: Int = [0, 1, 2]
2662    inc(x) => incSpec(x)
2663"#,
2664            "spec_gap",
2665        );
2666        let out = transpile(&ctx);
2667        let lean = generated_lean_file(&out);
2668
2669        assert!(lean.contains("-- verify law inc.spec incSpec (3 cases)"));
2670        assert!(lean.contains("theorem inc_eq_incSpec : ∀ (x : Int), inc x = incSpec x := by"));
2671        assert!(lean.contains("change (x + 1) = ((x + 2) - 1)"));
2672        assert!(lean.contains("omega"));
2673        assert!(!lean.contains(
2674            "-- universal theorem inc_eq_incSpec omitted: sampled law shape is not auto-proved yet"
2675        ));
2676        assert!(lean.contains("theorem inc_eq_incSpec_checked_domain :"));
2677    }
2678
2679    #[test]
2680    fn transpile_auto_proves_guarded_canonical_spec_law_in_auto_mode() {
2681        let ctx = ctx_from_source(
2682            r#"
2683module GuardedSpecGap
2684    intent =
2685        "guarded canonical spec law"
2686
2687fn clampNonNegative(x: Int) -> Int
2688    match x < 0
2689        true -> 0
2690        false -> x
2691
2692fn clampNonNegativeSpec(x: Int) -> Int
2693    match x < 0
2694        true -> 0
2695        false -> x
2696
2697verify clampNonNegative law clampNonNegativeSpec
2698    given x: Int = [-2, -1, 0, 1, 2]
2699    when x >= 0
2700    clampNonNegative(x) => clampNonNegativeSpec(x)
2701"#,
2702            "guarded_spec_gap",
2703        );
2704        let out = transpile(&ctx);
2705        let lean = generated_lean_file(&out);
2706
2707        assert!(lean.contains("-- when (x >= 0)"));
2708        assert!(lean.contains(
2709            "theorem clampNonNegative_eq_clampNonNegativeSpec : ∀ (x : Int), x = (-2) ∨ x = (-1) ∨ x = 0 ∨ x = 1 ∨ x = 2 -> (x >= 0) = true -> clampNonNegative x = clampNonNegativeSpec x := by"
2710        ));
2711        assert!(lean.contains("intro x h_x h_when"));
2712        assert!(lean.contains("simpa [clampNonNegative, clampNonNegativeSpec]"));
2713        assert!(!lean.contains(
2714            "-- universal theorem clampNonNegative_eq_clampNonNegativeSpec omitted: sampled law shape is not auto-proved yet"
2715        ));
2716        assert!(!lean.contains("cases h_x"));
2717    }
2718
2719    #[test]
2720    fn transpile_auto_proves_simp_normalized_canonical_spec_law_in_auto_mode() {
2721        let ctx = ctx_from_source(
2722            r#"
2723module SpecGapNonlinear
2724    intent =
2725        "nonlinear canonical spec law"
2726
2727fn square(x: Int) -> Int
2728    x * x
2729
2730fn squareSpec(x: Int) -> Int
2731    x * x + 0
2732
2733verify square law squareSpec
2734    given x: Int = [0, 1, 2]
2735    square(x) => squareSpec(x)
2736"#,
2737            "spec_gap_nonlinear",
2738        );
2739        let out = transpile(&ctx);
2740        let lean = generated_lean_file(&out);
2741
2742        assert!(lean.contains("-- verify law square.spec squareSpec (3 cases)"));
2743        assert!(
2744            lean.contains(
2745                "theorem square_eq_squareSpec : ∀ (x : Int), square x = squareSpec x := by"
2746            )
2747        );
2748        assert!(lean.contains("simp [square, squareSpec]"));
2749        assert!(!lean.contains(
2750            "-- universal theorem square_eq_squareSpec omitted: sampled law shape is not auto-proved yet"
2751        ));
2752        assert!(lean.contains("theorem square_eq_squareSpec_checked_domain :"));
2753        assert!(lean.contains("theorem square_eq_squareSpec_sample_1 :"));
2754    }
2755
2756    #[test]
2757    fn transpile_auto_proves_reflexive_law_with_rfl() {
2758        let mut ctx = empty_ctx();
2759        ctx.items.push(TopLevel::Verify(VerifyBlock {
2760            fn_name: "idLaw".to_string(),
2761            line: 1,
2762            cases: vec![(
2763                Expr::Literal(Literal::Int(1)),
2764                Expr::Literal(Literal::Int(1)),
2765            )],
2766            kind: VerifyKind::Law(Box::new(VerifyLaw {
2767                name: "reflexive".to_string(),
2768                givens: vec![VerifyGiven {
2769                    name: "x".to_string(),
2770                    type_name: "Int".to_string(),
2771                    domain: VerifyGivenDomain::IntRange { start: 1, end: 2 },
2772                }],
2773                when: None,
2774                lhs: Expr::Ident("x".to_string()),
2775                rhs: Expr::Ident("x".to_string()),
2776                sample_guards: vec![],
2777            })),
2778        }));
2779        let out = transpile(&ctx);
2780        let lean = out
2781            .files
2782            .iter()
2783            .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
2784            .expect("expected generated Lean file");
2785        assert!(lean.contains("theorem idLaw_law_reflexive : ∀ (x : Int), x = x := by"));
2786        assert!(lean.contains("  intro x"));
2787        assert!(lean.contains("  rfl"));
2788    }
2789
2790    #[test]
2791    fn transpile_auto_proves_identity_law_for_int_add_wrapper() {
2792        let mut ctx = empty_ctx_with_verify_law();
2793        ctx.items.push(TopLevel::Verify(VerifyBlock {
2794            fn_name: "add".to_string(),
2795            line: 10,
2796            cases: vec![(
2797                Expr::FnCall(
2798                    Box::new(Expr::Ident("add".to_string())),
2799                    vec![
2800                        Expr::Literal(Literal::Int(1)),
2801                        Expr::Literal(Literal::Int(0)),
2802                    ],
2803                ),
2804                Expr::Literal(Literal::Int(1)),
2805            )],
2806            kind: VerifyKind::Law(Box::new(VerifyLaw {
2807                name: "identityZero".to_string(),
2808                givens: vec![VerifyGiven {
2809                    name: "a".to_string(),
2810                    type_name: "Int".to_string(),
2811                    domain: VerifyGivenDomain::Explicit(vec![
2812                        Expr::Literal(Literal::Int(0)),
2813                        Expr::Literal(Literal::Int(1)),
2814                    ]),
2815                }],
2816                when: None,
2817                lhs: Expr::FnCall(
2818                    Box::new(Expr::Ident("add".to_string())),
2819                    vec![Expr::Ident("a".to_string()), Expr::Literal(Literal::Int(0))],
2820                ),
2821                rhs: Expr::Ident("a".to_string()),
2822                sample_guards: vec![],
2823            })),
2824        }));
2825        let out = transpile(&ctx);
2826        let lean = out
2827            .files
2828            .iter()
2829            .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
2830            .expect("expected generated Lean file");
2831        assert!(lean.contains("theorem add_law_identityZero : ∀ (a : Int), add a 0 = a := by"));
2832        assert!(lean.contains("  intro a"));
2833        assert!(lean.contains("  simp [add]"));
2834    }
2835
2836    #[test]
2837    fn transpile_auto_proves_associative_law_for_int_add_wrapper() {
2838        let mut ctx = empty_ctx_with_verify_law();
2839        ctx.items.push(TopLevel::Verify(VerifyBlock {
2840            fn_name: "add".to_string(),
2841            line: 20,
2842            cases: vec![(
2843                Expr::FnCall(
2844                    Box::new(Expr::Ident("add".to_string())),
2845                    vec![
2846                        Expr::FnCall(
2847                            Box::new(Expr::Ident("add".to_string())),
2848                            vec![
2849                                Expr::Literal(Literal::Int(1)),
2850                                Expr::Literal(Literal::Int(2)),
2851                            ],
2852                        ),
2853                        Expr::Literal(Literal::Int(3)),
2854                    ],
2855                ),
2856                Expr::FnCall(
2857                    Box::new(Expr::Ident("add".to_string())),
2858                    vec![
2859                        Expr::Literal(Literal::Int(1)),
2860                        Expr::FnCall(
2861                            Box::new(Expr::Ident("add".to_string())),
2862                            vec![
2863                                Expr::Literal(Literal::Int(2)),
2864                                Expr::Literal(Literal::Int(3)),
2865                            ],
2866                        ),
2867                    ],
2868                ),
2869            )],
2870            kind: VerifyKind::Law(Box::new(VerifyLaw {
2871                name: "associative".to_string(),
2872                givens: vec![
2873                    VerifyGiven {
2874                        name: "a".to_string(),
2875                        type_name: "Int".to_string(),
2876                        domain: VerifyGivenDomain::Explicit(vec![Expr::Literal(Literal::Int(1))]),
2877                    },
2878                    VerifyGiven {
2879                        name: "b".to_string(),
2880                        type_name: "Int".to_string(),
2881                        domain: VerifyGivenDomain::Explicit(vec![Expr::Literal(Literal::Int(2))]),
2882                    },
2883                    VerifyGiven {
2884                        name: "c".to_string(),
2885                        type_name: "Int".to_string(),
2886                        domain: VerifyGivenDomain::Explicit(vec![Expr::Literal(Literal::Int(3))]),
2887                    },
2888                ],
2889                when: None,
2890                lhs: Expr::FnCall(
2891                    Box::new(Expr::Ident("add".to_string())),
2892                    vec![
2893                        Expr::FnCall(
2894                            Box::new(Expr::Ident("add".to_string())),
2895                            vec![Expr::Ident("a".to_string()), Expr::Ident("b".to_string())],
2896                        ),
2897                        Expr::Ident("c".to_string()),
2898                    ],
2899                ),
2900                rhs: Expr::FnCall(
2901                    Box::new(Expr::Ident("add".to_string())),
2902                    vec![
2903                        Expr::Ident("a".to_string()),
2904                        Expr::FnCall(
2905                            Box::new(Expr::Ident("add".to_string())),
2906                            vec![Expr::Ident("b".to_string()), Expr::Ident("c".to_string())],
2907                        ),
2908                    ],
2909                ),
2910                sample_guards: vec![],
2911            })),
2912        }));
2913        let out = transpile(&ctx);
2914        let lean = out
2915            .files
2916            .iter()
2917            .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
2918            .expect("expected generated Lean file");
2919        assert!(lean.contains(
2920            "theorem add_law_associative : ∀ (a : Int) (b : Int) (c : Int), add (add a b) c = add a (add b c) := by"
2921        ));
2922        assert!(lean.contains("  intro a b c"));
2923        assert!(lean.contains("  simp [add, Int.add_assoc]"));
2924    }
2925
2926    #[test]
2927    fn transpile_auto_proves_sub_laws() {
2928        let mut ctx = empty_ctx();
2929        let sub = FnDef {
2930            name: "sub".to_string(),
2931            line: 1,
2932            params: vec![
2933                ("a".to_string(), "Int".to_string()),
2934                ("b".to_string(), "Int".to_string()),
2935            ],
2936            return_type: "Int".to_string(),
2937            effects: vec![],
2938            desc: None,
2939            body: Rc::new(FnBody::from_expr(Expr::BinOp(
2940                BinOp::Sub,
2941                Box::new(Expr::Ident("a".to_string())),
2942                Box::new(Expr::Ident("b".to_string())),
2943            ))),
2944            resolution: None,
2945        };
2946        ctx.fn_defs.push(sub.clone());
2947        ctx.items.push(TopLevel::FnDef(sub));
2948
2949        ctx.items.push(TopLevel::Verify(VerifyBlock {
2950            fn_name: "sub".to_string(),
2951            line: 10,
2952            cases: vec![(
2953                Expr::FnCall(
2954                    Box::new(Expr::Ident("sub".to_string())),
2955                    vec![
2956                        Expr::Literal(Literal::Int(2)),
2957                        Expr::Literal(Literal::Int(0)),
2958                    ],
2959                ),
2960                Expr::Literal(Literal::Int(2)),
2961            )],
2962            kind: VerifyKind::Law(Box::new(VerifyLaw {
2963                name: "rightIdentity".to_string(),
2964                givens: vec![VerifyGiven {
2965                    name: "a".to_string(),
2966                    type_name: "Int".to_string(),
2967                    domain: VerifyGivenDomain::Explicit(vec![Expr::Literal(Literal::Int(2))]),
2968                }],
2969                when: None,
2970                lhs: Expr::FnCall(
2971                    Box::new(Expr::Ident("sub".to_string())),
2972                    vec![Expr::Ident("a".to_string()), Expr::Literal(Literal::Int(0))],
2973                ),
2974                rhs: Expr::Ident("a".to_string()),
2975                sample_guards: vec![],
2976            })),
2977        }));
2978        ctx.items.push(TopLevel::Verify(VerifyBlock {
2979            fn_name: "sub".to_string(),
2980            line: 20,
2981            cases: vec![(
2982                Expr::FnCall(
2983                    Box::new(Expr::Ident("sub".to_string())),
2984                    vec![
2985                        Expr::Literal(Literal::Int(2)),
2986                        Expr::Literal(Literal::Int(1)),
2987                    ],
2988                ),
2989                Expr::BinOp(
2990                    BinOp::Sub,
2991                    Box::new(Expr::Literal(Literal::Int(0))),
2992                    Box::new(Expr::FnCall(
2993                        Box::new(Expr::Ident("sub".to_string())),
2994                        vec![
2995                            Expr::Literal(Literal::Int(1)),
2996                            Expr::Literal(Literal::Int(2)),
2997                        ],
2998                    )),
2999                ),
3000            )],
3001            kind: VerifyKind::Law(Box::new(VerifyLaw {
3002                name: "antiCommutative".to_string(),
3003                givens: vec![
3004                    VerifyGiven {
3005                        name: "a".to_string(),
3006                        type_name: "Int".to_string(),
3007                        domain: VerifyGivenDomain::Explicit(vec![Expr::Literal(Literal::Int(2))]),
3008                    },
3009                    VerifyGiven {
3010                        name: "b".to_string(),
3011                        type_name: "Int".to_string(),
3012                        domain: VerifyGivenDomain::Explicit(vec![Expr::Literal(Literal::Int(1))]),
3013                    },
3014                ],
3015                when: None,
3016                lhs: Expr::FnCall(
3017                    Box::new(Expr::Ident("sub".to_string())),
3018                    vec![Expr::Ident("a".to_string()), Expr::Ident("b".to_string())],
3019                ),
3020                rhs: Expr::BinOp(
3021                    BinOp::Sub,
3022                    Box::new(Expr::Literal(Literal::Int(0))),
3023                    Box::new(Expr::FnCall(
3024                        Box::new(Expr::Ident("sub".to_string())),
3025                        vec![Expr::Ident("b".to_string()), Expr::Ident("a".to_string())],
3026                    )),
3027                ),
3028                sample_guards: vec![],
3029            })),
3030        }));
3031
3032        let out = transpile(&ctx);
3033        let lean = out
3034            .files
3035            .iter()
3036            .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
3037            .expect("expected generated Lean file");
3038        assert!(lean.contains("theorem sub_law_rightIdentity : ∀ (a : Int), sub a 0 = a := by"));
3039        assert!(lean.contains("  simp [sub]"));
3040        assert!(lean.contains(
3041            "theorem sub_law_antiCommutative : ∀ (a : Int) (b : Int), sub a b = (-sub b a) := by"
3042        ));
3043        assert!(lean.contains("  simpa [sub] using (Int.neg_sub b a).symm"));
3044    }
3045
3046    #[test]
3047    fn transpile_auto_proves_unary_wrapper_equivalence_law() {
3048        let mut ctx = empty_ctx();
3049        let add = FnDef {
3050            name: "add".to_string(),
3051            line: 1,
3052            params: vec![
3053                ("a".to_string(), "Int".to_string()),
3054                ("b".to_string(), "Int".to_string()),
3055            ],
3056            return_type: "Int".to_string(),
3057            effects: vec![],
3058            desc: None,
3059            body: Rc::new(FnBody::from_expr(Expr::BinOp(
3060                BinOp::Add,
3061                Box::new(Expr::Ident("a".to_string())),
3062                Box::new(Expr::Ident("b".to_string())),
3063            ))),
3064            resolution: None,
3065        };
3066        let add_one = FnDef {
3067            name: "addOne".to_string(),
3068            line: 2,
3069            params: vec![("n".to_string(), "Int".to_string())],
3070            return_type: "Int".to_string(),
3071            effects: vec![],
3072            desc: None,
3073            body: Rc::new(FnBody::from_expr(Expr::BinOp(
3074                BinOp::Add,
3075                Box::new(Expr::Ident("n".to_string())),
3076                Box::new(Expr::Literal(Literal::Int(1))),
3077            ))),
3078            resolution: None,
3079        };
3080        ctx.fn_defs.push(add.clone());
3081        ctx.fn_defs.push(add_one.clone());
3082        ctx.items.push(TopLevel::FnDef(add));
3083        ctx.items.push(TopLevel::FnDef(add_one));
3084        ctx.items.push(TopLevel::Verify(VerifyBlock {
3085            fn_name: "addOne".to_string(),
3086            line: 3,
3087            cases: vec![(
3088                Expr::FnCall(
3089                    Box::new(Expr::Ident("addOne".to_string())),
3090                    vec![Expr::Literal(Literal::Int(2))],
3091                ),
3092                Expr::FnCall(
3093                    Box::new(Expr::Ident("add".to_string())),
3094                    vec![
3095                        Expr::Literal(Literal::Int(2)),
3096                        Expr::Literal(Literal::Int(1)),
3097                    ],
3098                ),
3099            )],
3100            kind: VerifyKind::Law(Box::new(VerifyLaw {
3101                name: "identityViaAdd".to_string(),
3102                givens: vec![VerifyGiven {
3103                    name: "n".to_string(),
3104                    type_name: "Int".to_string(),
3105                    domain: VerifyGivenDomain::Explicit(vec![Expr::Literal(Literal::Int(2))]),
3106                }],
3107                when: None,
3108                lhs: Expr::FnCall(
3109                    Box::new(Expr::Ident("addOne".to_string())),
3110                    vec![Expr::Ident("n".to_string())],
3111                ),
3112                rhs: Expr::FnCall(
3113                    Box::new(Expr::Ident("add".to_string())),
3114                    vec![Expr::Ident("n".to_string()), Expr::Literal(Literal::Int(1))],
3115                ),
3116                sample_guards: vec![],
3117            })),
3118        }));
3119        let out = transpile(&ctx);
3120        let lean = out
3121            .files
3122            .iter()
3123            .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
3124            .expect("expected generated Lean file");
3125        assert!(
3126            lean.contains(
3127                "theorem addOne_law_identityViaAdd : ∀ (n : Int), addOne n = add n 1 := by"
3128            )
3129        );
3130        assert!(lean.contains("  simp [addOne, add]"));
3131    }
3132
3133    #[test]
3134    fn transpile_auto_proves_direct_map_set_laws() {
3135        let mut ctx = empty_ctx();
3136
3137        let map_set = |m: Expr, k: Expr, v: Expr| {
3138            Expr::FnCall(
3139                Box::new(Expr::Attr(
3140                    Box::new(Expr::Ident("Map".to_string())),
3141                    "set".to_string(),
3142                )),
3143                vec![m, k, v],
3144            )
3145        };
3146        let map_has = |m: Expr, k: Expr| {
3147            Expr::FnCall(
3148                Box::new(Expr::Attr(
3149                    Box::new(Expr::Ident("Map".to_string())),
3150                    "has".to_string(),
3151                )),
3152                vec![m, k],
3153            )
3154        };
3155        let map_get = |m: Expr, k: Expr| {
3156            Expr::FnCall(
3157                Box::new(Expr::Attr(
3158                    Box::new(Expr::Ident("Map".to_string())),
3159                    "get".to_string(),
3160                )),
3161                vec![m, k],
3162            )
3163        };
3164        let some = |v: Expr| {
3165            Expr::FnCall(
3166                Box::new(Expr::Attr(
3167                    Box::new(Expr::Ident("Option".to_string())),
3168                    "Some".to_string(),
3169                )),
3170                vec![v],
3171            )
3172        };
3173
3174        ctx.items.push(TopLevel::Verify(VerifyBlock {
3175            fn_name: "map".to_string(),
3176            line: 1,
3177            cases: vec![(
3178                map_has(
3179                    map_set(
3180                        Expr::Ident("m".to_string()),
3181                        Expr::Ident("k".to_string()),
3182                        Expr::Ident("v".to_string()),
3183                    ),
3184                    Expr::Ident("k".to_string()),
3185                ),
3186                Expr::Literal(Literal::Bool(true)),
3187            )],
3188            kind: VerifyKind::Law(Box::new(VerifyLaw {
3189                name: "setHasKey".to_string(),
3190                givens: vec![
3191                    VerifyGiven {
3192                        name: "m".to_string(),
3193                        type_name: "Map<String, Int>".to_string(),
3194                        domain: VerifyGivenDomain::Explicit(vec![Expr::FnCall(
3195                            Box::new(Expr::Attr(
3196                                Box::new(Expr::Ident("Map".to_string())),
3197                                "empty".to_string(),
3198                            )),
3199                            vec![],
3200                        )]),
3201                    },
3202                    VerifyGiven {
3203                        name: "k".to_string(),
3204                        type_name: "String".to_string(),
3205                        domain: VerifyGivenDomain::Explicit(vec![Expr::Literal(Literal::Str(
3206                            "a".to_string(),
3207                        ))]),
3208                    },
3209                    VerifyGiven {
3210                        name: "v".to_string(),
3211                        type_name: "Int".to_string(),
3212                        domain: VerifyGivenDomain::Explicit(vec![Expr::Literal(Literal::Int(1))]),
3213                    },
3214                ],
3215                when: None,
3216                lhs: map_has(
3217                    map_set(
3218                        Expr::Ident("m".to_string()),
3219                        Expr::Ident("k".to_string()),
3220                        Expr::Ident("v".to_string()),
3221                    ),
3222                    Expr::Ident("k".to_string()),
3223                ),
3224                rhs: Expr::Literal(Literal::Bool(true)),
3225                sample_guards: vec![],
3226            })),
3227        }));
3228
3229        ctx.items.push(TopLevel::Verify(VerifyBlock {
3230            fn_name: "map".to_string(),
3231            line: 2,
3232            cases: vec![(
3233                map_get(
3234                    map_set(
3235                        Expr::Ident("m".to_string()),
3236                        Expr::Ident("k".to_string()),
3237                        Expr::Ident("v".to_string()),
3238                    ),
3239                    Expr::Ident("k".to_string()),
3240                ),
3241                some(Expr::Ident("v".to_string())),
3242            )],
3243            kind: VerifyKind::Law(Box::new(VerifyLaw {
3244                name: "setGetKey".to_string(),
3245                givens: vec![
3246                    VerifyGiven {
3247                        name: "m".to_string(),
3248                        type_name: "Map<String, Int>".to_string(),
3249                        domain: VerifyGivenDomain::Explicit(vec![Expr::FnCall(
3250                            Box::new(Expr::Attr(
3251                                Box::new(Expr::Ident("Map".to_string())),
3252                                "empty".to_string(),
3253                            )),
3254                            vec![],
3255                        )]),
3256                    },
3257                    VerifyGiven {
3258                        name: "k".to_string(),
3259                        type_name: "String".to_string(),
3260                        domain: VerifyGivenDomain::Explicit(vec![Expr::Literal(Literal::Str(
3261                            "a".to_string(),
3262                        ))]),
3263                    },
3264                    VerifyGiven {
3265                        name: "v".to_string(),
3266                        type_name: "Int".to_string(),
3267                        domain: VerifyGivenDomain::Explicit(vec![Expr::Literal(Literal::Int(1))]),
3268                    },
3269                ],
3270                when: None,
3271                lhs: map_get(
3272                    map_set(
3273                        Expr::Ident("m".to_string()),
3274                        Expr::Ident("k".to_string()),
3275                        Expr::Ident("v".to_string()),
3276                    ),
3277                    Expr::Ident("k".to_string()),
3278                ),
3279                rhs: some(Expr::Ident("v".to_string())),
3280                sample_guards: vec![],
3281            })),
3282        }));
3283
3284        let out = transpile(&ctx);
3285        let lean = out
3286            .files
3287            .iter()
3288            .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
3289            .expect("expected generated Lean file");
3290        assert!(lean.contains("simpa using AverMap.has_set_self m k v"));
3291        assert!(lean.contains("simpa using AverMap.get_set_self m k v"));
3292    }
3293
3294    #[test]
3295    fn transpile_auto_proves_direct_recursive_sum_law_by_structural_induction() {
3296        let ctx = ctx_from_source(
3297            r#"
3298module Mirror
3299    intent =
3300        "direct recursive sum induction probe"
3301
3302type Tree
3303    Leaf(Int)
3304    Node(Tree, Tree)
3305
3306fn mirror(t: Tree) -> Tree
3307    match t
3308        Tree.Leaf(v) -> Tree.Leaf(v)
3309        Tree.Node(left, right) -> Tree.Node(mirror(right), mirror(left))
3310
3311verify mirror law involutive
3312    given t: Tree = [Tree.Leaf(1), Tree.Node(Tree.Leaf(1), Tree.Leaf(2))]
3313    mirror(mirror(t)) => t
3314"#,
3315            "mirror",
3316        );
3317        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
3318        let lean = generated_lean_file(&out);
3319
3320        assert!(
3321            lean.contains(
3322                "theorem mirror_law_involutive : ∀ (t : Tree), mirror (mirror t) = t := by"
3323            )
3324        );
3325        assert!(lean.contains("  induction t with"));
3326        assert!(lean.contains("  | leaf f0 => simp [mirror]"));
3327        assert!(lean.contains("  | node f0 f1 ih0 ih1 => simp_all [mirror]"));
3328        assert!(!lean.contains(
3329            "-- universal theorem mirror_law_involutive omitted: sampled law shape is not auto-proved yet"
3330        ));
3331    }
3332
3333    #[test]
3334    fn transpile_auto_proves_map_update_laws() {
3335        let mut ctx = empty_ctx();
3336
3337        let map_get = |m: Expr, k: Expr| {
3338            Expr::FnCall(
3339                Box::new(Expr::Attr(
3340                    Box::new(Expr::Ident("Map".to_string())),
3341                    "get".to_string(),
3342                )),
3343                vec![m, k],
3344            )
3345        };
3346        let map_set = |m: Expr, k: Expr, v: Expr| {
3347            Expr::FnCall(
3348                Box::new(Expr::Attr(
3349                    Box::new(Expr::Ident("Map".to_string())),
3350                    "set".to_string(),
3351                )),
3352                vec![m, k, v],
3353            )
3354        };
3355        let map_has = |m: Expr, k: Expr| {
3356            Expr::FnCall(
3357                Box::new(Expr::Attr(
3358                    Box::new(Expr::Ident("Map".to_string())),
3359                    "has".to_string(),
3360                )),
3361                vec![m, k],
3362            )
3363        };
3364        let option_some = |v: Expr| {
3365            Expr::FnCall(
3366                Box::new(Expr::Attr(
3367                    Box::new(Expr::Ident("Option".to_string())),
3368                    "Some".to_string(),
3369                )),
3370                vec![v],
3371            )
3372        };
3373        let option_with_default = |opt: Expr, def: Expr| {
3374            Expr::FnCall(
3375                Box::new(Expr::Attr(
3376                    Box::new(Expr::Ident("Option".to_string())),
3377                    "withDefault".to_string(),
3378                )),
3379                vec![opt, def],
3380            )
3381        };
3382
3383        let add_one = FnDef {
3384            name: "addOne".to_string(),
3385            line: 1,
3386            params: vec![("n".to_string(), "Int".to_string())],
3387            return_type: "Int".to_string(),
3388            effects: vec![],
3389            desc: None,
3390            body: Rc::new(FnBody::from_expr(Expr::BinOp(
3391                BinOp::Add,
3392                Box::new(Expr::Ident("n".to_string())),
3393                Box::new(Expr::Literal(Literal::Int(1))),
3394            ))),
3395            resolution: None,
3396        };
3397        ctx.fn_defs.push(add_one.clone());
3398        ctx.items.push(TopLevel::FnDef(add_one));
3399
3400        let inc_count = FnDef {
3401            name: "incCount".to_string(),
3402            line: 2,
3403            params: vec![
3404                ("counts".to_string(), "Map<String, Int>".to_string()),
3405                ("word".to_string(), "String".to_string()),
3406            ],
3407            return_type: "Map<String, Int>".to_string(),
3408            effects: vec![],
3409            desc: None,
3410            body: Rc::new(FnBody::Block(vec![
3411                Stmt::Binding(
3412                    "current".to_string(),
3413                    None,
3414                    map_get(
3415                        Expr::Ident("counts".to_string()),
3416                        Expr::Ident("word".to_string()),
3417                    ),
3418                ),
3419                Stmt::Expr(Expr::Match {
3420                    subject: Box::new(Expr::Ident("current".to_string())),
3421                    arms: vec![
3422                        MatchArm {
3423                            pattern: Pattern::Constructor(
3424                                "Option.Some".to_string(),
3425                                vec!["n".to_string()],
3426                            ),
3427                            body: Box::new(map_set(
3428                                Expr::Ident("counts".to_string()),
3429                                Expr::Ident("word".to_string()),
3430                                Expr::BinOp(
3431                                    BinOp::Add,
3432                                    Box::new(Expr::Ident("n".to_string())),
3433                                    Box::new(Expr::Literal(Literal::Int(1))),
3434                                ),
3435                            )),
3436                        },
3437                        MatchArm {
3438                            pattern: Pattern::Constructor("Option.None".to_string(), vec![]),
3439                            body: Box::new(map_set(
3440                                Expr::Ident("counts".to_string()),
3441                                Expr::Ident("word".to_string()),
3442                                Expr::Literal(Literal::Int(1)),
3443                            )),
3444                        },
3445                    ],
3446                    line: 2,
3447                }),
3448            ])),
3449            resolution: None,
3450        };
3451        ctx.fn_defs.push(inc_count.clone());
3452        ctx.items.push(TopLevel::FnDef(inc_count));
3453
3454        ctx.items.push(TopLevel::Verify(VerifyBlock {
3455            fn_name: "incCount".to_string(),
3456            line: 10,
3457            cases: vec![(
3458                map_has(
3459                    Expr::FnCall(
3460                        Box::new(Expr::Ident("incCount".to_string())),
3461                        vec![
3462                            Expr::Ident("counts".to_string()),
3463                            Expr::Ident("word".to_string()),
3464                        ],
3465                    ),
3466                    Expr::Ident("word".to_string()),
3467                ),
3468                Expr::Literal(Literal::Bool(true)),
3469            )],
3470            kind: VerifyKind::Law(Box::new(VerifyLaw {
3471                name: "keyPresent".to_string(),
3472                givens: vec![
3473                    VerifyGiven {
3474                        name: "counts".to_string(),
3475                        type_name: "Map<String, Int>".to_string(),
3476                        domain: VerifyGivenDomain::Explicit(vec![Expr::FnCall(
3477                            Box::new(Expr::Attr(
3478                                Box::new(Expr::Ident("Map".to_string())),
3479                                "empty".to_string(),
3480                            )),
3481                            vec![],
3482                        )]),
3483                    },
3484                    VerifyGiven {
3485                        name: "word".to_string(),
3486                        type_name: "String".to_string(),
3487                        domain: VerifyGivenDomain::Explicit(vec![Expr::Literal(Literal::Str(
3488                            "a".to_string(),
3489                        ))]),
3490                    },
3491                ],
3492                when: None,
3493                lhs: map_has(
3494                    Expr::FnCall(
3495                        Box::new(Expr::Ident("incCount".to_string())),
3496                        vec![
3497                            Expr::Ident("counts".to_string()),
3498                            Expr::Ident("word".to_string()),
3499                        ],
3500                    ),
3501                    Expr::Ident("word".to_string()),
3502                ),
3503                rhs: Expr::Literal(Literal::Bool(true)),
3504                sample_guards: vec![],
3505            })),
3506        }));
3507
3508        ctx.items.push(TopLevel::Verify(VerifyBlock {
3509            fn_name: "incCount".to_string(),
3510            line: 20,
3511            cases: vec![(
3512                map_get(
3513                    Expr::FnCall(
3514                        Box::new(Expr::Ident("incCount".to_string())),
3515                        vec![
3516                            Expr::Ident("counts".to_string()),
3517                            Expr::Literal(Literal::Str("a".to_string())),
3518                        ],
3519                    ),
3520                    Expr::Literal(Literal::Str("a".to_string())),
3521                ),
3522                option_some(Expr::FnCall(
3523                    Box::new(Expr::Ident("addOne".to_string())),
3524                    vec![option_with_default(
3525                        map_get(
3526                            Expr::Ident("counts".to_string()),
3527                            Expr::Literal(Literal::Str("a".to_string())),
3528                        ),
3529                        Expr::Literal(Literal::Int(0)),
3530                    )],
3531                )),
3532            )],
3533            kind: VerifyKind::Law(Box::new(VerifyLaw {
3534                name: "existingKeyIncrements".to_string(),
3535                givens: vec![VerifyGiven {
3536                    name: "counts".to_string(),
3537                    type_name: "Map<String, Int>".to_string(),
3538                    domain: VerifyGivenDomain::Explicit(vec![Expr::FnCall(
3539                        Box::new(Expr::Attr(
3540                            Box::new(Expr::Ident("Map".to_string())),
3541                            "empty".to_string(),
3542                        )),
3543                        vec![],
3544                    )]),
3545                }],
3546                when: None,
3547                lhs: map_get(
3548                    Expr::FnCall(
3549                        Box::new(Expr::Ident("incCount".to_string())),
3550                        vec![
3551                            Expr::Ident("counts".to_string()),
3552                            Expr::Literal(Literal::Str("a".to_string())),
3553                        ],
3554                    ),
3555                    Expr::Literal(Literal::Str("a".to_string())),
3556                ),
3557                rhs: option_some(Expr::FnCall(
3558                    Box::new(Expr::Ident("addOne".to_string())),
3559                    vec![option_with_default(
3560                        map_get(
3561                            Expr::Ident("counts".to_string()),
3562                            Expr::Literal(Literal::Str("a".to_string())),
3563                        ),
3564                        Expr::Literal(Literal::Int(0)),
3565                    )],
3566                )),
3567                sample_guards: vec![],
3568            })),
3569        }));
3570
3571        let out = transpile(&ctx);
3572        let lean = out
3573            .files
3574            .iter()
3575            .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
3576            .expect("expected generated Lean file");
3577        assert!(
3578            lean.contains("cases h : AverMap.get counts word <;> simp [AverMap.has_set_self]"),
3579            "expected keyPresent auto-proof with has_set_self"
3580        );
3581        assert!(
3582            lean.contains("cases h : AverMap.get counts \"a\" <;> simp [AverMap.get_set_self, addOne, incCount]"),
3583            "expected existingKeyIncrements auto-proof with get_set_self"
3584        );
3585    }
3586
3587    #[test]
3588    fn transpile_parenthesizes_negative_int_call_args_in_law_samples() {
3589        let mut ctx = empty_ctx();
3590        let add = FnDef {
3591            name: "add".to_string(),
3592            line: 1,
3593            params: vec![
3594                ("a".to_string(), "Int".to_string()),
3595                ("b".to_string(), "Int".to_string()),
3596            ],
3597            return_type: "Int".to_string(),
3598            effects: vec![],
3599            desc: None,
3600            body: Rc::new(FnBody::from_expr(Expr::BinOp(
3601                BinOp::Add,
3602                Box::new(Expr::Ident("a".to_string())),
3603                Box::new(Expr::Ident("b".to_string())),
3604            ))),
3605            resolution: None,
3606        };
3607        ctx.fn_defs.push(add.clone());
3608        ctx.items.push(TopLevel::FnDef(add));
3609        ctx.items.push(TopLevel::Verify(VerifyBlock {
3610            fn_name: "add".to_string(),
3611            line: 1,
3612            cases: vec![(
3613                Expr::FnCall(
3614                    Box::new(Expr::Ident("add".to_string())),
3615                    vec![
3616                        Expr::Literal(Literal::Int(-2)),
3617                        Expr::Literal(Literal::Int(-1)),
3618                    ],
3619                ),
3620                Expr::FnCall(
3621                    Box::new(Expr::Ident("add".to_string())),
3622                    vec![
3623                        Expr::Literal(Literal::Int(-1)),
3624                        Expr::Literal(Literal::Int(-2)),
3625                    ],
3626                ),
3627            )],
3628            kind: VerifyKind::Law(Box::new(VerifyLaw {
3629                name: "commutative".to_string(),
3630                givens: vec![
3631                    VerifyGiven {
3632                        name: "a".to_string(),
3633                        type_name: "Int".to_string(),
3634                        domain: VerifyGivenDomain::Explicit(vec![Expr::Literal(Literal::Int(-2))]),
3635                    },
3636                    VerifyGiven {
3637                        name: "b".to_string(),
3638                        type_name: "Int".to_string(),
3639                        domain: VerifyGivenDomain::Explicit(vec![Expr::Literal(Literal::Int(-1))]),
3640                    },
3641                ],
3642                when: None,
3643                lhs: Expr::FnCall(
3644                    Box::new(Expr::Ident("add".to_string())),
3645                    vec![Expr::Ident("a".to_string()), Expr::Ident("b".to_string())],
3646                ),
3647                rhs: Expr::FnCall(
3648                    Box::new(Expr::Ident("add".to_string())),
3649                    vec![Expr::Ident("b".to_string()), Expr::Ident("a".to_string())],
3650                ),
3651                sample_guards: vec![],
3652            })),
3653        }));
3654
3655        let out = transpile(&ctx);
3656        let lean = out
3657            .files
3658            .iter()
3659            .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
3660            .expect("expected generated Lean file");
3661        assert!(lean.contains(
3662            "theorem add_law_commutative_sample_1 : add (-2) (-1) = add (-1) (-2) := by native_decide"
3663        ));
3664    }
3665
3666    #[test]
3667    fn verify_law_numbering_is_scoped_per_law_name() {
3668        let mut ctx = empty_ctx();
3669        let f = FnDef {
3670            name: "f".to_string(),
3671            line: 1,
3672            params: vec![("x".to_string(), "Int".to_string())],
3673            return_type: "Int".to_string(),
3674            effects: vec![],
3675            desc: None,
3676            body: Rc::new(FnBody::from_expr(Expr::Ident("x".to_string()))),
3677            resolution: None,
3678        };
3679        ctx.fn_defs.push(f.clone());
3680        ctx.items.push(TopLevel::FnDef(f));
3681        ctx.items.push(TopLevel::Verify(VerifyBlock {
3682            fn_name: "f".to_string(),
3683            line: 1,
3684            cases: vec![(
3685                Expr::Literal(Literal::Int(1)),
3686                Expr::Literal(Literal::Int(1)),
3687            )],
3688            kind: VerifyKind::Cases,
3689        }));
3690        ctx.items.push(TopLevel::Verify(VerifyBlock {
3691            fn_name: "f".to_string(),
3692            line: 2,
3693            cases: vec![(
3694                Expr::Literal(Literal::Int(2)),
3695                Expr::Literal(Literal::Int(2)),
3696            )],
3697            kind: VerifyKind::Law(Box::new(VerifyLaw {
3698                name: "identity".to_string(),
3699                givens: vec![VerifyGiven {
3700                    name: "x".to_string(),
3701                    type_name: "Int".to_string(),
3702                    domain: VerifyGivenDomain::Explicit(vec![Expr::Literal(Literal::Int(2))]),
3703                }],
3704                when: None,
3705                lhs: Expr::Ident("x".to_string()),
3706                rhs: Expr::Ident("x".to_string()),
3707                sample_guards: vec![],
3708            })),
3709        }));
3710        let out = transpile_with_verify_mode(&ctx, VerifyEmitMode::TheoremSkeleton);
3711        let lean = out
3712            .files
3713            .iter()
3714            .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
3715            .expect("expected generated Lean file");
3716        assert!(lean.contains("theorem f_verify_1 : 1 = 1 := by"));
3717        assert!(lean.contains("theorem f_law_identity : ∀ (x : Int), x = x := by"));
3718        assert!(lean.contains("theorem f_law_identity_sample_1 : 2 = 2 := by"));
3719        assert!(!lean.contains("theorem f_law_identity_sample_2 : 2 = 2 := by"));
3720    }
3721
3722    #[test]
3723    fn proof_mode_accepts_single_int_countdown_recursion() {
3724        let mut ctx = empty_ctx();
3725        let down = FnDef {
3726            name: "down".to_string(),
3727            line: 1,
3728            params: vec![("n".to_string(), "Int".to_string())],
3729            return_type: "Int".to_string(),
3730            effects: vec![],
3731            desc: None,
3732            body: Rc::new(FnBody::from_expr(Expr::Match {
3733                subject: Box::new(Expr::Ident("n".to_string())),
3734                arms: vec![
3735                    MatchArm {
3736                        pattern: Pattern::Literal(Literal::Int(0)),
3737                        body: Box::new(Expr::Literal(Literal::Int(0))),
3738                    },
3739                    MatchArm {
3740                        pattern: Pattern::Wildcard,
3741                        body: Box::new(Expr::TailCall(Box::new((
3742                            "down".to_string(),
3743                            vec![Expr::BinOp(
3744                                BinOp::Sub,
3745                                Box::new(Expr::Ident("n".to_string())),
3746                                Box::new(Expr::Literal(Literal::Int(1))),
3747                            )],
3748                        )))),
3749                    },
3750                ],
3751                line: 1,
3752            })),
3753            resolution: None,
3754        };
3755        ctx.items.push(TopLevel::FnDef(down.clone()));
3756        ctx.fn_defs.push(down);
3757
3758        let issues = proof_mode_issues(&ctx);
3759        assert!(
3760            issues.is_empty(),
3761            "expected Int countdown recursion to be accepted, got: {:?}",
3762            issues
3763        );
3764
3765        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
3766        let lean = out
3767            .files
3768            .iter()
3769            .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
3770            .expect("expected generated Lean file");
3771        assert!(lean.contains("def down__fuel"));
3772        assert!(lean.contains("def down (n : Int) : Int :="));
3773        assert!(lean.contains("down__fuel ((Int.natAbs n) + 1) n"));
3774    }
3775
3776    #[test]
3777    fn proof_mode_accepts_single_int_countdown_on_nonfirst_param() {
3778        let mut ctx = empty_ctx();
3779        let repeat_like = FnDef {
3780            name: "repeatLike".to_string(),
3781            line: 1,
3782            params: vec![
3783                ("char".to_string(), "String".to_string()),
3784                ("n".to_string(), "Int".to_string()),
3785            ],
3786            return_type: "List<String>".to_string(),
3787            effects: vec![],
3788            desc: None,
3789            body: Rc::new(FnBody::from_expr(Expr::Match {
3790                subject: Box::new(Expr::BinOp(
3791                    BinOp::Lte,
3792                    Box::new(Expr::Ident("n".to_string())),
3793                    Box::new(Expr::Literal(Literal::Int(0))),
3794                )),
3795                arms: vec![
3796                    MatchArm {
3797                        pattern: Pattern::Literal(Literal::Bool(true)),
3798                        body: Box::new(Expr::List(vec![])),
3799                    },
3800                    MatchArm {
3801                        pattern: Pattern::Literal(Literal::Bool(false)),
3802                        body: Box::new(Expr::TailCall(Box::new((
3803                            "repeatLike".to_string(),
3804                            vec![
3805                                Expr::Ident("char".to_string()),
3806                                Expr::BinOp(
3807                                    BinOp::Sub,
3808                                    Box::new(Expr::Ident("n".to_string())),
3809                                    Box::new(Expr::Literal(Literal::Int(1))),
3810                                ),
3811                            ],
3812                        )))),
3813                    },
3814                ],
3815                line: 1,
3816            })),
3817            resolution: None,
3818        };
3819        ctx.items.push(TopLevel::FnDef(repeat_like.clone()));
3820        ctx.fn_defs.push(repeat_like);
3821
3822        let issues = proof_mode_issues(&ctx);
3823        assert!(
3824            issues.is_empty(),
3825            "expected non-first Int countdown recursion to be accepted, got: {:?}",
3826            issues
3827        );
3828
3829        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
3830        let lean = out
3831            .files
3832            .iter()
3833            .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
3834            .expect("expected generated Lean file");
3835        assert!(lean.contains("def repeatLike__fuel"));
3836        assert!(lean.contains("def repeatLike (char : String) (n : Int) : List String :="));
3837        assert!(lean.contains("repeatLike__fuel ((Int.natAbs n) + 1) char n"));
3838    }
3839
3840    #[test]
3841    fn proof_mode_accepts_negative_guarded_int_ascent() {
3842        let mut ctx = empty_ctx();
3843        let normalize = FnDef {
3844            name: "normalize".to_string(),
3845            line: 1,
3846            params: vec![("angle".to_string(), "Int".to_string())],
3847            return_type: "Int".to_string(),
3848            effects: vec![],
3849            desc: None,
3850            body: Rc::new(FnBody::from_expr(Expr::Match {
3851                subject: Box::new(Expr::BinOp(
3852                    BinOp::Lt,
3853                    Box::new(Expr::Ident("angle".to_string())),
3854                    Box::new(Expr::Literal(Literal::Int(0))),
3855                )),
3856                arms: vec![
3857                    MatchArm {
3858                        pattern: Pattern::Literal(Literal::Bool(true)),
3859                        body: Box::new(Expr::TailCall(Box::new((
3860                            "normalize".to_string(),
3861                            vec![Expr::BinOp(
3862                                BinOp::Add,
3863                                Box::new(Expr::Ident("angle".to_string())),
3864                                Box::new(Expr::Literal(Literal::Int(360))),
3865                            )],
3866                        )))),
3867                    },
3868                    MatchArm {
3869                        pattern: Pattern::Literal(Literal::Bool(false)),
3870                        body: Box::new(Expr::Ident("angle".to_string())),
3871                    },
3872                ],
3873                line: 1,
3874            })),
3875            resolution: None,
3876        };
3877        ctx.items.push(TopLevel::FnDef(normalize.clone()));
3878        ctx.fn_defs.push(normalize);
3879
3880        let issues = proof_mode_issues(&ctx);
3881        assert!(
3882            issues.is_empty(),
3883            "expected negative-guarded Int ascent recursion to be accepted, got: {:?}",
3884            issues
3885        );
3886
3887        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
3888        let lean = out
3889            .files
3890            .iter()
3891            .find_map(|(name, content)| (name == "Verify_mode.lean").then_some(content))
3892            .expect("expected generated Lean file");
3893        assert!(lean.contains("def normalize__fuel"));
3894        assert!(lean.contains("normalize__fuel ((Int.natAbs angle) + 1) angle"));
3895    }
3896
3897    #[test]
3898    fn proof_mode_accepts_single_list_structural_recursion() {
3899        let mut ctx = empty_ctx();
3900        let len = FnDef {
3901            name: "len".to_string(),
3902            line: 1,
3903            params: vec![("xs".to_string(), "List<Int>".to_string())],
3904            return_type: "Int".to_string(),
3905            effects: vec![],
3906            desc: None,
3907            body: Rc::new(FnBody::from_expr(Expr::Match {
3908                subject: Box::new(Expr::Ident("xs".to_string())),
3909                arms: vec![
3910                    MatchArm {
3911                        pattern: Pattern::EmptyList,
3912                        body: Box::new(Expr::Literal(Literal::Int(0))),
3913                    },
3914                    MatchArm {
3915                        pattern: Pattern::Cons("h".to_string(), "t".to_string()),
3916                        body: Box::new(Expr::TailCall(Box::new((
3917                            "len".to_string(),
3918                            vec![Expr::Ident("t".to_string())],
3919                        )))),
3920                    },
3921                ],
3922                line: 1,
3923            })),
3924            resolution: None,
3925        };
3926        ctx.items.push(TopLevel::FnDef(len.clone()));
3927        ctx.fn_defs.push(len);
3928
3929        let issues = proof_mode_issues(&ctx);
3930        assert!(
3931            issues.is_empty(),
3932            "expected List structural recursion to be accepted, got: {:?}",
3933            issues
3934        );
3935    }
3936
3937    #[test]
3938    fn proof_mode_accepts_single_list_structural_recursion_on_nonfirst_param() {
3939        let mut ctx = empty_ctx();
3940        let len_from = FnDef {
3941            name: "lenFrom".to_string(),
3942            line: 1,
3943            params: vec![
3944                ("count".to_string(), "Int".to_string()),
3945                ("xs".to_string(), "List<Int>".to_string()),
3946            ],
3947            return_type: "Int".to_string(),
3948            effects: vec![],
3949            desc: None,
3950            body: Rc::new(FnBody::from_expr(Expr::Match {
3951                subject: Box::new(Expr::Ident("xs".to_string())),
3952                arms: vec![
3953                    MatchArm {
3954                        pattern: Pattern::EmptyList,
3955                        body: Box::new(Expr::Ident("count".to_string())),
3956                    },
3957                    MatchArm {
3958                        pattern: Pattern::Cons("h".to_string(), "t".to_string()),
3959                        body: Box::new(Expr::TailCall(Box::new((
3960                            "lenFrom".to_string(),
3961                            vec![
3962                                Expr::BinOp(
3963                                    BinOp::Add,
3964                                    Box::new(Expr::Ident("count".to_string())),
3965                                    Box::new(Expr::Literal(Literal::Int(1))),
3966                                ),
3967                                Expr::Ident("t".to_string()),
3968                            ],
3969                        )))),
3970                    },
3971                ],
3972                line: 1,
3973            })),
3974            resolution: None,
3975        };
3976        ctx.items.push(TopLevel::FnDef(len_from.clone()));
3977        ctx.fn_defs.push(len_from);
3978
3979        let issues = proof_mode_issues(&ctx);
3980        assert!(
3981            issues.is_empty(),
3982            "expected non-first List structural recursion to be accepted, got: {:?}",
3983            issues
3984        );
3985
3986        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
3987        let lean = generated_lean_file(&out);
3988        assert!(lean.contains("termination_by xs.length"));
3989        assert!(!lean.contains("partial def lenFrom"));
3990    }
3991
3992    #[test]
3993    fn proof_mode_accepts_single_string_pos_advance_recursion() {
3994        let mut ctx = empty_ctx();
3995        let skip_ws = FnDef {
3996            name: "skipWs".to_string(),
3997            line: 1,
3998            params: vec![
3999                ("s".to_string(), "String".to_string()),
4000                ("pos".to_string(), "Int".to_string()),
4001            ],
4002            return_type: "Int".to_string(),
4003            effects: vec![],
4004            desc: None,
4005            body: Rc::new(FnBody::from_expr(Expr::Match {
4006                subject: Box::new(Expr::FnCall(
4007                    Box::new(Expr::Attr(
4008                        Box::new(Expr::Ident("String".to_string())),
4009                        "charAt".to_string(),
4010                    )),
4011                    vec![Expr::Ident("s".to_string()), Expr::Ident("pos".to_string())],
4012                )),
4013                arms: vec![
4014                    MatchArm {
4015                        pattern: Pattern::Constructor("Option.None".to_string(), vec![]),
4016                        body: Box::new(Expr::Ident("pos".to_string())),
4017                    },
4018                    MatchArm {
4019                        pattern: Pattern::Wildcard,
4020                        body: Box::new(Expr::TailCall(Box::new((
4021                            "skipWs".to_string(),
4022                            vec![
4023                                Expr::Ident("s".to_string()),
4024                                Expr::BinOp(
4025                                    BinOp::Add,
4026                                    Box::new(Expr::Ident("pos".to_string())),
4027                                    Box::new(Expr::Literal(Literal::Int(1))),
4028                                ),
4029                            ],
4030                        )))),
4031                    },
4032                ],
4033                line: 1,
4034            })),
4035            resolution: None,
4036        };
4037        ctx.items.push(TopLevel::FnDef(skip_ws.clone()));
4038        ctx.fn_defs.push(skip_ws);
4039
4040        let issues = proof_mode_issues(&ctx);
4041        assert!(
4042            issues.is_empty(),
4043            "expected String+pos recursion to be accepted, got: {:?}",
4044            issues
4045        );
4046
4047        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
4048        let lean = generated_lean_file(&out);
4049        assert!(lean.contains("def skipWs__fuel"));
4050        assert!(!lean.contains("partial def skipWs"));
4051    }
4052
4053    #[test]
4054    fn proof_mode_accepts_mutual_int_countdown_recursion() {
4055        let mut ctx = empty_ctx();
4056        let even = FnDef {
4057            name: "even".to_string(),
4058            line: 1,
4059            params: vec![("n".to_string(), "Int".to_string())],
4060            return_type: "Bool".to_string(),
4061            effects: vec![],
4062            desc: None,
4063            body: Rc::new(FnBody::from_expr(Expr::Match {
4064                subject: Box::new(Expr::Ident("n".to_string())),
4065                arms: vec![
4066                    MatchArm {
4067                        pattern: Pattern::Literal(Literal::Int(0)),
4068                        body: Box::new(Expr::Literal(Literal::Bool(true))),
4069                    },
4070                    MatchArm {
4071                        pattern: Pattern::Wildcard,
4072                        body: Box::new(Expr::TailCall(Box::new((
4073                            "odd".to_string(),
4074                            vec![Expr::BinOp(
4075                                BinOp::Sub,
4076                                Box::new(Expr::Ident("n".to_string())),
4077                                Box::new(Expr::Literal(Literal::Int(1))),
4078                            )],
4079                        )))),
4080                    },
4081                ],
4082                line: 1,
4083            })),
4084            resolution: None,
4085        };
4086        let odd = FnDef {
4087            name: "odd".to_string(),
4088            line: 2,
4089            params: vec![("n".to_string(), "Int".to_string())],
4090            return_type: "Bool".to_string(),
4091            effects: vec![],
4092            desc: None,
4093            body: Rc::new(FnBody::from_expr(Expr::Match {
4094                subject: Box::new(Expr::Ident("n".to_string())),
4095                arms: vec![
4096                    MatchArm {
4097                        pattern: Pattern::Literal(Literal::Int(0)),
4098                        body: Box::new(Expr::Literal(Literal::Bool(false))),
4099                    },
4100                    MatchArm {
4101                        pattern: Pattern::Wildcard,
4102                        body: Box::new(Expr::TailCall(Box::new((
4103                            "even".to_string(),
4104                            vec![Expr::BinOp(
4105                                BinOp::Sub,
4106                                Box::new(Expr::Ident("n".to_string())),
4107                                Box::new(Expr::Literal(Literal::Int(1))),
4108                            )],
4109                        )))),
4110                    },
4111                ],
4112                line: 2,
4113            })),
4114            resolution: None,
4115        };
4116        ctx.items.push(TopLevel::FnDef(even.clone()));
4117        ctx.items.push(TopLevel::FnDef(odd.clone()));
4118        ctx.fn_defs.push(even);
4119        ctx.fn_defs.push(odd);
4120
4121        let issues = proof_mode_issues(&ctx);
4122        assert!(
4123            issues.is_empty(),
4124            "expected mutual Int countdown recursion to be accepted, got: {:?}",
4125            issues
4126        );
4127
4128        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
4129        let lean = generated_lean_file(&out);
4130        assert!(lean.contains("def even__fuel"));
4131        assert!(lean.contains("def odd__fuel"));
4132        assert!(lean.contains("def even (n : Int) : Bool :="));
4133        assert!(lean.contains("even__fuel ((Int.natAbs n) + 1) n"));
4134    }
4135
4136    #[test]
4137    fn proof_mode_accepts_mutual_string_pos_recursion_with_ranked_same_edges() {
4138        let mut ctx = empty_ctx();
4139        let f = FnDef {
4140            name: "f".to_string(),
4141            line: 1,
4142            params: vec![
4143                ("s".to_string(), "String".to_string()),
4144                ("pos".to_string(), "Int".to_string()),
4145            ],
4146            return_type: "Int".to_string(),
4147            effects: vec![],
4148            desc: None,
4149            body: Rc::new(FnBody::from_expr(Expr::Match {
4150                subject: Box::new(Expr::BinOp(
4151                    BinOp::Gte,
4152                    Box::new(Expr::Ident("pos".to_string())),
4153                    Box::new(Expr::Literal(Literal::Int(3))),
4154                )),
4155                arms: vec![
4156                    MatchArm {
4157                        pattern: Pattern::Literal(Literal::Bool(true)),
4158                        body: Box::new(Expr::Ident("pos".to_string())),
4159                    },
4160                    MatchArm {
4161                        pattern: Pattern::Wildcard,
4162                        body: Box::new(Expr::TailCall(Box::new((
4163                            "g".to_string(),
4164                            vec![Expr::Ident("s".to_string()), Expr::Ident("pos".to_string())],
4165                        )))),
4166                    },
4167                ],
4168                line: 1,
4169            })),
4170            resolution: None,
4171        };
4172        let g = FnDef {
4173            name: "g".to_string(),
4174            line: 2,
4175            params: vec![
4176                ("s".to_string(), "String".to_string()),
4177                ("pos".to_string(), "Int".to_string()),
4178            ],
4179            return_type: "Int".to_string(),
4180            effects: vec![],
4181            desc: None,
4182            body: Rc::new(FnBody::from_expr(Expr::Match {
4183                subject: Box::new(Expr::BinOp(
4184                    BinOp::Gte,
4185                    Box::new(Expr::Ident("pos".to_string())),
4186                    Box::new(Expr::Literal(Literal::Int(3))),
4187                )),
4188                arms: vec![
4189                    MatchArm {
4190                        pattern: Pattern::Literal(Literal::Bool(true)),
4191                        body: Box::new(Expr::Ident("pos".to_string())),
4192                    },
4193                    MatchArm {
4194                        pattern: Pattern::Wildcard,
4195                        body: Box::new(Expr::TailCall(Box::new((
4196                            "f".to_string(),
4197                            vec![
4198                                Expr::Ident("s".to_string()),
4199                                Expr::BinOp(
4200                                    BinOp::Add,
4201                                    Box::new(Expr::Ident("pos".to_string())),
4202                                    Box::new(Expr::Literal(Literal::Int(1))),
4203                                ),
4204                            ],
4205                        )))),
4206                    },
4207                ],
4208                line: 2,
4209            })),
4210            resolution: None,
4211        };
4212        ctx.items.push(TopLevel::FnDef(f.clone()));
4213        ctx.items.push(TopLevel::FnDef(g.clone()));
4214        ctx.fn_defs.push(f);
4215        ctx.fn_defs.push(g);
4216
4217        let issues = proof_mode_issues(&ctx);
4218        assert!(
4219            issues.is_empty(),
4220            "expected mutual String+pos recursion to be accepted, got: {:?}",
4221            issues
4222        );
4223
4224        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
4225        let lean = generated_lean_file(&out);
4226        assert!(lean.contains("def f__fuel"));
4227        assert!(lean.contains("def g__fuel"));
4228        assert!(!lean.contains("partial def f"));
4229    }
4230
4231    #[test]
4232    fn proof_mode_accepts_mutual_ranked_sizeof_recursion() {
4233        let mut ctx = empty_ctx();
4234        let f = FnDef {
4235            name: "f".to_string(),
4236            line: 1,
4237            params: vec![("xs".to_string(), "List<Int>".to_string())],
4238            return_type: "Int".to_string(),
4239            effects: vec![],
4240            desc: None,
4241            body: Rc::new(FnBody::from_expr(Expr::TailCall(Box::new((
4242                "g".to_string(),
4243                vec![
4244                    Expr::Literal(Literal::Str("acc".to_string())),
4245                    Expr::Ident("xs".to_string()),
4246                ],
4247            ))))),
4248            resolution: None,
4249        };
4250        let g = FnDef {
4251            name: "g".to_string(),
4252            line: 2,
4253            params: vec![
4254                ("acc".to_string(), "String".to_string()),
4255                ("xs".to_string(), "List<Int>".to_string()),
4256            ],
4257            return_type: "Int".to_string(),
4258            effects: vec![],
4259            desc: None,
4260            body: Rc::new(FnBody::from_expr(Expr::Match {
4261                subject: Box::new(Expr::Ident("xs".to_string())),
4262                arms: vec![
4263                    MatchArm {
4264                        pattern: Pattern::EmptyList,
4265                        body: Box::new(Expr::Literal(Literal::Int(0))),
4266                    },
4267                    MatchArm {
4268                        pattern: Pattern::Cons("h".to_string(), "t".to_string()),
4269                        body: Box::new(Expr::TailCall(Box::new((
4270                            "f".to_string(),
4271                            vec![Expr::Ident("t".to_string())],
4272                        )))),
4273                    },
4274                ],
4275                line: 2,
4276            })),
4277            resolution: None,
4278        };
4279        ctx.items.push(TopLevel::FnDef(f.clone()));
4280        ctx.items.push(TopLevel::FnDef(g.clone()));
4281        ctx.fn_defs.push(f);
4282        ctx.fn_defs.push(g);
4283
4284        let issues = proof_mode_issues(&ctx);
4285        assert!(
4286            issues.is_empty(),
4287            "expected mutual ranked-sizeOf recursion to be accepted, got: {:?}",
4288            issues
4289        );
4290
4291        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
4292        let lean = generated_lean_file(&out);
4293        assert!(lean.contains("mutual"));
4294        assert!(lean.contains("def f__fuel"));
4295        assert!(lean.contains("def g__fuel"));
4296        assert!(!lean.contains("partial def f"));
4297        assert!(!lean.contains("partial def g"));
4298    }
4299
4300    #[test]
4301    fn proof_mode_rejects_recursive_pure_functions() {
4302        let mut ctx = empty_ctx();
4303        let recursive_fn = FnDef {
4304            name: "loop".to_string(),
4305            line: 1,
4306            params: vec![("n".to_string(), "Int".to_string())],
4307            return_type: "Int".to_string(),
4308            effects: vec![],
4309            desc: None,
4310            body: Rc::new(FnBody::from_expr(Expr::FnCall(
4311                Box::new(Expr::Ident("loop".to_string())),
4312                vec![Expr::Ident("n".to_string())],
4313            ))),
4314            resolution: None,
4315        };
4316        ctx.items.push(TopLevel::FnDef(recursive_fn.clone()));
4317        ctx.fn_defs.push(recursive_fn);
4318
4319        let issues = proof_mode_issues(&ctx);
4320        assert!(
4321            issues.iter().any(|i| i.contains("outside proof subset")),
4322            "expected recursive function blocker, got: {:?}",
4323            issues
4324        );
4325    }
4326
4327    #[test]
4328    fn proof_mode_allows_recursive_types() {
4329        let mut ctx = empty_ctx();
4330        let recursive_type = TypeDef::Sum {
4331            name: "Node".to_string(),
4332            variants: vec![TypeVariant {
4333                name: "Cons".to_string(),
4334                fields: vec!["Node".to_string()],
4335            }],
4336            line: 1,
4337        };
4338        ctx.items.push(TopLevel::TypeDef(recursive_type.clone()));
4339        ctx.type_defs.push(recursive_type);
4340
4341        let issues = proof_mode_issues(&ctx);
4342        assert!(
4343            issues
4344                .iter()
4345                .all(|i| !i.contains("recursive types require unsafe DecidableEq shim")),
4346            "did not expect recursive type blocker, got: {:?}",
4347            issues
4348        );
4349    }
4350
4351    #[test]
4352    fn law_auto_example_exports_real_proof_artifacts() {
4353        let ctx = ctx_from_source(
4354            include_str!("../../../examples/formal/law_auto.av"),
4355            "law_auto",
4356        );
4357        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
4358        let lean = generated_lean_file(&out);
4359
4360        assert!(lean.contains("theorem add_law_commutative :"));
4361        assert!(lean.contains("theorem id'_law_reflexive : ∀ (x : Int), x = x := by"));
4362        assert!(lean.contains("theorem incCount_law_keyPresent :"));
4363        assert!(lean.contains("AverMap.has_set_self"));
4364        assert!(lean.contains("theorem add_law_commutative_sample_1 :"));
4365        assert!(lean.contains(":= by native_decide"));
4366    }
4367
4368    #[test]
4369    fn json_example_stays_inside_proof_subset() {
4370        let ctx = ctx_from_source(include_str!("../../../examples/data/json.av"), "json");
4371        let issues = proof_mode_issues(&ctx);
4372        assert!(
4373            issues.is_empty(),
4374            "expected json example to stay inside proof subset, got: {:?}",
4375            issues
4376        );
4377    }
4378
4379    #[test]
4380    fn json_example_uses_total_defs_and_domain_guarded_laws_in_proof_mode() {
4381        let ctx = ctx_from_source(include_str!("../../../examples/data/json.av"), "json");
4382        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
4383        let lean = generated_lean_file(&out);
4384
4385        assert!(!lean.contains("partial def"));
4386        assert!(lean.contains("def skipWs__fuel"));
4387        assert!(lean.contains("def parseValue__fuel"));
4388        assert!(lean.contains("def toString' (j : Json) : String :="));
4389        assert!(
4390            lean.contains(
4391                "def averMeasureJsonEntries_String (items : List (String × Json)) : Nat :="
4392            )
4393        );
4394        assert!(lean.contains(
4395            "| .jsonObject x0 => (averMeasureJsonEntries_String (AverMap.entries x0)) + 1"
4396        ));
4397        assert!(lean.contains("-- when jsonRoundtripSafe j"));
4398        assert!(!lean.contains("-- hint: verify law '"));
4399        assert!(!lean.contains("private theorem toString'_law_parseRoundtrip_aux"));
4400        assert!(
4401            lean.contains(
4402                "theorem toString'_law_parseRoundtrip : ∀ (j : Json), j = Json.jsonNull ∨"
4403            )
4404        );
4405        assert!(lean.contains(
4406            "jsonRoundtripSafe j = true -> fromString (toString' j) = Except.ok j := by"
4407        ));
4408        assert!(
4409            lean.contains("theorem finishFloat_law_fromCanonicalFloat : ∀ (f : Float), f = 3.5 ∨")
4410        );
4411        assert!(lean.contains("theorem finishInt_law_fromCanonicalInt_checked_domain :"));
4412        assert!(lean.contains(
4413            "theorem toString'_law_parseValueRoundtrip : ∀ (j : Json), j = Json.jsonNull ∨"
4414        ));
4415        assert!(lean.contains("theorem toString'_law_parseRoundtrip_sample_1 :"));
4416        assert!(lean.contains(
4417            "example : fromString \"null\" = Except.ok Json.jsonNull := by native_decide"
4418        ));
4419    }
4420
4421    #[test]
4422    fn transpile_injects_builtin_network_types_and_int_list_get_support() {
4423        let ctx = ctx_from_source(
4424            r#"
4425fn firstOrMissing(xs: List<String>) -> Result<String, String>
4426    Option.toResult(List.get(xs, -1), "missing")
4427
4428fn defaultHeader() -> Header
4429    Header(name = "Content-Type", value = "application/json")
4430
4431fn mkResponse(body: String) -> HttpResponse
4432    HttpResponse(status = 200, body = body, headers = [defaultHeader()])
4433
4434fn requestPath(req: HttpRequest) -> String
4435    req.path
4436
4437fn connPort(conn: Tcp.Connection) -> Int
4438    conn.port
4439"#,
4440            "network_helpers",
4441        );
4442        let out = transpile(&ctx);
4443        let lean = generated_lean_file(&out);
4444
4445        assert!(lean.contains("structure Header where"));
4446        assert!(lean.contains("structure HttpResponse where"));
4447        assert!(lean.contains("structure HttpRequest where"));
4448        assert!(lean.contains("structure Tcp_Connection where"));
4449        assert!(lean.contains("port : Int"));
4450        assert!(lean.contains("def get (xs : List α) (i : Int) : Option α :="));
4451        assert!(lean.contains("AverList.get xs (-1)"));
4452    }
4453
4454    #[test]
4455    fn law_auto_example_has_no_sorry_in_proof_mode() {
4456        let ctx = ctx_from_source(
4457            include_str!("../../../examples/formal/law_auto.av"),
4458            "law_auto",
4459        );
4460        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
4461        let lean = generated_lean_file(&out);
4462        assert!(
4463            !lean.contains("sorry"),
4464            "expected law_auto proof export to avoid sorry, got:\n{}",
4465            lean
4466        );
4467    }
4468
4469    #[test]
4470    fn map_example_has_no_sorry_in_proof_mode() {
4471        let ctx = ctx_from_source(include_str!("../../../examples/data/map.av"), "map");
4472        let issues = proof_mode_issues(&ctx);
4473        assert!(
4474            issues.is_empty(),
4475            "expected map example to stay inside proof subset, got: {:?}",
4476            issues
4477        );
4478
4479        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
4480        let lean = generated_lean_file(&out);
4481        // After codegen change: universal theorems that can't be auto-proved get sorry
4482        assert!(lean.contains("theorem incCount_law_trackedCountStepsByOne :"));
4483        assert!(lean.contains("sorry"));
4484        // Universal theorems that can't be auto-proved now get sorry instead of being omitted
4485        assert!(lean.contains("theorem countWords_law_presenceMatchesContains_sample_1 :"));
4486        assert!(lean.contains("theorem countWords_law_trackedWordCount_sample_1 :"));
4487        assert!(lean.contains("AverMap.has_set_self"));
4488        assert!(lean.contains("AverMap.get_set_self"));
4489    }
4490
4491    #[test]
4492    fn spec_laws_example_has_no_sorry_in_proof_mode() {
4493        let ctx = ctx_from_source(
4494            include_str!("../../../examples/formal/spec_laws.av"),
4495            "spec_laws",
4496        );
4497        let issues = proof_mode_issues(&ctx);
4498        assert!(
4499            issues.is_empty(),
4500            "expected spec_laws example to stay inside proof subset, got: {:?}",
4501            issues
4502        );
4503
4504        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
4505        let lean = generated_lean_file(&out);
4506        assert!(
4507            !lean.contains("sorry"),
4508            "expected spec_laws proof export to avoid sorry, got:\n{}",
4509            lean
4510        );
4511        assert!(lean.contains("theorem absVal_eq_absValSpec :"));
4512        assert!(lean.contains("theorem clampNonNegative_eq_clampNonNegativeSpec :"));
4513    }
4514
4515    #[test]
4516    fn rle_example_exports_sampled_roundtrip_laws_without_sorry() {
4517        let ctx = ctx_from_source(include_str!("../../../examples/data/rle.av"), "rle");
4518        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
4519        let lean = generated_lean_file(&out);
4520
4521        assert!(
4522            lean.contains("sorry"),
4523            "expected rle proof export to contain sorry for unproved universal theorems"
4524        );
4525        assert!(lean.contains(
4526            "theorem encode_law_roundtrip_sample_1 : decode (encode []) = [] := by native_decide"
4527        ));
4528        assert!(lean.contains(
4529            "theorem encodeString_law_string_roundtrip_sample_1 : decodeString (encodeString \"\") = \"\" := by native_decide"
4530        ));
4531    }
4532
4533    #[test]
4534    fn fibonacci_example_uses_fuelized_int_countdown_in_proof_mode() {
4535        let ctx = ctx_from_source(
4536            include_str!("../../../examples/data/fibonacci.av"),
4537            "fibonacci",
4538        );
4539        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
4540        let lean = generated_lean_file(&out);
4541
4542        assert!(lean.contains("def fibTR__fuel"));
4543        assert!(lean.contains("def fibTR (n : Int) (a : Int) (b : Int) : Int :="));
4544        assert!(lean.contains("fibTR__fuel ((Int.natAbs n) + 1) n a b"));
4545        assert!(!lean.contains("partial def fibTR"));
4546    }
4547
4548    #[test]
4549    fn fibonacci_example_stays_inside_proof_subset() {
4550        let ctx = ctx_from_source(
4551            include_str!("../../../examples/data/fibonacci.av"),
4552            "fibonacci",
4553        );
4554        let issues = proof_mode_issues(&ctx);
4555        assert!(
4556            issues.is_empty(),
4557            "expected fibonacci example to stay inside proof subset, got: {:?}",
4558            issues
4559        );
4560    }
4561
4562    #[test]
4563    fn fibonacci_example_matches_general_linear_recurrence_shapes() {
4564        let ctx = ctx_from_source(
4565            include_str!("../../../examples/data/fibonacci.av"),
4566            "fibonacci",
4567        );
4568        let fib = ctx.fn_defs.iter().find(|fd| fd.name == "fib").unwrap();
4569        let fib_tr = ctx.fn_defs.iter().find(|fd| fd.name == "fibTR").unwrap();
4570        let fib_spec = ctx.fn_defs.iter().find(|fd| fd.name == "fibSpec").unwrap();
4571
4572        assert!(recurrence::detect_tailrec_int_linear_pair_wrapper(fib).is_some());
4573        assert!(recurrence::detect_tailrec_int_linear_pair_worker(fib_tr).is_some());
4574        assert!(recurrence::detect_second_order_int_linear_recurrence(fib_spec).is_some());
4575    }
4576
4577    #[test]
4578    fn fibonacci_example_auto_proves_general_linear_recurrence_spec_law() {
4579        let ctx = ctx_from_source(
4580            include_str!("../../../examples/data/fibonacci.av"),
4581            "fibonacci",
4582        );
4583        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
4584        let lean = generated_lean_file(&out);
4585
4586        assert!(lean.contains("private def fibSpec__nat : Nat -> Int"));
4587        assert!(!lean.contains("partial def fibSpec"));
4588        assert!(lean.contains("private theorem fib_eq_fibSpec__worker_nat_shift"));
4589        assert!(lean.contains("private theorem fib_eq_fibSpec__helper_nat"));
4590        assert!(lean.contains("private theorem fib_eq_fibSpec__helper_seed"));
4591        assert!(lean.contains("theorem fib_eq_fibSpec : ∀ (n : Int), fib n = fibSpec n := by"));
4592        assert!(!lean.contains(
4593            "-- universal theorem fib_eq_fibSpec omitted: sampled law shape is not auto-proved yet"
4594        ));
4595    }
4596
4597    #[test]
4598    fn pell_like_example_auto_proves_same_general_shape() {
4599        let ctx = ctx_from_source(
4600            r#"
4601module Pell
4602    intent =
4603        "linear recurrence probe"
4604
4605fn pellTR(n: Int, a: Int, b: Int) -> Int
4606    match n
4607        0 -> a
4608        _ -> pellTR(n - 1, b, a + 2 * b)
4609
4610fn pell(n: Int) -> Int
4611    match n < 0
4612        true -> 0
4613        false -> pellTR(n, 0, 1)
4614
4615fn pellSpec(n: Int) -> Int
4616    match n < 0
4617        true -> 0
4618        false -> match n
4619            0 -> 0
4620            1 -> 1
4621            _ -> pellSpec(n - 2) + 2 * pellSpec(n - 1)
4622
4623verify pell law pellSpec
4624    given n: Int = [0, 1, 2, 3]
4625    pell(n) => pellSpec(n)
4626"#,
4627            "pell",
4628        );
4629        let issues = proof_mode_issues(&ctx);
4630        assert!(
4631            issues.is_empty(),
4632            "expected pell example to stay inside proof subset, got: {:?}",
4633            issues
4634        );
4635
4636        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
4637        let lean = generated_lean_file(&out);
4638        assert!(lean.contains("private def pellSpec__nat : Nat -> Int"));
4639        assert!(lean.contains("private theorem pell_eq_pellSpec__worker_nat_shift"));
4640        assert!(lean.contains("theorem pell_eq_pellSpec : ∀ (n : Int), pell n = pellSpec n := by"));
4641        assert!(!lean.contains(
4642            "-- universal theorem pell_eq_pellSpec omitted: sampled law shape is not auto-proved yet"
4643        ));
4644    }
4645
4646    #[test]
4647    fn nonlinear_pair_state_recurrence_is_not_auto_proved_as_linear_shape() {
4648        let ctx = ctx_from_source(
4649            r#"
4650module WeirdRec
4651    intent =
4652        "reject nonlinear pair-state recurrence from linear recurrence prover"
4653
4654fn weirdTR(n: Int, a: Int, b: Int) -> Int
4655    match n
4656        0 -> a
4657        _ -> weirdTR(n - 1, b, a * b)
4658
4659fn weird(n: Int) -> Int
4660    match n < 0
4661        true -> 0
4662        false -> weirdTR(n, 0, 1)
4663
4664fn weirdSpec(n: Int) -> Int
4665    match n < 0
4666        true -> 0
4667        false -> match n
4668            0 -> 0
4669            1 -> 1
4670            _ -> weirdSpec(n - 1) * weirdSpec(n - 2)
4671
4672verify weird law weirdSpec
4673    given n: Int = [0, 1, 2, 3]
4674    weird(n) => weirdSpec(n)
4675"#,
4676            "weirdrec",
4677        );
4678        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
4679        let lean = generated_lean_file(&out);
4680
4681        // After codegen change: emit sorry instead of omitting universal theorems
4682        assert!(lean.contains("sorry"));
4683        assert!(!lean.contains("private theorem weird_eq_weirdSpec__worker_nat_shift"));
4684        assert!(lean.contains("theorem weird_eq_weirdSpec_sample_1 :"));
4685    }
4686
4687    #[test]
4688    fn date_example_stays_inside_proof_subset() {
4689        let ctx = ctx_from_source(include_str!("../../../examples/data/date.av"), "date");
4690        let issues = proof_mode_issues(&ctx);
4691        assert!(
4692            issues.is_empty(),
4693            "expected date example to stay inside proof subset, got: {:?}",
4694            issues
4695        );
4696
4697        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
4698        let lean = generated_lean_file(&out);
4699        assert!(!lean.contains("partial def"));
4700        assert!(lean.contains("def parseIntSlice (s : String) (from' : Int) (to : Int) : Int :="));
4701    }
4702
4703    #[test]
4704    fn temperature_example_stays_inside_proof_subset() {
4705        let ctx = ctx_from_source(
4706            include_str!("../../../examples/core/temperature.av"),
4707            "temperature",
4708        );
4709        let issues = proof_mode_issues(&ctx);
4710        assert!(
4711            issues.is_empty(),
4712            "expected temperature example to stay inside proof subset, got: {:?}",
4713            issues
4714        );
4715
4716        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
4717        let lean = generated_lean_file(&out);
4718        assert!(!lean.contains("partial def"));
4719        assert!(
4720            lean.contains("example : celsiusToFahr 0.0 = 32.0 := by native_decide"),
4721            "expected verify examples to survive proof export, got:\n{}",
4722            lean
4723        );
4724    }
4725
4726    #[test]
4727    fn quicksort_example_stays_inside_proof_subset() {
4728        let ctx = ctx_from_source(
4729            include_str!("../../../examples/data/quicksort.av"),
4730            "quicksort",
4731        );
4732        let issues = proof_mode_issues(&ctx);
4733        assert!(
4734            issues.is_empty(),
4735            "expected quicksort example to stay inside proof subset, got: {:?}",
4736            issues
4737        );
4738
4739        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
4740        let lean = generated_lean_file(&out);
4741        assert!(lean.contains("def isOrderedFrom"));
4742        assert!(!lean.contains("partial def isOrderedFrom"));
4743        assert!(lean.contains("termination_by xs.length"));
4744    }
4745
4746    #[test]
4747    fn grok_s_language_example_uses_total_ranked_sizeof_mutual_recursion() {
4748        let ctx = ctx_from_source(
4749            include_str!("../../../examples/core/grok_s_language.av"),
4750            "grok_s_language",
4751        );
4752        let issues = proof_mode_issues(&ctx);
4753        assert!(
4754            issues.is_empty(),
4755            "expected grok_s_language example to stay inside proof subset, got: {:?}",
4756            issues
4757        );
4758
4759        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
4760        let lean = generated_lean_file(&out);
4761        assert!(lean.contains("mutual"));
4762        assert!(lean.contains("def eval__fuel"));
4763        assert!(lean.contains("def parseListItems__fuel"));
4764        assert!(!lean.contains("partial def eval"));
4765        assert!(!lean.contains("termination_by (sizeOf e,"));
4766        assert!(lean.contains("-- when validSymbolNames e"));
4767        assert!(!lean.contains("private theorem toString'_law_parseRoundtrip_aux"));
4768        assert!(lean.contains(
4769            "theorem toString'_law_parseRoundtrip : ∀ (e : Sexpr), e = Sexpr.atomNum 42 ∨"
4770        ));
4771        assert!(
4772            lean.contains("validSymbolNames e = true -> parse (toString' e) = Except.ok e := by")
4773        );
4774        assert!(lean.contains("theorem toString'_law_parseSexprRoundtrip :"));
4775        assert!(lean.contains("theorem toString'_law_parseRoundtrip_sample_1 :"));
4776    }
4777
4778    #[test]
4779    fn lambda_example_keeps_only_eval_outside_proof_subset() {
4780        let ctx = ctx_from_source(include_str!("../../../examples/core/lambda.av"), "lambda");
4781        let issues = proof_mode_issues(&ctx);
4782        assert_eq!(
4783            issues,
4784            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()]
4785        );
4786
4787        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
4788        let lean = generated_lean_file(&out);
4789        assert!(lean.contains("def termToString__fuel"));
4790        assert!(lean.contains("def subst__fuel"));
4791        assert!(lean.contains("def countS__fuel"));
4792        assert!(!lean.contains("partial def termToString"));
4793        assert!(!lean.contains("partial def subst"));
4794        assert!(!lean.contains("partial def countS"));
4795        assert!(lean.contains("partial def eval"));
4796    }
4797
4798    #[test]
4799    fn mission_control_example_stays_inside_proof_subset() {
4800        let ctx = ctx_from_source(
4801            include_str!("../../../examples/apps/mission_control.av"),
4802            "mission_control",
4803        );
4804        let issues = proof_mode_issues(&ctx);
4805        assert!(
4806            issues.is_empty(),
4807            "expected mission_control example to stay inside proof subset, got: {:?}",
4808            issues
4809        );
4810
4811        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
4812        let lean = generated_lean_file(&out);
4813        assert!(!lean.contains("partial def normalizeAngle"));
4814        assert!(lean.contains("def normalizeAngle__fuel"));
4815    }
4816
4817    #[test]
4818    fn notepad_store_example_stays_inside_proof_subset() {
4819        let ctx = ctx_from_source(
4820            include_str!("../../../examples/apps/notepad/store.av"),
4821            "notepad_store",
4822        );
4823        let issues = proof_mode_issues(&ctx);
4824        assert!(
4825            issues.is_empty(),
4826            "expected notepad/store example to stay inside proof subset, got: {:?}",
4827            issues
4828        );
4829
4830        let out = transpile_for_proof_mode(&ctx, VerifyEmitMode::NativeDecide);
4831        let lean = generated_lean_file(&out);
4832        assert!(lean.contains("def deserializeLine (line : String) : Except String Note :=\n  do"));
4833        assert!(lean.contains("Except String (List Note)"));
4834        assert!(!lean.contains("partial def deserializeLine"));
4835        assert!(lean.contains("-- when noteRoundtripSafe note"));
4836        assert!(lean.contains("-- when notesRoundtripSafe notes"));
4837        assert!(lean.contains(
4838            "theorem serializeLine_law_lineRoundtrip : ∀ (note : Note), note = { id' := 1, title := \"Hello\", body := \"World\" : Note } ∨"
4839        ));
4840        assert!(lean.contains(
4841            "theorem serializeLines_law_notesRoundtrip : ∀ (notes : List Note), notes = [] ∨"
4842        ));
4843        assert!(lean.contains("notesRoundtripSafe notes = true ->"));
4844        assert!(lean.contains("parseNotes (s!\"{String.intercalate \"\\n\" (serializeLines notes)}\\n\") = Except.ok notes"));
4845        assert!(lean.contains("theorem serializeLine_law_lineRoundtrip_sample_1 :"));
4846        assert!(lean.contains("theorem serializeLines_law_notesRoundtrip_sample_1 :"));
4847    }
4848}