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