| /- | |
| Copyright (c) 2025 Lean FRO LLC. All rights reserved. | |
| Released under Apache 2.0 license as described in the file LICENSE. | |
| Authors: Vladimir Gladshtein, Sebastian Graf | |
| -/ | |
| import Lean | |
| import Std.WP | |
| set_option experimental.vcgen true | |
| /-! | |
| # Do-logic tests for `vcgen` | |
| Ported from `tests/elab/doLogicTests.lean`, keeping only `mvcgen`-specific test cases | |
| and replacing `mvcgen` with `vcgen` where possible. | |
| Tests that are not yet working with `vcgen` keep the original `mvcgen`-based proof. | |
| The deprecation warning emitted by `mvcgen` indicates which tests still need migration. | |
| Tests whose proofs do not mention `mvcgen`/`vcgen` (manual `mspec`/`mintro` proofs) | |
| are intentionally not ported. | |
| -/ | |
| open Lean Order Meta Elab Tactic Sym Std WP | |
| set_option grind.warning false | |
| set_option warn.sorry false | |
| set_option backward.do.legacy false | |
| namespace Code | |
| def fib_impl (n : Nat) : Id Nat := do | |
| if n = 0 then return 0 | |
| let mut a := 0 | |
| let mut b := 1 | |
| for _ in [1:n] do | |
| let a' := a | |
| a := b | |
| b := a' + b | |
| return b | |
| @[simp, grind =] | |
| def fib_spec : Nat → Nat | |
| | 0 => 0 | |
| | 1 => 1 | |
| | n+2 => fib_spec n + fib_spec (n+1) | |
| abbrev AppState := Nat × Nat | |
| def mkFreshNat [Monad m] [MonadStateOf AppState m] : m Nat := do | |
| let n ← Prod.fst <$> get | |
| modify (fun s => (s.1 + 1, s.2)) | |
| pure n | |
| def mkFreshPair : StateM AppState (Nat × Nat) := do | |
| let a ← mkFreshNat | |
| let b ← mkFreshNat | |
| pure (a, b) | |
| def sum_loop : Id Nat := do | |
| let mut x := 0 | |
| for i in [1:5] do x := x + i | |
| return x | |
| def throwing_loop : ExceptT Nat (StateT Nat Id) Nat := do | |
| let mut x := 0 | |
| let s ← get | |
| for i in [1:s] do { x := x + i; if x > 4 then throw 42 } | |
| (set 1 : ExceptT Nat (StateT Nat Id) PUnit) | |
| return x | |
| def breaking_loop : StateT Nat Id Nat := do | |
| let mut x := 0 | |
| let s ← get | |
| for i in [1:s] do { x := x + i; if x > 4 then break } | |
| set 1 | |
| return x | |
| def returning_loop : StateT Nat Id Nat := do | |
| let mut x := 0 | |
| let s ← get | |
| for i in [1:s] do { x := x + i; if x > 4 then return 42 } | |
| set 1 | |
| return x | |
| def unfold_to_expose_match : StateM Nat Nat := | |
| (some get).getD (pure 3) | |
| end Code | |
| namespace Automated | |
| open Code | |
| theorem fib_triple : ⦃ True ⦄ fib_impl n ⦃ fun r => r = fib_spec n ⦄ := by | |
| unfold fib_impl | |
| vcgen | |
| case inv1 => exact fun pref _ ⟨a, b⟩ => | |
| a = fib_spec pref.length ∧ b = fib_spec (pref.length + 1) | |
| all_goals grind | |
| theorem fib_triple_finish : ⦃ True ⦄ fib_impl n ⦃ fun r => r = fib_spec n ⦄ := by | |
| vcgen [fib_impl] invariants | |
| | inv1 => fun pref _ ⟨a, b⟩ => a = fib_spec pref.length ∧ b = fib_spec (pref.length + 1) | |
| with finish | |
| theorem fib_triple_step : ⦃ True ⦄ fib_impl n ⦃ fun r => r = fib_spec n ⦄ := by | |
| unfold fib_impl | |
| vcgen (stepLimit := some 14) | |
| case inv1 => exact fun pref _ ⟨a, b⟩ => | |
| a = fib_spec pref.length ∧ b = fib_spec (pref.length + 1) | |
| all_goals grind | |
| attribute [local spec] fib_triple in | |
| theorem fib_triple_attr : ⦃ True ⦄ fib_impl n ⦃ fun r => r = fib_spec n ⦄ := by | |
| vcgen | |
| attribute [local spec] fib_triple in | |
| theorem fib_triple_erase : ⦃ True ⦄ fib_impl n ⦃fun r => r = fib_spec n⦄ := by | |
| vcgen (errorOnMissingSpec := false) [-fib_triple] | |
| fail_if_success done | |
| admit | |
| theorem fib_impl_vcs | |
| (Q : Nat → Nat → Prop) | |
| (E : EStack⟨⟩) | |
| (I : (n : Nat) → (_ : ¬n = 0) → | |
| Invariant Nat (Prod Nat Nat) Prop) | |
| (ret : Q 0 0) | |
| (loop_pre : ∀ n (hn : ¬n = 0), (I n hn) [] (ForIn.toList [1:n]) (0, 1)) | |
| (loop_post : ∀ n (hn : ¬n = 0) r, (I n hn) (ForIn.toList [1:n]) [] r ⊑ Q n r.2) | |
| (loop_step : ∀ n (hn : ¬n = 0) r pref cur suff | |
| (_h : ForIn.toList [1:n] = pref ++ cur :: suff), | |
| (I n hn) pref (cur::suff) r ⊑ (I n hn) (pref ++ [cur]) suff (r.2, r.1+r.2)) | |
| : wp (fib_impl n) (Q n) E := by | |
| vcgen [fib_impl] | |
| case inv1 h => exact I n h | |
| case vc1 h => subst h; apply_rules [ret] | |
| case vc2 h => apply_rules [loop_pre] | |
| case vc3 h a b hinv => exact loop_post n h (a, b) hinv | |
| case vc4 h pref cur suff _hsplit a b₀ _hinv => | |
| -- The `ForInStep.yield` that the step's postcondition matches on and the projections of the | |
| -- state pair are reduced, and the loop's two mutable variables reach the verification | |
| -- condition as separate binders. The new value of `b` is the let-variable `b := a + b₀`. | |
| guard_target =ₛ I n h (pref ++ [cur]) suff (b₀, b) | |
| exact loop_step n h (a, b₀) pref cur suff _hsplit _hinv | |
| @[spec] | |
| theorem mkFreshNat_spec [Monad m] [Assertion Pred] [Assertion EPosts] [WPMonad m Pred EPosts] : | |
| ⦃ fun s => ⌜s.1 = n ∧ s.2 = o⌝ ⦄ | |
| (mkFreshNat : StateT AppState m Nat) | |
| ⦃ fun r s => ⌜r = n ∧ s.1 = n + 1 ∧ s.2 = o⌝ ⦄ := by | |
| vcgen [mkFreshNat] <;> simp_all | |
| theorem erase_unfold [Monad m] [Assertion Pred] [Assertion EPosts] [WPMonad m Pred EPosts] : | |
| ⦃fun s => ⌜s.1 = n ∧ s.2 = o⌝ ⦄ | |
| (mkFreshNat : StateT AppState m Nat) | |
| ⦃fun r s => ⌜r = n ∧ s.1 = n + 1 ∧ s.2 = o⌝ ⦄ := by | |
| unfold mkFreshNat | |
| vcgen (errorOnMissingSpec := false) [-modify] | |
| simp_all [-WPMonad.wp_modify_StateT_apply_eq] | |
| fail_if_success done | |
| admit | |
| theorem add_unfold [Monad m] [Assertion Pred] [Assertion EPosts] [WPMonad m Pred EPosts] : | |
| ⦃ fun s => ⌜s.1 = n ∧ s.2 = o⌝ ⦄ | |
| (mkFreshNat : StateT AppState m Nat) | |
| ⦃ fun r s => ⌜r = n ∧ s.1 = n + 1 ∧ s.2 = o⌝ ⦄ := by | |
| vcgen [mkFreshNat] <;> simp_all | |
| theorem mkFreshPair_triple : | |
| ⦃ fun _ => True ⦄ mkFreshPair ⦃ fun (p : Nat × Nat) => ⌜p.1 ≠ p.2⌝ ⦄ := by | |
| vcgen [mkFreshPair] <;> simp_all | |
| theorem sum_loop_spec : ⦃ True ⦄ sum_loop ⦃ fun r => r < 30 ⦄ := by | |
| vcgen [sum_loop] | |
| case inv1 => exact fun pref _ x => x = pref.sum | |
| all_goals grind | |
| theorem throwing_loop_spec : | |
| ⦃fun s => s = 4⦄ | |
| throwing_loop | |
| ⦃fun _ _ => False; | |
| estack⟨fun e s => e = 42 ∧ s = 4⟩⦄ := by | |
| vcgen [throwing_loop] | |
| case inv1 => exact fun _ suff r s => r ≤ 4 ∧ s = 4 ∧ r + suff.sum > 4 | |
| all_goals (simp_all; try grind) | |
| theorem test_loop_break : | |
| ⦃ fun s => s = 42 ⦄ breaking_loop ⦃ fun r s => r > 4 ∧ s = 1 ⦄ := by | |
| vcgen [breaking_loop] | |
| case inv1 => exact fun pref _ r s => (r ≤ 4 ∧ r = pref.sum ∨ r > 4) ∧ s = 42 | |
| all_goals grind | |
| theorem test_loop_early_return : | |
| ⦃ fun s => s = 4 ⦄ returning_loop ⦃ fun r s => r = 42 ∧ s = 4 ⦄ := by | |
| vcgen [returning_loop] | |
| case inv1 => exact fun pref _ r s => (r.1 = none ∧ r.2 = pref.sum ∧ r.2 ≤ 4 ∨ r.1 = some 42 ∧ r.2 > 4) ∧ s = 4 | |
| all_goals grind | |
| theorem unfold_to_expose_match_spec : | |
| ⦃ fun s => s = 4 ⦄ | |
| unfold_to_expose_match | |
| ⦃ fun r => ⌜r = 4⌝ ⦄ := by | |
| vcgen [unfold_to_expose_match, Option.getD] | |
| theorem test_match_splitting {mo : Option Nat} (h : mo = some 4) : | |
| ⦃ fun _ => True ⦄ | |
| (match mo with | |
| | some n => (set n : StateM Nat PUnit) | |
| | none => set 0) | |
| ⦃ fun _ s => s = 4 ⦄ := by | |
| vcgen <;> simp_all | |
| theorem test_sum : | |
| ⦃ True ⦄ | |
| (do | |
| let mut x := 0 | |
| for i in [1:5] do | |
| x := x + i | |
| pure x : Id _) | |
| ⦃ fun r => r < 30 ⦄ := by | |
| vcgen | |
| case inv1 => exact fun pref _ x => x = pref.sum | |
| all_goals grind | |
| theorem mspec_forwards_mvars {n : Nat} : | |
| ⦃True⦄ | |
| (do | |
| for i in [2:n] do | |
| if n < i * i then | |
| return 1 | |
| return 1 : Id Nat) | |
| ⦃fun r => True⦄ := by | |
| vcgen | |
| all_goals admit | |
| def check_all (p : Nat → Prop) [DecidablePred p] (n : Nat) : Bool := Id.run do | |
| for i in [0:n] do | |
| if ¬ p i then | |
| return false | |
| return true | |
| example (p : Nat → Prop) [DecidablePred p] (n : Nat) : | |
| (∀ i, i < n → p i) ↔ check_all p n := by | |
| generalize h : check_all p n = x | |
| apply Id.of_run_eq_wp h | |
| vcgen | |
| case inv1 => | |
| exact Invariant.withEarlyReturnNewDo | |
| (onReturn := fun ret _ => ⌜ret = false ∧ ¬ ∀ i < n, p i⌝) | |
| (onContinue := fun pref _ _ => ⌜∀ i, i ∈ pref → p i⌝) | |
| all_goals simp_all [-Classical.not_forall]; try grind | |
| def nodup (l : List Int) : Bool := Id.run do | |
| let mut seen : Std.HashSet Int := ∅ | |
| for x in l do | |
| if x ∈ seen then | |
| return false | |
| seen := seen.insert x | |
| return true | |
| theorem nodup_correct (l : List Int) : nodup l ↔ l.Nodup := by | |
| generalize h : nodup l = r | |
| apply Id.of_run_eq_wp h | |
| vcgen invariants | |
| · Invariant.withEarlyReturnNewDo | |
| (onReturn := fun ret seen => ret = false ∧ ¬l.Nodup) | |
| (onContinue := fun pref suff seen => | |
| (∀ x, x ∈ seen ↔ x ∈ pref) ∧ pref.Nodup) | |
| with finish | |
| end Automated | |
| namespace HimpSplit | |
| -- A `⇨` (Heyting implication) in the postcondition exercises the `PreservesSup.le_upperAdjoint` split, whose | |
| -- subgoal carries a `⊓ ⊤` precondition that `meet_top_le_of_le` cancels. The abstract `Pred` keeps | |
| -- `⇨` from collapsing to `→`. | |
| theorem himp_post {m} [Monad m] [Assertion Pred] [Assertion EPosts] [WPMonad m Pred EPosts] : | |
| ⦃ ⊤ ⦄ (pure 4 : m Nat) ⦃ fun r => ⌜r = 4⌝ ⇨ ⌜r > 0⌝ ⦄ := by | |
| vcgen | |
| all_goals grind | |
| end HimpSplit | |
| namespace AndSplit | |
| -- A pointwise `∧` precondition splits like `⊓`, so the `wp` of the second `dec` is stepped. | |
| def dec : StateM Nat Unit := modify (· - 1) | |
| @[spec] theorem dec_spec {Q : Unit → Nat → Prop} : | |
| ⦃ fun n => 0 < n ∧ Q () (n - 1) ⦄ dec ⦃ Q ⦄ := by | |
| vcgen [dec] <;> simp_all | |
| example : ⦃ fun n => n = 2 ⦄ (do dec; dec) ⦃ fun _ n => n = 0 ⦄ := by | |
| vcgen <;> omega | |
| end AndSplit | |
| namespace ExistsSplit | |
| -- An `∃` over a proposition splits like `∧`, so the `wp` of the second `setAt` is stepped. | |
| def setAt (xs : Array Nat) (i : Nat) : StateM Nat Unit := set xs[i]! | |
| @[spec] theorem setAt_spec {xs : Array Nat} {i : Nat} {Q : Unit → Nat → Prop} : | |
| ⦃ fun _ => ∃ h : i < xs.size, Q () xs[i] ⦄ setAt xs i ⦃ Q ⦄ := by | |
| vcgen [setAt] with finish | |
| example : ⦃ fun _ => True ⦄ (do setAt #[1, 2, 3] 1; setAt #[4, 5] 0) ⦃ fun _ n => n = 4 ⦄ := by | |
| vcgen with finish | |
| -- A `⨆` over a proposition splits like `∃`. | |
| def setAt' (xs : Array Nat) (i : Nat) : StateM Nat Unit := set xs[i]! | |
| @[spec] theorem setAt'_spec {xs : Array Nat} {i : Nat} {Q : Unit → Nat → Prop} : | |
| ⦃ fun _ => ⨆ h : i < xs.size, Q () xs[i] ⦄ setAt' xs i ⦃ Q ⦄ := by | |
| vcgen [setAt'] with finish | |
| example : ⦃ fun _ => True ⦄ (do setAt' #[1, 2, 3] 1; setAt' #[4, 5] 0) ⦃ fun _ n => n = 4 ⦄ := by | |
| vcgen with finish | |
| end ExistsSplit | |
| namespace VSTTE2010 | |
| namespace MaxAndSum | |
| def max_and_sum (xs : Array Nat) : Id (Nat × Nat) := do | |
| let mut max := 0 | |
| let mut sum := 0 | |
| for h : i in [0:xs.size] do | |
| sum := sum + xs[i] | |
| if xs[i] > max then | |
| max := xs[i] | |
| return (max, sum) | |
| theorem max_and_sum_spec (xs : Array Nat) : | |
| ⦃ ∀ i, (h : i < xs.size) → xs[i] ≥ 0 ⦄ | |
| max_and_sum xs ⦃ fun (m, s) => s ≤ m * xs.size ⦄ := by | |
| vcgen [max_and_sum] | |
| case inv1 => exact fun pref _ ⟨mx, s⟩ => s ≤ mx * pref.length | |
| all_goals simp_all +zetaDelta | |
| case vc3 => | |
| rename_i hle hlt | |
| rw [Nat.left_distrib] | |
| simp only [Nat.mul_one] | |
| exact Nat.add_le_add (Nat.le_trans hle (Nat.mul_le_mul_right _ (Nat.le_of_lt hlt))) (Nat.le_refl _) | |
| case vc4 => | |
| rw [Nat.left_distrib] | |
| grind | |
| end MaxAndSum | |
| end VSTTE2010 | |
| namespace RishsConstApproxBug | |
| @[inline] def test : StateM Unit Unit := do | |
| let _ ← get | |
| if True then | |
| pure () | |
| theorem need_const_approx' : | |
| ⦃ fun x => x = () ⦄ test ⦃ fun _ _ => True ⦄ := by | |
| vcgen [test] | |
| end RishsConstApproxBug | |
| namespace RishsTailContextBug | |
| axiom I : StateM Nat Unit | |
| axiom F : StateM Nat Unit | |
| axiom G : StateM Nat Unit | |
| axiom P : Nat → Prop | |
| axiom Q : Unit → Nat → Prop | |
| axiom hI : ⦃ fun _ => True ⦄ I ⦃ fun _ => P ⦄ | |
| axiom hF : ⦃ P ⦄ F ⦃ Q ⦄ | |
| axiom hG : ⦃ P ⦄ G ⦃ Q ⦄ | |
| attribute [local spec] hI hF hG | |
| @[inline] noncomputable def test_ite : StateM Nat Unit := do | |
| I | |
| let n ← get | |
| if n < 1 then | |
| F | |
| else | |
| G | |
| theorem ex : ⦃ fun _ => True ⦄ test_ite ⦃ Q ⦄ := by | |
| vcgen [test_ite] | |
| end RishsTailContextBug | |
| namespace KimsUnivPolyUseCase | |
| open Std | |
| variable {α : Type u} {β : Type v} {cmp : α → α → Ordering} [TransCmp cmp] | |
| def mergeWithAll (m₁ m₂ : ExtTreeMap α β cmp) (f : α → Option β → Option β → Option β) : | |
| ExtTreeMap α β cmp := | |
| Id.run do | |
| let mut r := ∅ | |
| for (a, b₁) in m₁ do | |
| if let some b := f a (some b₁) m₂[a]? then | |
| r := r.insert a b | |
| for (a, b₂) in m₂ do | |
| if a ∉ m₁ then | |
| if let some b := f a none (some b₂) then | |
| r := r.insert a b | |
| return r | |
| -- A demo that `Id.of_run_eq_wp` applies despite universe polymorphism. The `ExtTreeMap` | |
| -- loops are decomposed by the `PureForIn` specification; the invariants relating the merge | |
| -- to its two arguments are left open. | |
| theorem mem_mergeWithAll [LawfulEqCmp cmp] {m₁ m₂ : ExtTreeMap α β cmp} | |
| {f : α → Option β → Option β → Option β} {a : α} : | |
| a ∈ mergeWithAll m₁ m₂ f ↔ (a ∈ m₁ ∨ a ∈ m₂) ∧ (f a m₁[a]? m₂[a]?).isSome := by | |
| generalize h : mergeWithAll m₁ m₂ f = x | |
| apply Id.of_run_eq_wp h | |
| vcgen [mergeWithAll] | |
| all_goals admit | |
| end KimsUnivPolyUseCase | |
| namespace Slices | |
| def subarraySum (xs : Subarray Nat) : Nat := Id.run do | |
| let mut sum := 0 | |
| for x in xs do | |
| sum := sum + x | |
| return sum | |
| theorem subarraySum_correct {xs : Subarray Nat} : subarraySum xs = xs.toList.sum := by | |
| generalize h : subarraySum xs = r | |
| apply Id.of_run_eq_wp h | |
| vcgen | |
| case inv1 => exact fun pref _ s => s = pref.sum | |
| all_goals simp_all +zetaDelta | |
| end Slices | |
| /-! ## PatricksFastExp -/ | |
| namespace PatricksFastExp | |
| def naive_expo (x n : Nat) : Nat := Id.run do | |
| let mut y := 1 | |
| for _ in [:n] do | |
| y := y * x | |
| return y | |
| def fast_expo (x n : Nat) : Nat := Id.run do | |
| let mut x := x | |
| let mut y := 1 | |
| let mut e := n | |
| for _ in [:n] do -- simulating a while loop running at most n times | |
| if e = 0 then break | |
| if e % 2 = 1 then | |
| y := x * y | |
| e := e - 1 | |
| else | |
| x := x*x | |
| e := e/2 | |
| return y | |
| theorem naive_expo_correct (x n : Nat) : naive_expo x n = x ^ n := by | |
| generalize h : naive_expo x n = r | |
| apply Id.of_run_eq_wp h | |
| vcgen | |
| case inv1 => exact fun pref _ y => y = x ^ pref.length | |
| all_goals simp_all +zetaDelta [Nat.pow_add_one] | |
| theorem fast_expo_correct (x n : Nat) : fast_expo x n = x ^ n := by | |
| generalize h : fast_expo x n = r | |
| apply Id.of_run_eq_wp h | |
| vcgen | |
| case inv1 => exact fun pref _ ⟨x', y, e⟩ => x' ^ e * y = x ^ n ∧ e ≤ n - pref.length | |
| all_goals simp_all +zetaDelta | |
| case vc2 ih => | |
| rw [← ih.1, ih.2, Nat.pow_zero, Nat.one_mul] | |
| case vc4 => | |
| constructor | |
| · rw [← Nat.mul_assoc, ← Nat.pow_add_one] | |
| grind | |
| · grind | |
| case vc5 => | |
| constructor | |
| · rw [← Nat.pow_two, ← Nat.pow_mul] | |
| grind | |
| · grind | |
| theorem same_func (x n : Nat) : fast_expo x n = naive_expo x n := by | |
| rw [naive_expo_correct, fast_expo_correct] | |
| end PatricksFastExp | |
| section IteratorTests | |
| variable {m} [Monad m] | |
| open Std Std.Iterators | |
| theorem forIn_eq_sum (xs : Array Nat) {m} [Monad m] [Assertion Pred] [Assertion EPosts] | |
| [WPMonad m Pred EPosts] : | |
| ⦃ ⊤ ⦄ | |
| (do | |
| let mut sum : Nat := 0 | |
| for n in xs.iter do | |
| sum := sum + n | |
| return sum : m _) | |
| ⦃ fun r => ⌜r = xs.sum⌝ ⦄ := by | |
| vcgen | |
| case inv1 => exact fun pref _ n => ⌜n = pref.sum⌝ | |
| all_goals grind | |
| theorem forIn_map_eq_sum_add_size' (xs : Array Nat) {m} [Monad m] [Assertion Pred] [Assertion EPosts] | |
| [WPMonad m Pred EPosts] : | |
| ⦃ ⊤ ⦄ (m := m) (do | |
| let mut sum : Nat := 0 | |
| for n in (xs.iterM Id).map (· + 1) do | |
| sum := sum + n | |
| return sum) ⦃ fun r => ⌜r = xs.sum + xs.size⌝ ⦄ := by | |
| vcgen | |
| case inv1 => exact fun pref _ n => ⌜n = pref.sum + pref.length⌝ | |
| all_goals grind | |
| theorem forIn_map_eq_sum_add_size (xs : Array Nat) {m} [Monad m] [Assertion Pred] [Assertion EPosts] | |
| [WPMonad m Pred EPosts] : | |
| ⦃ ⊤ ⦄ (m := m) (do | |
| let mut sum : Nat := 0 | |
| for n in (xs.iterM Id).map (· + 1) do | |
| sum := sum + n | |
| return sum) ⦃ fun r => ⌜r = xs.sum + xs.size⌝ ⦄ := by | |
| vcgen | |
| case inv1 => exact fun pref _ n => ⌜n = pref.sum + pref.length⌝ | |
| all_goals grind | |
| theorem forIn_mapM_eq_sum_add_size (xs : Array Nat) {m} [Monad m] [MonadAttach m] | |
| [LawfulMonad m] [WeaklyLawfulMonadAttach m] [Assertion Pred] [Assertion EPosts] [WPMonad m Pred EPosts] : | |
| ⦃ ⊤ ⦄ (m := m) (do | |
| let mut sum : Nat := 0 | |
| for n in (xs.iterM Id).mapM (pure (f := m) <| · + 1) do | |
| sum := sum + n | |
| return sum) ⦃ fun r => ⌜r = xs.sum + xs.size⌝ ⦄ := by | |
| vcgen | |
| case inv1 => exact fun pref _ n => ⌜n = pref.sum + pref.length⌝ | |
| all_goals grind | |
| theorem forIn_filterMapM_eq_sum_add_size (xs : Array Nat) {m} | |
| [Monad m] [LawfulMonad m] [MonadAttach m] [WeaklyLawfulMonadAttach m] [Assertion Pred] [Assertion EPosts] [WPMonad m Pred EPosts] : | |
| ⦃ ⊤ ⦄ (m := m) (do | |
| let mut sum : Nat := 0 | |
| for n in (xs.iterM Id).filterMapM (pure (f := m) <| some <| · + 1) do | |
| sum := sum + n | |
| return sum) ⦃ fun r => ⌜r = xs.sum + xs.size⌝ ⦄ := by | |
| vcgen | |
| case inv1 => exact fun pref _ n => ⌜n = pref.sum + pref.length⌝ | |
| all_goals grind | |
| theorem foldM_eq_sum (xs : Array Nat) {m} [Monad m] [LawfulMonad m] | |
| [Assertion Pred] [Assertion EPosts] [WPMonad m Pred EPosts] : | |
| ⦃ ⊤ ⦄ (xs.iter.foldM (m := m) (init := 0) (pure <| · + ·)) ⦃ fun r => ⌜r = xs.sum⌝ ⦄ := by | |
| vcgen | |
| case inv1 => exact fun pref _ n => ⌜n = pref.sum⌝ | |
| all_goals grind | |
| end IteratorTests | |
| namespace ConfigSyntaxTests | |
| /-! Tests for the ported `(config := …)` syntax. Implemented options change behavior | |
| silently; `leave`, `trivial` and `jp` are accepted by the parser but warn that they are | |
| currently ignored. -/ | |
| def trivial_test (n : Nat) : Id Nat := pure n | |
| /-- An empty `(config := {})` matches the default `vcgen` behavior. -/ | |
| example : ⦃ True ⦄ trivial_test 0 ⦃fun r => r = 0⦄ := by | |
| vcgen (config := {}) [trivial_test] | |
| /-- warning: vcgen: the `trivial` config option is currently ignored. -/ | |
| #guard_msgs in | |
| example : ⦃ True ⦄ trivial_test 0 ⦃fun r => r = 0⦄ := by | |
| vcgen (trivial := false) [trivial_test] | |
| -- `elimLets := false` skips the let-elimination pre-pass (now honored by `vcgen`). | |
| example : ⦃ True ⦄ trivial_test 0 ⦃fun r => r = 0⦄ := by | |
| vcgen (config := { elimLets := false }) [trivial_test] | |
| -- `stepLimit` is accepted; with a positive limit, simple programs still discharge. | |
| example : ⦃ True ⦄ trivial_test 0 ⦃fun r => r = 0⦄ := by | |
| vcgen (config := { stepLimit := some 100 }) [trivial_test] | |
| /-- warning: vcgen: the `leave` config option is currently ignored. -/ | |
| #guard_msgs in | |
| example : ⦃ True ⦄ trivial_test 0 ⦃fun r => r = 0⦄ := by | |
| vcgen (config := { leave := false }) [trivial_test] | |
| -- `jp := true` is accepted and wired through `Context.useJP`; the actual | |
| -- shared-continuation construction (Phase 6 of the plan) is not yet ported, | |
| -- so enabling it on a program containing `__do_jp` errors at the detection | |
| -- point. Programs without `__do_jp` (like this trivial example) are unaffected. | |
| example : ⦃ True ⦄ trivial_test 0 ⦃fun r => r = 0⦄ := by | |
| vcgen (config := { jp := true }) [trivial_test] | |
| end ConfigSyntaxTests | |
| namespace InvariantSyntaxTests | |
| /-! Tests for the ported `invariants` syntax (bullet form and labelled form). -/ | |
| def check_all (p : Nat → Prop) [DecidablePred p] (n : Nat) : Bool := Id.run do | |
| for i in [0:n] do | |
| if ¬ p i then | |
| return false | |
| return true | |
| -- Bullet form: `· …` per invariant. Uses the `with` clause to discharge the | |
| -- emitted VCs in one go (preTac runs after all invariants are inline-elaborated, | |
| -- so the `with` tactic sees the assigned invariant values). | |
| example (p : Nat → Prop) [DecidablePred p] (n : Nat) : | |
| (∀ i, i < n → p i) ↔ check_all p n := by | |
| generalize h : check_all p n = x | |
| apply Id.of_run_eq_wp h | |
| vcgen invariants | |
| · Invariant.withEarlyReturnNewDo | |
| (onReturn := fun ret _ => ⌜ret = false ∧ ¬ ∀ i < n, p i⌝) | |
| (onContinue := fun pref _ _ => ⌜∀ i, i ∈ pref → p i⌝) | |
| all_goals simp_all [-Classical.not_forall]; try grind | |
| -- Labelled form: `| inv1 => …`. | |
| example (p : Nat → Prop) [DecidablePred p] (n : Nat) : | |
| (∀ i, i < n → p i) ↔ check_all p n := by | |
| generalize h : check_all p n = x | |
| apply Id.of_run_eq_wp h | |
| vcgen invariants | |
| | inv1 => Invariant.withEarlyReturnNewDo | |
| (onReturn := fun ret _ => ⌜ret = false ∧ ¬ ∀ i < n, p i⌝) | |
| (onContinue := fun pref _ _ => ⌜∀ i, i ∈ pref → p i⌝) | |
| all_goals simp_all [-Classical.not_forall]; try grind | |
| end InvariantSyntaxTests | |
| namespace RflReducibility | |
| -- From `mvcgenRflReducibility.lean`. Asserts that decomposing `MyShl.shl a 32` does | |
| -- not whnf at default reducibility, otherwise `UInt64.ofNat 32.toInt.toNat` would | |
| -- unfold deeply and timeout. `vcgen` keeps reduction at `.instances` transparency | |
| -- when stepping through class projections (`reduceProj?` in `Reduce.lean`), so this | |
| -- example decomposes cleanly. | |
| abbrev RustM := Except String | |
| class MyAddU (Self : Type) (Rhs : Type) where | |
| add : (Self → Rhs → RustM Self) | |
| instance : MyAddU UInt64 UInt64 := { | |
| add x y := if BitVec.uaddOverflow x.toBitVec y.toBitVec then Except.error "" else pure (x + y) | |
| } | |
| class MyShl (Self : Type) (Rhs : Type) where | |
| shl : (Self → Rhs → RustM Self) | |
| instance : MyShl UInt64 Int32 := { | |
| shl x y := pure (x <<< (UInt64.ofNat y.toInt.toNat)) | |
| } | |
| /-- | |
| error: unsolved goals | |
| case vc1 | |
| a : UInt64 | |
| h✝ : (0#64).uaddOverflow (a <<< UInt64.ofNat (Int32.toInt 32).toNat).toBitVec = true | |
| ⊢ wp (Except.error "") (fun x => True) ⊥ | |
| -/ | |
| #guard_msgs in | |
| example (a : UInt64) : | |
| ⦃True⦄ | |
| do | |
| let a ← MyShl.shl a (32: Int32) | |
| let a ← MyAddU.add (0 : UInt64) a | |
| pure a | |
| ⦃fun _ => True⦄ := by | |
| vcgen (errorOnMissingSpec := false) [MyShl.shl, MyAddU.add] | |
| end RflReducibility | |
| namespace LocalSpec | |
| def foo (x : Id Nat → Id Nat) : Id Nat := do | |
| let r₁ ← x (pure 42) | |
| let r₂ ← x (pure 26) | |
| pure (r₁ + r₂) | |
| theorem foo_spec | |
| (x : Id Nat → Id Nat) | |
| (x_spec : ∀ (k : Id Nat), ⦃ True ⦄ k ⦃ fun r => r % 2 = 0 ⦄ → | |
| ⦃ True ⦄ x k ⦃ fun r => r % 2 = 0 ⦄) : | |
| ⦃ True ⦄ foo x ⦃ fun r => r % 2 = 0 ⦄ := by | |
| vcgen [foo, x_spec] with finish | |
| def bar (k : Id Nat) : Id Nat := do | |
| let r ← k | |
| if r > 30 then | |
| return 12 | |
| else | |
| return r | |
| example : ⦃ True ⦄ foo bar ⦃ fun r => r % 2 = 0 ⦄ := by | |
| vcgen [foo_spec, bar] with finish | |
| end LocalSpec | |
| namespace RawMonadLiftRegression | |
| /-! A raw `monadLift` of an `Id` value into an outer monad, discharged by `Spec.monadLift_Id`. -/ | |
| def liftProg : StateT Nat Id Nat := do | |
| let x ← (pure 5 : Id Nat) | |
| return x | |
| example : ⦃ fun _ => ⌜True⌝ ⦄ liftProg ⦃ fun r _ => ⌜r = 5⌝ ⦄ := by vcgen [liftProg] <;> grind | |
| end RawMonadLiftRegression | |
| namespace InvalidSpecRejection | |
| /-! A `@[spec]` annotation whose conclusion is neither a Hoare triple nor an equation is rejected. -/ | |
| /-- error: Invalid 'spec': target was neither a Hoare triple specification nor a 'simp' lemma -/ | |
| #guard_msgs in | |
| @[spec] theorem trivialSpec : True := trivial | |
| end InvalidSpecRejection | |
| namespace TopBetaReduction | |
| variable {m : Type → Type u} {Pred EPosts} [Monad m] [Assertion Pred] [Assertion EPosts] [WPMonad m Pred EPosts] | |
| def incr (n : Nat) : StateT Nat m PUnit := modify (· + n) | |
| @[spec] | |
| theorem Spec.incr | |
| (post : PUnit → Nat → Pred) (eposts : EPosts) (n : Nat) : | |
| ⦃ fun s => post ⟨⟩ (s + n) ⦄ (incr n : StateT Nat m PUnit) ⦃ post; eposts ⦄ := by | |
| vcgen [TopBetaReduction.incr] | |
| /-- | |
| error: unsolved goals | |
| case vc1 | |
| amounts : List Nat | |
| s✝ : Nat | |
| ⊢ False | |
| -/ | |
| #guard_msgs in | |
| theorem incr_id (amounts : List Nat) : | |
| ⦃ ⊤ ⦄ | |
| incr (m := Id) 1 | |
| ⦃ fun _ _ => ⊥ ⦄ := by | |
| vcgen [incr] | |
| /-- | |
| error: unsolved goals | |
| case vc1 | |
| m : Type → Type u | |
| Pred : Type u_1 | |
| EPosts : Type u_2 | |
| inst✝³ : Monad m | |
| inst✝² : Assertion Pred | |
| inst✝¹ : Assertion EPosts | |
| inst✝ : WPMonad m Pred EPosts | |
| amounts : List Nat | |
| s✝ : Nat | |
| ⊢ ⊤ ⊑ ⊥ | |
| -/ | |
| #guard_msgs in | |
| theorem incr_poly (amounts : List Nat) : | |
| ⦃ ⊤ ⦄ | |
| incr (m := m) 1 | |
| ⦃ fun _ _ => ⊥ ⦄ := by | |
| vcgen [incr] | |
| end TopBetaReduction | |
| namespace WhileInvariantOfInvariantAndBreak | |
| /-! Verifies a `while` loop whose `vcgen` invariant is supplied via | |
| `WhileInvariant.ofInvariantAndBreak`: a loop invariant `inv` that holds after every iteration plus | |
| an `onBreak` condition (here the negated loop condition) that additionally holds once the loop | |
| exits. -/ | |
| /-- Counts `i` down from `n`, incrementing the state on each iteration, so the final state is `n`. | |
| The measure reads the loop's own variable, which `NondetFun` interprets as that value. -/ | |
| def countdown (n : Nat) : StateT Nat Id Unit := do | |
| let mut i := n | |
| while i > 0 do | |
| i := i - 1 | |
| modify (· + 1) | |
| return | |
| theorem countdown_spec (n : Nat) : | |
| ⦃ fun s => s = 0 ⦄ countdown n ⦃ fun _ s => s = n ⦄ := by | |
| vcgen [countdown] invariants | |
| | inv1 => WhileInvariant.ofInvariantAndBreak (fun i s => s + i = n) (fun i _ => i = 0) | |
| | inv2 => .ofMeasure fun i => i | |
| with finish | |
| /-- Like `countdown`, but termination is measured from the monadic state rather than the loop cursor. -/ | |
| def countdownStateful (n : Nat) : StateT Nat Id Unit := do | |
| set 0 | |
| while (← get) ≠ n do | |
| modify (· + 1) | |
| return | |
| theorem countdownStateful_spec (n : Nat) : | |
| ⦃ fun _ => True ⦄ countdownStateful n ⦃ fun _ s => s = n ⦄ := by | |
| vcgen [countdownStateful] invariants | |
| | inv1 => WhileInvariant.ofInvariantAndBreak | |
| (fun _ s => s ≤ n) | |
| (fun _ s => s = n) | |
| | inv2 => .ofMeasure fun _ s => n - s | |
| with finish | |
| /-- Nested countdown driven by a single `while` loop: `i` counts down and resets `j`, so the | |
| decrease is lexicographic in `(i, j)`. -/ | |
| def countdownLex (n : Nat) : StateT Nat Id Unit := do | |
| let mut i := n | |
| let mut j := 0 | |
| let mut k := 0 | |
| while 0 < i ∨ 0 < j ∨ 0 < k do | |
| if 0 < k then | |
| k := k - 1 | |
| modify (· + 1) | |
| else if 0 < j then | |
| j := j - 1 | |
| k := n | |
| else | |
| i := i - 1 | |
| j := n | |
| return | |
| theorem countdownLex_spec (n : Nat) : | |
| ⦃ fun _ => True ⦄ countdownLex n ⦃ fun _ _ => True ⦄ := by | |
| vcgen [countdownLex] invariants | |
| | inv1 => WhileInvariant.ofInvariantAndBreak (fun _ _ => True) (fun _ _ => True) | |
| | inv2 => .ofMeasure fun (i, j, k) => (i, j, k) | |
| with finish | |
| end WhileInvariantOfInvariantAndBreak | |
| namespace WithGrindError | |
| /-! The `with` clause of `vcgen` only accepts a `grind`-mode step (e.g. `finish`, `intro`). A | |
| general tactic such as `grind` parses but is rejected with a helpful error in the elaborator, | |
| rather than a raw `unexpected identifier; expected grind` parser error. -/ | |
| def trivial_test (n : Nat) : Id Nat := pure n | |
| /-- | |
| error: `vcgen … with` expects a `grind`-mode discharging step, not a general tactic | |
| Hint: Examples: `vcgen … with finish`, `vcgen … with intro`. | |
| -/ | |
| #guard_msgs in | |
| example : ⦃ True ⦄ trivial_test 0 ⦃fun r => r = 0⦄ := by | |
| vcgen [trivial_test] with grind | |
| end WithGrindError | |
| namespace ConjunctivePre | |
| /-! Each spec below has a precondition conjunctive in `Q`, so `vcgen` applies it directly and forms | |
| no frame. The preconditions use `∀`/`→` (`bump_spec`), a `wp` applied to the state (`bump2_spec`), | |
| `if` (`bumpSat_spec`), `match` (`dec_spec`), `Prod.snd` (`bumpE_spec`) and a pair (`retryE_spec`). | |
| The frame `fun s => s = 3` fails to hold across each program: a framed application leaves an | |
| unprovable goal such as `WP.Frames meet bump (fun s => s = 3)`. -/ | |
| @[irreducible] def bump : StateT Nat Id Unit := modify (· + 1) | |
| @[spec] | |
| theorem bump_spec (Q : Unit → Nat → Prop) : | |
| ⦃ fun s => ∀ s', s' = s + 1 → Q () s' ⦄ bump ⦃ Q ⦄ := by | |
| unfold bump; vcgen with finish | |
| example : ⦃ fun s => s = 3 ⦄ bump ⦃ fun _ s => s = 4 ⦄ := by | |
| vcgen frames | bump => fun s => s = 3 with finish | |
| @[irreducible] def bump2 : StateT Nat Id Unit := do bump; bump | |
| @[spec] | |
| theorem bump2_spec (Q : Unit → Nat → Prop) (E : EStack⟨⟩) : | |
| ⦃ fun s => wp bump (fun _ => wp bump Q E) E s ⦄ bump2 ⦃ Q; E ⦄ := by | |
| unfold bump2; exact ⟨WPMonad.bind_le_wp_bind bump (fun _ => bump) Q E⟩ | |
| example : ⦃ fun s => s = 3 ⦄ bump2 ⦃ fun _ s => s = 5 ⦄ := by | |
| vcgen frames | bump2 => fun s => s = 3 with finish | |
| @[irreducible] def bumpSat : StateT Nat Id Unit := modify fun s => if s < 10 then s + 1 else s | |
| @[spec] | |
| theorem bumpSat_spec (Q : Unit → Nat → Prop) : | |
| ⦃ fun s => if s < 10 then Q () (s + 1) else Q () s ⦄ bumpSat ⦃ Q ⦄ := by | |
| unfold bumpSat; vcgen with finish | |
| example : ⦃ fun s => s = 3 ⦄ bumpSat ⦃ fun _ s => s = 4 ⦄ := by | |
| vcgen frames | bumpSat => fun s => s = 3 with finish | |
| @[irreducible] def dec : StateT Nat Id Unit := modify fun | 0 => 0 | n + 1 => n | |
| @[spec] | |
| theorem dec_spec (Q : Unit → Nat → Prop) : | |
| ⦃ fun s => match s with | 0 => Q () 0 | n + 1 => Q () n ⦄ dec ⦃ Q ⦄ := by | |
| unfold dec; vcgen; rename_i s _; cases s <;> simp_all | |
| example : ⦃ fun s => s = 3 ⦄ dec ⦃ fun _ s => s = 2 ⦄ := by | |
| vcgen frames | dec => fun s => s = 3 with finish | |
| @[irreducible] def bumpE : ExceptT String (StateT Nat Id) Unit := monadLift bump | |
| @[spec] | |
| theorem bumpE_spec (Q : Unit → Nat → Prop) (E : (String → Nat → Prop) × EStack⟨⟩) : | |
| ⦃ wp bump Q E.snd ⦄ bumpE ⦃ Q; E ⦄ := by | |
| unfold bumpE; exact Spec.monadLift_ExceptT bump Q E | |
| example : ⦃ fun s => s = 3 ⦄ bumpE ⦃ fun _ s => s = 4 ⦄ := by | |
| vcgen frames | bumpE => fun s => s = 3 with finish | |
| @[irreducible] def retryE : ExceptT String (StateT Nat Id) Unit := tryCatch bumpE fun _ => bumpE | |
| @[spec] | |
| theorem retryE_spec (Q : Unit → Nat → Prop) (E : (String → Nat → Prop) × EStack⟨⟩) : | |
| ⦃ wp bumpE Q (fun _ => wp bumpE Q E, E.snd) ⦄ retryE ⦃ Q; E ⦄ := by | |
| unfold retryE; exact Spec.tryCatch_ExceptT bumpE (fun _ => bumpE) Q E | |
| example : ⦃ fun s => s = 3 ⦄ retryE ⦃ fun _ s => s = 4 ⦄ := by | |
| vcgen frames | retryE => fun s => s = 3 with finish | |
| end ConjunctivePre |