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