From 0f103b9d1a2975aea6e88c052c9bb8e13911ad6e Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Fri, 9 Oct 2026 15:27:24 +0200 Subject: [PATCH 01/64] Shallow embedding: a starting point on Std.Do StrataBoole/Shallow/Layer.lean: a nondeterministic monad on Lean's Std.Do with havoc, assume, assert and a while loop carrying its invariant, each with a proved rule, so mvcgen generates the verification conditions. StrataBooleTest/shallow_find_max.lean: three hand-written programs verified with it, find max among them, in the form a translation from Core should produce. The proofs use only Lean's standard axioms. docs/ShallowEmbedding.md: the design, the mapping from Core to Lean, the status, and the research and open questions. Co-Authored-By: Claude Opus 5.5 --- StrataBoole.lean | 6 + StrataBoole/Shallow/Layer.lean | 176 ++++++++++++++++++++++++++ StrataBooleTest.lean | 1 + StrataBooleTest/shallow_find_max.lean | 112 ++++++++++++++++ docs/ShallowEmbedding.md | 89 +++++++++++++ 5 files changed, 384 insertions(+) create mode 100644 StrataBoole/Shallow/Layer.lean create mode 100644 StrataBooleTest/shallow_find_max.lean create mode 100644 docs/ShallowEmbedding.md diff --git a/StrataBoole.lean b/StrataBoole.lean index 8e64d24..4a4bf75 100644 --- a/StrataBoole.lean +++ b/StrataBoole.lean @@ -29,6 +29,12 @@ dialect of Strata. `Strata.BooleNat.prepend`. The implementation is `natCorePreamble` in `StrataBoole/Verify.lean`; nothing imports this module. `lake build StrataBoole.Nat`. +### `import StrataBoole.Shallow.Layer` + +The shallow embedding's layer on `Std.Do`: the `ND` monad with `havoc`, +`assume`, `assert` and `whileInv`, each with its `@[spec]` rule for `mvcgen`. +See `docs/ShallowEmbedding.md`. + ### `import StrataBoole.MetaVerifier` The `gen_smt_vcs_boole` tactic and `Strata.smtVCsCorrectBoole` are available diff --git a/StrataBoole/Shallow/Layer.lean b/StrataBoole/Shallow/Layer.lean new file mode 100644 index 0000000..860a340 --- /dev/null +++ b/StrataBoole/Shallow/Layer.lean @@ -0,0 +1,176 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +module + +public import Std.Do +public import Std.Tactic.Do + +/-! # The shallow embedding's layer on `Std.Do` + +What a Core program needs beyond Lean's `do` notation and `mvcgen`: a +nondeterministic monad with `havoc`, `assume` and `assert`, and a `while` loop +whose invariant is part of the program. Each construct comes with its proof +rule (`@[spec]`), so `mvcgen` generates the verification conditions. + +The design follows Velvet (verse-lab/velvet); the code is ours and runs on the +Lean version Strata is on. See `docs/ShallowEmbedding.md`. +-/ + +public section + +namespace Strata.Shallow + +open Std.Do + +/-- A nondeterministic computation is its set of outcomes; `none` is a failed `assert`. -/ +structure ND (α : Type) where + run : Option α → Prop + +namespace ND + +theorem ext {x y : ND α} (h : ∀ r, x.run r ↔ y.run r) : x = y := by + cases x; cases y; congr; funext r; exact propext (h r) + +instance : Monad ND where + pure a := ⟨fun r => r = some a⟩ + bind x f := ⟨fun r => (∃ a, x.run (some a) ∧ (f a).run r) ∨ (x.run none ∧ r = none)⟩ + +theorem run_pure (a : α) (r : Option α) : (pure a : ND α).run r ↔ r = some a := Iff.rfl + +theorem run_bind (x : ND α) (f : α → ND β) (r : Option β) : + (x >>= f).run r ↔ (∃ a, x.run (some a) ∧ (f a).run r) ∨ (x.run none ∧ r = none) := Iff.rfl + +instance : LawfulMonad ND := LawfulMonad.mk' ND + (id_map := by + intro α x; apply ext; intro r + show (x >>= fun a => pure (id a)).run r ↔ _ + simp only [run_bind, run_pure, id] + cases r <;> simp) + (pure_bind := by + intro α β a f; apply ext; intro r + simp [run_bind, run_pure]) + (bind_assoc := by + intro α β γ x f g; apply ext; intro r + simp only [run_bind] + constructor + · rintro (⟨b, (⟨a, hx, hf⟩ | ⟨hx, hb⟩), hg⟩ | ⟨(⟨a, hx, hf⟩ | ⟨hx, -⟩), rfl⟩) + · exact .inl ⟨a, hx, .inl ⟨b, hf, hg⟩⟩ + · cases hb + · exact .inl ⟨a, hx, .inr ⟨hf, rfl⟩⟩ + · exact .inr ⟨hx, by simp⟩ + · rintro (⟨a, hx, (⟨b, hf, hg⟩ | ⟨hf, rfl⟩)⟩ | ⟨hx, rfl⟩) + · exact .inl ⟨b, .inl ⟨a, hx, hf⟩, hg⟩ + · exact .inr ⟨.inl ⟨a, hx, hf⟩, rfl⟩ + · exact .inr ⟨.inr ⟨hx, by simp⟩, rfl⟩) + +/-- Every outcome is a value satisfying the postcondition (partial correctness). -/ +def wpTrans (x : ND α) : PredTrans .pure α where + trans Q := ⌜∀ r, x.run r → ∃ a, r = some a ∧ (Q.1 a).down⌝ + conjunctiveRaw := by + intro Q₁ Q₂ + simp only [SPred.bientails_nil, SPred.and_nil, SPred.down_pure] + constructor + · intro h + exact ⟨fun r hr => let ⟨a, e, h1, _⟩ := h r hr; ⟨a, e, h1⟩, + fun r hr => let ⟨a, e, _, h2⟩ := h r hr; ⟨a, e, h2⟩⟩ + · rintro ⟨h1, h2⟩ r hr + obtain ⟨a, rfl, ha⟩ := h1 r hr + obtain ⟨b, hb, hb2⟩ := h2 _ hr + cases hb + exact ⟨a, rfl, ha, hb2⟩ + +instance : WP ND .pure := ⟨wpTrans⟩ + +theorem wp_apply (x : ND α) (Q : PostCond α .pure) : + (wp⟦x⟧ Q).down ↔ ∀ r, x.run r → ∃ a, r = some a ∧ (Q.1 a).down := Iff.rfl + +private theorem spred_ext {P Q : SPred []} (h : P.down ↔ Q.down) : P = Q := by + show ULift.up P.down = ULift.up Q.down + rw [propext h] + +instance : WPMonad ND .pure where + wp_pure a := by + apply PredTrans.ext; intro Q + apply spred_ext + rw [wp_apply] + simp [run_pure] + wp_bind x f := by + apply PredTrans.ext; intro Q + apply spred_ext + rw [wp_apply] + simp only [PredTrans.apply_Bind_bind, run_bind] + show _ ↔ ∀ r, x.run r → ∃ a, r = some a ∧ ∀ r', (f a).run r' → ∃ b, r' = some b ∧ (Q.1 b).down + constructor + · intro h r hr + cases r with + | none => exact absurd (h none (.inr ⟨hr, rfl⟩)) (by simp) + | some a => exact ⟨a, rfl, fun r' hr' => h r' (.inl ⟨a, hr, hr'⟩)⟩ + · rintro h r (⟨a, hx, hf⟩ | ⟨hx, rfl⟩) + · obtain ⟨a', ha', h'⟩ := h _ hx + cases ha' + exact h' r hf + · obtain ⟨a', ha', -⟩ := h _ hx + cases ha' + +/-! Statements Lean has no counterpart for. -/ + +/-- `havoc`: any value. -/ +def havoc : ND α := ⟨fun r => ∃ a, r = some a⟩ + +/-- `assume p`: executions where `p` fails do not exist. -/ +def assume (p : Prop) : ND Unit := ⟨fun r => p ∧ r = some ()⟩ + +/-- `assert p`: fails when `p` does not hold. -/ +def assert (p : Prop) : ND Unit := ⟨fun r => (p ∧ r = some ()) ∨ (¬ p ∧ r = none)⟩ + +/-- Executions of `while c do body` from a state: the least relation closed under the +loop's steps, so a diverging run has no outcome (partial correctness). -/ +inductive WhileRel (c : β → Prop) (body : β → ND β) : β → Option β → Prop + | done {s} : ¬ c s → WhileRel c body s (some s) + | step {s s' r} : c s → (body s).run (some s') → WhileRel c body s' r → WhileRel c body s r + | fail {s} : c s → (body s).run none → WhileRel c body s none + +/-- A `while` loop on the state `β`. The invariant is an annotation; it does not affect +what the loop does. -/ +def whileInv (_inv : β → Prop) (c : β → Prop) (body : β → ND β) (init : β) : ND β := + ⟨WhileRel c body init⟩ + +theorem triple_iff {x : ND α} {P : Prop} {Q : α → Prop} : + ⦃⌜P⌝⦄ x ⦃⇓ a => ⌜Q a⌝⦄ ↔ (P → ∀ r, x.run r → ∃ a, r = some a ∧ Q a) := Iff.rfl + +@[spec] theorem havoc_spec : ⦃⌜True⌝⦄ (havoc : ND α) ⦃⇓ _ => ⌜True⌝⦄ := by + rw [triple_iff]; rintro - r ⟨a, rfl⟩; exact ⟨a, rfl, trivial⟩ + +@[spec] theorem assume_spec (p : Prop) : ⦃⌜True⌝⦄ assume p ⦃⇓ _ => ⌜p⌝⦄ := by + rw [triple_iff]; rintro - r ⟨hp, rfl⟩; exact ⟨(), rfl, hp⟩ + +@[spec] theorem assert_spec (p : Prop) : ⦃⌜p⌝⦄ assert p ⦃⇓ _ => ⌜p⌝⦄ := by + rw [triple_iff]; rintro hp r (⟨-, rfl⟩ | ⟨hn, -⟩) + · exact ⟨(), rfl, hp⟩ + · exact absurd hp hn + +/-- The invariant rule: if the body preserves the invariant, the loop ends with the +invariant and the negated condition. -/ +@[spec] theorem whileInv_spec (inv c : β → Prop) (body : β → ND β) (init : β) + (step : ∀ s, ⦃⌜inv s ∧ c s⌝⦄ body s ⦃⇓ s' => ⌜inv s'⌝⦄) : + ⦃⌜inv init⌝⦄ whileInv inv c body init ⦃⇓ s => ⌜inv s ∧ ¬ c s⌝⦄ := by + rw [triple_iff] + intro hinit r hr + induction hr with + | done hc => exact ⟨_, rfl, hinit, hc⟩ + | step hc hb _ ih => + obtain ⟨s'', hs, hinv⟩ := triple_iff.mp (step _) ⟨hinit, hc⟩ _ hb + cases hs + exact ih hinv + | fail hc hb => + obtain ⟨s'', hs, -⟩ := triple_iff.mp (step _) ⟨hinit, hc⟩ _ hb + cases hs + +end ND + +end Strata.Shallow + +end diff --git a/StrataBooleTest.lean b/StrataBooleTest.lean index a2a90f1..4b39e7c 100644 --- a/StrataBooleTest.lean +++ b/StrataBooleTest.lean @@ -54,3 +54,4 @@ import StrataBooleTest.FeatureRequests.trait_spec_methods import StrataBooleTest.widening_casts import StrataBooleTest.inline_boole_defs import StrataBooleTest.seq_unsafe_ops +import StrataBooleTest.shallow_find_max diff --git a/StrataBooleTest/shallow_find_max.lean b/StrataBooleTest/shallow_find_max.lean new file mode 100644 index 0000000..bbe2d68 --- /dev/null +++ b/StrataBooleTest/shallow_find_max.lean @@ -0,0 +1,112 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.Shallow.Layer + +/-! Three programs, written by hand in the form the translation from Core +should produce, verified with `mvcgen` on the layer. This file is the +contract between the translation and the layer. -/ + +-- Lean marks `mvcgen` experimental; see docs/ShallowEmbedding.md. +set_option mvcgen.warning false + +namespace Strata.Shallow.Test + +open Std.Do Strata.Shallow Strata.Shallow.ND + +/-- `havoc x; assume x >= 0`. -/ +def pick_nat : ND Int := do + let x ← havoc + assume (x ≥ 0) + return x + +theorem pick_nat_spec : ⦃⌜True⌝⦄ pick_nat ⦃⇓ x => ⌜x ≥ 0⌝⦄ := by + mvcgen [pick_nat] + +/-- A loop without a termination measure. State: `(i, r)`. -/ +def sum_to (n : Int) : ND Int := do + let s ← whileInv + (fun s : Int × Int => 0 ≤ s.1 ∧ s.1 ≤ n ∧ 2 * s.2 = s.1 * (s.1 + 1)) + (fun s => s.1 < n) + (fun s => pure (s.1 + 1, s.2 + (s.1 + 1))) + (0, 0) + return s.2 + +theorem sum_to_spec (n : Int) (h : n ≥ 0) : + ⦃⌜True⌝⦄ sum_to n ⦃⇓ r => ⌜2 * r = n * (n + 1)⌝⦄ := by + mvcgen [sum_to] + all_goals grind + +/-- Find max, from the Verus translator's Boole output. State: `(max, i)`. -/ +def find_max (nums : Array (BitVec 32)) : ND (BitVec 32) := do + assert (0 < nums.size) + let s ← whileInv + (fun s : BitVec 32 × Int => + (∃ j : Int, 0 ≤ j ∧ j < s.2 ∧ s.1 = nums[j.toNat]!) ∧ + (∀ k : Int, 0 ≤ k ∧ k < s.2 → BitVec.sle nums[k.toNat]! s.1) ∧ + 0 ≤ s.2 ∧ s.2 ≤ nums.size) + (fun s => s.2 < nums.size) + (fun s => do + assert (0 ≤ s.2 ∧ s.2 < nums.size) + let max := if BitVec.slt s.1 nums[s.2.toNat]! then nums[s.2.toNat]! else s.1 + assert (0 ≤ s.2 + 1 ∧ s.2 + 1 ≤ 18446744073709551615) + pure (max, (s.2 + 1) % 18446744073709551616)) + (nums[0]!, 1) + return s.1 + +theorem find_max_spec (nums : Array (BitVec 32)) : + ⦃⌜nums.size > 0 ∧ (nums.size : Int) ≤ 18446744073709551615⌝⦄ + find_max nums + ⦃⇓ ret => ⌜(∀ i : Int, 0 ≤ i ∧ i < nums.size → BitVec.sle nums[i.toNat]! ret) ∧ + (∃ j : Int, 0 ≤ j ∧ j < nums.size ∧ ret = nums[j.toNat]!)⌝⦄ := by + mvcgen [find_max] + all_goals (try simp only [BitVec.sle_iff_toInt_le] at *) + all_goals (try grind) + -- One iteration: the invariant holds again. + · rename_i hpre _ h0 s _ max hb _ hov hinv + obtain ⟨⟨⟨j, hj0, hji, hmax⟩, habove, hi0, hin⟩, hlt⟩ := hinv + have hmaxdef : max = if s.1.slt nums[s.2.toNat]! = true then nums[s.2.toNat]! else s.1 := rfl + clear_value max + subst hmaxdef + rw [Int.emod_eq_of_lt (by omega) (by omega)] + refine ⟨?_, ?_, by omega, by omega⟩ + · split + · exact ⟨s.2, by omega, by omega, rfl⟩ + · exact ⟨j, hj0, by omega, hmax⟩ + · intro k hk0 hk + split + · next hslt => + rw [BitVec.slt_iff_toInt_lt] at hslt + by_cases hki : k < s.2 + · have := habove k hk0 hki + omega + · obtain rfl : k = s.2 := by omega + exact Int.le_refl _ + · next hslt => + rw [BitVec.slt_iff_toInt_lt] at hslt + by_cases hki : k < s.2 + · exact habove k hk0 hki + · obtain rfl : k = s.2 := by omega + omega + -- Entry: the prefix is just `nums[0]`. + · rename_i hpre _ h0 + refine ⟨⟨0, by omega, by omega, by simp⟩, ?_, by omega, by exact_mod_cast h0⟩ + intro k hk0 hk + obtain rfl : k = 0 := by omega + simp + +/-- info: 'Strata.Shallow.Test.pick_nat_spec' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms pick_nat_spec + +/-- info: 'Strata.Shallow.Test.sum_to_spec' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms sum_to_spec + +/-- info: 'Strata.Shallow.Test.find_max_spec' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms find_max_spec + +end Strata.Shallow.Test diff --git a/docs/ShallowEmbedding.md b/docs/ShallowEmbedding.md new file mode 100644 index 0000000..bcc0dc9 --- /dev/null +++ b/docs/ShallowEmbedding.md @@ -0,0 +1,89 @@ +# Shallow embedding of Strata in Lean + +The goal is to interpret Strata Core programs in Lean as computations in a +nondeterministic state monad. Verification conditions come from proved +weakest-precondition rules, so the generator is sound by construction. The design follows +Velvet; the code builds on Lean's `Std.Do` and `mvcgen`. Boole programs reach it through +their lowering to Core. + +```mermaid +flowchart TD + B["Boole program"] -->|toCoreProgram| C["Strata Core program"] + subgraph solver ["Solver path"] + V["VC generation and SMT encoding"] --> S["cvc5, or Lean via lean-smt"] + end + subgraph lean ["Lean path"] + T["Core to Lean (planned)"] --> G["Std.Do + mvcgen + Layer.lean"] + G --> P["Lean proof"] + end + C --> V + C --> T +``` + +## Decisions + +- **Input is Core**, which has a formal semantics (`StatementSemantics.lean`), so the + interpretation can be proved adequate against it. Boole and other front ends lower to + Core. +- **Framework: `Std.Do` and `mvcgen`**, available in Lean 4.29 and 4.31. Lean marks + `mvcgen` experimental; its successor `vcgen` needs Lean 4.33. +- **No Velvet dependency:** Velvet needs Lean 4.34. + +## Mapping + +| Core | Lean | +| --- | --- | +| assignments, `if`, locals | `do` notation | +| `exit` from a loop or the procedure | `break`, `return` | +| other labeled `exit` | to do, e.g. one exception per label | +| `while` without a measure, `havoc`, `assume`, `assert` | `Layer.lean` | +| `while` with a measure, nondeterministic `init`, `if *`, `while *` | to do | +| `call` | the callee's proved specification | +| `in`, `inout`, `out` parameters (Boole's globals and `modifies` become these) | arguments and results | +| `int`, `bool`, `nat`, `bv n`, `Sequence`, `Map` | `Int`, `Bool`, `Nat`, `BitVec n`, `List`/`Array`, functions | +| datatypes | inductive types | +| `cover`, local function and type declarations | to do | + +## Status + +`StrataBoole/Shallow/Layer.lean` provides a nondeterminism monad with `havoc`, `assume`, +`assert` and a `while` loop carrying its invariant, each with a proved rule. +`StrataBooleTest/shallow_find_max.lean` verifies three hand-written programs with it, +find max among them, and fixes the form the translation should produce. The proofs use +only Lean's standard axioms. + +## Research questions + +1. **Variables:** represent program variables so that verification conditions range over + Lean values. In the hand-written programs they already are; the open part is getting + there from Core, in particular with an interpreter. +2. **Invariants:** pass the invariants recorded in the program to the monadic loop rules. + `whileInv` takes the invariant as an argument and its rule uses it; loops with a + measure are still missing. +3. **Adequacy:** prove the interpretation adequate with respect to Core's operational + semantics. One detail: in Core a failed `assert` sets a failure flag and execution + continues, while in `Layer.lean` it ends the run. +4. **`cover` and frames** have no counterpart in Velvet. Frames follow from Core's + `in`/`inout` parameters. `cover` checks that some path reaches it with its condition + true, which is not a weakest-precondition fact. + +## Open questions + +- **Translator or interpreter:** generate Lean code for each program, or define the + interpretation as one Lean function, which makes adequacy a single theorem. +- **Execution:** `ND` is a set of outcomes, so it cannot run programs; Velvet's monad can. +- **`assume`:** in Boogie an impossible `assume` makes the path vacuous; Velvet's choice + operator instead requires proving that a value exists. `Layer.lean` follows Boogie. +- **Reads:** a checked read needs an `assert` or Lean's `a[i]'h`. Core leaves an + out-of-range `select!` unconstrained, while Lean's `a[i]!` returns a default value, + which proofs must not rely on. +- **Goal names:** `mvcgen` numbers the goals; they should carry the program's clause names. +- **Axioms:** a program's axioms become either Lean axioms, which are trusted, or + hypotheses of each theorem. + +## Sources + +- [Velvet (CAV'26)](https://ilyasergey.net/assets/pdf/papers/velvet-cav26.pdf) +- [Foundational Multi-Modal Program Verifiers (Loom, POPL'26)](https://ilyasergey.net/assets/pdf/papers/loom-popl26.pdf) +- [verse-lab/velvet](https://github.com/verse-lab/velvet) +- [ilyasergey/lean-vcgen-tutorial](https://github.com/ilyasergey/lean-vcgen-tutorial) From 4c50465a257162482aa07a636acdfe11d7846c85 Mon Sep 17 00:00:00 2001 From: Stephanie Ma Date: Mon, 12 Oct 2026 21:09:16 -0700 Subject: [PATCH 02/64] Shallow embedding: Core-to-Lean translator (shallow_embed) with tests --- StrataBoole/Shallow/Emit.lean | 168 ++++++++ StrataBoole/Shallow/Translate.lean | 519 +++++++++++++++++++++++++ StrataBooleTest.lean | 1 + StrataBooleTest/shallow_translate.lean | 142 +++++++ 4 files changed, 830 insertions(+) create mode 100644 StrataBoole/Shallow/Emit.lean create mode 100644 StrataBoole/Shallow/Translate.lean create mode 100644 StrataBooleTest/shallow_translate.lean diff --git a/StrataBoole/Shallow/Emit.lean b/StrataBoole/Shallow/Emit.lean new file mode 100644 index 0000000..487253b --- /dev/null +++ b/StrataBoole/Shallow/Emit.lean @@ -0,0 +1,168 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import Lean +import Std.Do +import Std.Tactic.Do +import StrataBoole.Shallow.Layer + +/-! # Shallow embedding: emitting Lean syntax + +Builders for the `do`-notation programs and `Triple` theorems that the Core-to-Lean +translator produces (`StrataBoole.Shallow.Translate`). This half has no dependency on +Strata, so the shape of the output can be fixed and tested on its own. + +The generated code refers to the layer (`Strata.Shallow.ND.*`) by full name (the layer is +imported here so the quotations pre-resolve those names) and wraps each theorem in +`open Std.Do in`, because the triple notations `⦃ ⦄`, `⌜ ⌝`, `⇓` are scoped. The output shape follows `StrataBooleTest/shallow_find_max.lean`: +parameters are arguments, locals are `let mut`, a loop is `whileInv` on the tuple of +the variables its body assigns. +-/ + +open Lean Elab Command Term Meta +open Std.Do + +namespace Strata.Shallow.Emit + +abbrev DoItem := TSyntax ``Lean.Parser.Term.doSeqItem +abbrev DoElem := TSyntax `doElem + +/-- Wrap a `doElem` as a sequence item. -/ +def item (e : DoElem) : MacroM DoItem := `(Lean.Parser.Term.doSeqItem| $e:doElem) + +/-- `do` block from items; an empty block is `pure ()`. -/ +def doBlock (items : Array DoItem) : MacroM Term := do + if items.isEmpty then `(do pure ()) else `(do $items*) + +/-! ## Tuples: right-nested products, as Lean's `(a, b, c)` -/ + +/-- `(a, b, c)`; `()` for none; the term itself for one. -/ +def tuple (xs : Array Term) : MacroM Term := do + match xs.size with + | 0 => `(()) + | 1 => pure xs[0]! + | _ => + let x := xs[0]! + let rest := xs[1:].toArray + `(($x, $rest,*)) + +/-- `A × B × C`; `Unit` for none. -/ +def tupleType (ts : Array Term) : MacroM Term := do + match ts.size with + | 0 => `(Unit) + | _ => do + let mut acc := ts.back! + for t in ts.pop.reverse do + acc ← `($t × $acc) + pure acc + +/-- Projection of component `j` out of `k` from a right-nested tuple `s`. -/ +def proj (s : Term) (j k : Nat) : MacroM Term := do + if k ≤ 1 then pure s + else + let mut acc := s + for _ in [:j] do + acc ← `(($acc).2) + if j + 1 < k then `(($acc).1) else pure acc + +/-! ## Statements -/ + +def letMut (x : Ident) (ty : Term) (e : Term) : MacroM DoElem := + `(doElem| let mut $x:ident : $ty := $e) + +def letMutHavoc (x : Ident) (ty : Term) : MacroM DoElem := + `(doElem| let mut $x:ident : $ty ← Strata.Shallow.ND.havoc) + +def assign (x : Ident) (e : Term) : MacroM DoElem := + `(doElem| $x:ident := $e) + +def assignHavoc (x : Ident) : MacroM DoElem := + `(doElem| $x:ident ← Strata.Shallow.ND.havoc) + +def assume (p : Term) : MacroM DoElem := + `(doElem| Strata.Shallow.ND.assume $p) + +def assert (p : Term) : MacroM DoElem := + `(doElem| Strata.Shallow.ND.assert $p) + +def ret (e : Term) : MacroM DoElem := + `(doElem| return $e) + +/-- `if c then … else …`; an empty branch becomes `pure ()`. -/ +def ite (c : Term) (thenItems elseItems : Array DoItem) : MacroM DoElem := do + let thenItems ← if thenItems.isEmpty then pure #[← item (← `(doElem| pure ()))] else pure thenItems + if elseItems.isEmpty then + `(doElem| if $c then $thenItems*) + else + `(doElem| if $c then $thenItems* else $elseItems*) + +/-- A nondeterministic branch: `let b ← havoc; if b then … else …`. -/ +def iteNondet (b : Ident) (thenItems elseItems : Array DoItem) : MacroM (Array DoElem) := do + let pick ← `(doElem| let $b:ident : Bool ← Strata.Shallow.ND.havoc) + let branch ← ite (← `($b)) thenItems elseItems + pure #[pick, branch] + +/-- A `while` loop with invariant on the state tuple of the variables `vars` that the body +assigns. `inv` and `guard` receive the state term (so the caller can substitute projections +for the variables); `body` receives it as well and returns the body items, which may assign +the `vars` (they are rebound with `let mut` from the state). Generic in the monad so the +translator can run its own context inside the callbacks. Returns the items: the loop +bound to `s`, then one assignment per variable. -/ +def whileInv {m : Type → Type} [Monad m] [MonadLiftT MacroM m] + (s : Ident) (vars : Array Ident) (tys : Array Term) + (inv guard : Term → m Term) (body : Term → m (Array DoItem)) : + m (Array DoItem) := do + let k := vars.size + let stTy ← (tupleType tys : MacroM Term) + let sTerm : Term ← (`($s) : MacroM Term) + let invBody ← inv sTerm + let guardBody ← guard sTerm + let invFn ← (`(fun ($s : $stTy) => $invBody) : MacroM Term) + let guardFn ← (`(fun ($s : $stTy) => $guardBody) : MacroM Term) + -- body: rebind each variable mutably from the state, run the body, return the tuple + let mut bodyItems : Array DoItem := #[] + for j in [:k] do + let pj ← (proj sTerm j k : MacroM Term) + let v := vars[j]! + let t := tys[j]! + bodyItems := bodyItems.push (← (do item (← `(doElem| let mut $v:ident : $t := $pj)) : MacroM DoItem)) + bodyItems := bodyItems ++ (← body sTerm) + let tup ← (tuple (vars.map fun v => (v : Term)) : MacroM Term) + bodyItems := bodyItems.push (← (do item (← `(doElem| pure $tup)) : MacroM DoItem)) + let bodyBlock ← (doBlock bodyItems : MacroM Term) + let bodyFn ← (`(fun ($s : $stTy) => $bodyBlock) : MacroM Term) + let init ← (tuple (vars.map fun v => (v : Term)) : MacroM Term) + let loop ← (do item (← `(doElem| let $s:ident ← Strata.Shallow.ND.whileInv $invFn $guardFn $bodyFn $init)) : MacroM DoItem) + let mut out : Array DoItem := #[loop] + for j in [:k] do + let pj ← (proj sTerm j k : MacroM Term) + let v := vars[j]! + out := out.push (← (do item (← `(doElem| $v:ident := $pj)) : MacroM DoItem)) + pure out + +/-! ## Declarations -/ + +/-- `def name (x₁ : T₁) … : Strata.Shallow.ND R := body`. -/ +def procDef (name : Ident) (params : Array (Ident × Term)) (retTy : Term) (body : Term) : + MacroM Command := do + let binders ← params.mapM fun (x, t) => `(bracketedBinder| ($x:ident : $t)) + `(command| def $name:ident $binders* : Strata.Shallow.ND $retTy := $body) + +/-- `theorem name_spec (x₁ : T₁) … : ⦃⌜pre⌝⦄ name x₁ … ⦃⇓ r => ⌜post⌝⦄ := by …`, wrapped in +`open Std.Do in` for the scoped notation and with the experimental-tactic warning off. -/ +def specTheorem (thmName fnName : Ident) (params : Array (Ident × Term)) (pre : Term) + (r : Ident) (post : Term) : MacroM Command := do + let binders ← params.mapM fun (x, t) => `(bracketedBinder| ($x:ident : $t)) + let args : Array Term := params.map fun (x, _) => (x : Term) + let warnOpt := mkIdent `mvcgen.warning + let stdDo := mkIdent `Std.Do + `(command| + set_option $warnOpt:ident false in + open $stdDo:ident in + theorem $thmName:ident $binders* : + ⦃⌜$pre⌝⦄ $fnName:ident $args* ⦃⇓ $r:ident => ⌜$post⌝⦄ := by + (mvcgen [$fnName:ident]; all_goals (try grind))) + +end Strata.Shallow.Emit diff --git a/StrataBoole/Shallow/Translate.lean b/StrataBoole/Shallow/Translate.lean new file mode 100644 index 0000000..541d857 --- /dev/null +++ b/StrataBoole/Shallow/Translate.lean @@ -0,0 +1,519 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.Verify +import StrataBoole.Shallow.Layer +import StrataBoole.Shallow.Emit + +/-! # Shallow embedding: Core to Lean + +`shallow_embed p` takes a `StrataDDM.Program` (a `#strata program Boole; … #end` block), +lowers and type-checks it with `Strata.Boole.typeCheck` (`getProgram → toCoreProgram → +Core.typeCheck`, i.e. before any Core transform phase), and for every procedure emits + +* `def p (inputs) : Strata.Shallow.ND (outputs) := do …` +* `theorem p_spec (inputs) : ⦃⌜requires⌝⦄ p inputs ⦃⇓ r => ⌜ensures⌝⦄ := by mvcgen [p]; …` + +in the shape fixed by `StrataBooleTest/shallow_find_max.lean`: parameters are arguments, +outputs are `let mut` variables (arbitrary at entry, copies of the input for `inout`), +locals are `let mut`, a loop is `whileInv` on the tuple of the variables its body assigns. + +Supported in this first cut: `init`, `set`, `havoc`, `assert`, `assume`, deterministic and +nondeterministic `if`, deterministic `while` with invariants (partial correctness; a measure +is ignored with a warning), the procedure's own `exit` (Boole `return`) outside loops, and +the `int`/`bool`/`bv`/`Map`/`Sequence` expression layer. Not yet: `call`, `cover`, labelled +`exit`, nondeterministic `while`, local `function`/`type`, `old`, clause names on goals. + +Operators that carry a precondition obligation in Core (`Safe*`, the checked sequence +operations) are rejected rather than translated without their obligation. The total +operations are mapped to Lean's total functions: `Int.Div`/`Int.Mod` to `/`/`%` (Euclidean on +both sides), `DivT`/`ModT` to `Int.tdiv`/`Int.tmod`, `select!` to `a[i]!`. Where Core leaves a +result unconstrained (division by zero, out-of-range `select!`) Lean returns a default value; +a proof must not rely on that value (open decision in `docs/ShallowEmbedding.md`). +-/ + +open Lean Elab Command Term Meta +open Lambda Imperative +open Strata.Shallow.Emit + +namespace Strata.Shallow.Translate + +/-- Lower and type-check; render the error as a string so the result can be evaluated at +elaboration time without naming Strata's message type. -/ +def typeCheckStr (p : StrataDDM.Program) : Except String Core.Program := + match Strata.Boole.typeCheck p Core.VerifyOptions.quiet with + | .ok cp => .ok cp + | .error m => .error (toString (m.format none)) + +/-! ## Translation monad -/ + +/-- What the translator knows while walking a procedure body. -/ +structure Ctx where + /-- Lean term standing for each Core variable in scope: its identifier, or, inside a loop's + invariant and guard, a projection of the loop state. -/ + vars : Std.HashMap String Term := {} + /-- Types of the variables in scope (Bool-typed variables become `x = true` in `Prop`). -/ + tys : Std.HashMap String LMonoTy := {} + /-- Enclosing expression binders for de Bruijn indices, innermost first. -/ + bvars : List (Ident × Option LMonoTy) := [] + /-- The procedure's own block label; `exit` to it is `return`. -/ + procLabel : String := "" + /-- The output variables, returned by `exit procLabel` and at the end of the body. -/ + outputs : Array Ident := #[] + /-- Inside a loop body, `return` would leave the body function, not the procedure. -/ + inLoop : Bool := false + +structure St where + fresh : Nat := 0 + warnings : Array String := #[] + +abbrev TransM := ReaderT Ctx (StateT St MacroM) + +def warn (msg : String) : TransM Unit := + modify fun s => { s with warnings := s.warnings.push msg } + +def fresh (base : String) : TransM Ident := do + let n ← modifyGet fun s => (s.fresh, { s with fresh := s.fresh + 1 }) + pure (mkIdent (Name.mkSimple s!"__{base}{n}")) + +def ident (x : String) : Ident := mkIdent (Name.mkSimple x) + +def fail {α} (msg : String) : TransM α := Macro.throwError s!"shallow_embed: {msg}" + +/-! ## Types -/ + +partial def transTy (t : LMonoTy) : TransM Term := do + match t with + | .tcons "int" [] => `(Int) + | .tcons "bool" [] => `(Bool) + | .tcons "nat" [] => `(Nat) + | .tcons "real" [] => `(Rat) + | .tcons "string" [] => `(String) + | .bitvec n => `(BitVec $(quote n)) + | .tcons "Map" [k, v] => do `($(← transTy k) → $(← transTy v)) + | .tcons "Sequence" [a] => do `(Array $(← transTy a)) + | .tcons "arrow" [a, b] => do `($(← transTy a) → $(← transTy b)) + | .tcons n [] => pure (ident n) + | .tcons n args => do + let args ← args.mapM transTy + `($(ident n) $(args.toArray)*) + | .ftvar n => pure (ident n) + +def isBoolTy : Option LMonoTy → Bool + | some (.tcons "bool" []) => true + | _ => false + +/-- Result type of an operator of type `ty` applied to `n` arguments. -/ +def resultTy : Option LMonoTy → Nat → Option LMonoTy + | some (.tcons "arrow" [_, b]), n + 1 => resultTy (some b) n + | t, 0 => t + | _, _ => none + +/-! ## Expressions -/ + +/-- `prop`: the result is a `Prop` (assertion positions). `val`: the result is a value, a +`Bool` for Boolean expressions. -/ +inductive Mode | prop | val + +def asProp (t : Term) : TransM Term := `($t = true) +def asBool (p : Term) : TransM Term := `(decide $p) + +/-- Head and arguments of an application spine. -/ +def spine : Core.Expression.Expr → Core.Expression.Expr × List Core.Expression.Expr + | .app _ f a => let (h, as) := spine f; (h, as ++ [a]) + | e => (e, []) + +def conj (ps : List Term) : TransM Term := do + match ps with + | [] => `(True) + | [p] => pure p + | p :: rest => do `($p ∧ $(← conj rest)) + +def transConst (mode : Mode) (c : LConst) : TransM Term := do + match c with + | .intConst i => + if i < 0 then `((-$(quote i.natAbs) : Int)) else `(($(quote i.toNat) : Int)) + | .boolConst b => + match mode, b with + | .prop, true => `(True) + | .prop, false => `(False) + | .val, true => `(true) + | .val, false => `(false) + | .strConst s => pure (quote s) + | .bitvecConst n v => `(($(quote v.toNat) : BitVec $(quote n))) + | .realConst _ => fail "real constants are not supported yet" + +/-- A binder name for a quantifier or lambda that does not clash with enclosing binders. -/ +def binderName (n : String) : TransM Ident := do + let base := if n.isEmpty then "x" else n + let taken := (← read).bvars.map (·.1.getId) + if taken.contains (Name.mkSimple base) then fresh base else pure (ident base) + +mutual + +partial def transExpr (mode : Mode) (e : Core.Expression.Expr) : TransM Term := do + let ctx ← read + match e with + | .const _ c => transConst mode c + | .fvar _ x ty => + let t := ctx.vars.getD x.name (ident x.name) + let ty := ty <|> ctx.tys[x.name]? + match mode with + | .prop => if isBoolTy ty then asProp t else pure t + | .val => pure t + | .bvar _ i => + match ctx.bvars[i]? with + | some (x, ty) => + match mode with + | .prop => if isBoolTy ty then asProp x else pure x + | .val => pure x + | none => fail s!"unbound de Bruijn index {i}" + | .op _ o ty => transOp mode o.name ty [] + | .app .. => + let (h, args) := spine e + match h with + | .op _ o ty => transOp mode o.name ty args + | _ => + let f ← transExpr .val h + let args ← args.mapM (transExpr .val) + `($f $(args.toArray)*) + | .ite _ c t f => + let c ← transExpr .prop c + let t ← transExpr mode t + let f ← transExpr mode f + `(if $c then $t else $f) + | .eq _ a b => + let a ← transExpr .val a + let b ← transExpr .val b + match mode with + | .prop => `($a = $b) + | .val => `(decide ($a = $b)) + | .quant _ k n ty _trig body => + let x ← binderName n + let some mty := ty | fail "quantifier without a type annotation" + let tyT ← transTy mty + let body ← withReader (fun c => { c with bvars := (x, ty) :: c.bvars }) (transExpr .prop body) + let p ← match k with + | .all => `(∀ $x:ident : $tyT, $body) + | .exist => `(∃ $x:ident : $tyT, $body) + match mode with + | .prop => pure p + | .val => asBool p + | .abs _ n ty body => + let x ← binderName n + let body ← withReader (fun c => { c with bvars := (x, ty) :: c.bvars }) (transExpr .val body) + match ty with + | some mty => do `(fun ($x:ident : $(← transTy mty)) => $body) + | none => `(fun $x:ident => $body) + +/-- Operators by their Core name (`CoreOp.toString`): `Int.Add`, `Bool.And`, `Bv32.SLt`, +`select`, `Sequence.length`, …; anything else is a user function. -/ +partial def transOp (mode : Mode) (name : String) (ty : Option LMonoTy) + (args : List Core.Expression.Expr) : TransM Term := do + let vals : TransM (List Term) := args.mapM (transExpr .val) + let props : TransM (List Term) := args.mapM (transExpr .prop) + -- a predicate: `Prop` in prop mode, `Bool` via `decide` in val mode + let cmp (p : Term) : TransM Term := match mode with | .prop => pure p | .val => asBool p + -- a `Bool`-valued operation: `= true` in prop mode + let boolRes (t : Term) : TransM Term := match mode with | .prop => asProp t | .val => pure t + let un (f : Term → TransM Term) : TransM Term := do + match ← vals with | [a] => f a | _ => fail s!"{name}: expected one argument" + let bin (f : Term → Term → TransM Term) : TransM Term := do + match ← vals with | [a, b] => f a b | _ => fail s!"{name}: expected two arguments" + let binP (f : Term → Term → TransM Term) : TransM Term := do + match ← props with | [a, b] => f a b | _ => fail s!"{name}: expected two arguments" + let unP (f : Term → TransM Term) : TransM Term := do + match ← props with | [a] => f a | _ => fail s!"{name}: expected one argument" + let parts := name.splitOn "." + match parts with + -- integers and reals + | ["Int", k] | ["Real", k] => + match k with + | "Add" => bin fun a b => `($a + $b) + | "Sub" => bin fun a b => `($a - $b) + | "Mul" => bin fun a b => `($a * $b) + | "Neg" => un fun a => `(-$a) + | "Div" => bin fun a b => `($a / $b) + | "Mod" => bin fun a b => `($a % $b) + | "DivT" => bin fun a b => `(Int.tdiv $a $b) + | "ModT" => bin fun a b => `(Int.tmod $a $b) + | "SafeDiv" | "SafeMod" | "SafeDivT" | "SafeModT" => + fail s!"{name} carries a precondition obligation that the translator does not emit yet" + + | "Lt" => bin fun a b => do cmp (← `($a < $b)) + | "Le" => bin fun a b => do cmp (← `($a ≤ $b)) + | "Gt" => bin fun a b => do cmp (← `($a > $b)) + | "Ge" => bin fun a b => do cmp (← `($a ≥ $b)) + | _ => + if k.startsWith "ToBv" then + let some n := (String.ofList (k.toList.drop 4)).toNat? | fail s!"bad operator {name}" + un fun a => `(BitVec.ofInt $(quote n) $a) + else fail s!"operator {name} is not supported yet" + -- booleans + | ["Bool", k] => + match mode, k with + | .prop, "And" => binP fun a b => `($a ∧ $b) + | .prop, "Or" => binP fun a b => `($a ∨ $b) + | .prop, "Not" => unP fun a => `(¬ $a) + | .prop, "Implies" => binP fun a b => `($a → $b) + | .prop, "Equiv" => binP fun a b => `($a ↔ $b) + | .val, "And" => bin fun a b => `($a && $b) + | .val, "Or" => bin fun a b => `($a || $b) + | .val, "Not" => un fun a => `(!$a) + | .val, "Implies" => bin fun a b => `(!$a || $b) + | .val, "Equiv" => bin fun a b => `($a == $b) + | _, _ => fail s!"operator {name} is not supported yet" + -- bit vectors `Bv{n}.{kind}` + | [bv, k] => + if bv.startsWith "Bv" then + match k with + | "Add" => bin fun a b => `($a + $b) + | "Sub" => bin fun a b => `($a - $b) + | "Mul" => bin fun a b => `($a * $b) + | "Neg" => un fun a => `(-$a) + | "Not" => un fun a => `(~~~$a) + | "And" => bin fun a b => `($a &&& $b) + | "Or" => bin fun a b => `($a ||| $b) + | "Xor" => bin fun a b => `($a ^^^ $b) + | "Shl" => bin fun a b => `($a <<< $b) + | "UShr" => bin fun a b => `($a >>> $b) + | "SShr" => bin fun a b => `(BitVec.sshiftRight $a ($b).toNat) + | "UDiv" => bin fun a b => `($a / $b) + | "UMod" => bin fun a b => `($a % $b) + | "SDiv" => bin fun a b => `(BitVec.sdiv $a $b) + | "SMod" => bin fun a b => `(BitVec.smod $a $b) + | "ULt" => bin fun a b => do cmp (← `($a < $b)) + | "ULe" => bin fun a b => do cmp (← `($a ≤ $b)) + | "UGt" => bin fun a b => do cmp (← `($a > $b)) + | "UGe" => bin fun a b => do cmp (← `($a ≥ $b)) + | "SLt" => bin fun a b => do boolRes (← `(BitVec.slt $a $b)) + | "SLe" => bin fun a b => do boolRes (← `(BitVec.sle $a $b)) + | "SGt" => bin fun a b => do boolRes (← `(BitVec.slt $b $a)) + | "SGe" => bin fun a b => do boolRes (← `(BitVec.sle $b $a)) + | "Concat" => bin fun a b => `($a ++ $b) + | "ToUInt" => un fun a => `((($a).toNat : Int)) + | "ToInt" => un fun a => `(($a).toInt) + | _ => + if k.startsWith "Extract_" then + match (String.ofList (k.toList.drop 8)).splitOn "_" with + | [hi, lo] => + let some hi := hi.toNat? | fail s!"bad operator {name}" + let some lo := lo.toNat? | fail s!"bad operator {name}" + un fun a => `(BitVec.extractLsb $(quote hi) $(quote lo) $a) + | _ => fail s!"bad operator {name}" + else if k.startsWith "Safe" || k.endsWith "Overflow" then + fail s!"{name} carries an overflow obligation that the translator does not emit yet" + else fail s!"operator {name} is not supported yet" + else if bv == "Sequence" then + match k with + | "length" => un fun s => `((($s).size : Int)) + | "select!" => bin fun s i => `($s[($i).toNat]!) + | "update!" => do + match ← vals with + | [s, i, v] => `(($s).set! ($i).toNat $v) + | _ => fail s!"{name}: expected three arguments" + | "empty" => `(#[]) + | "append" => bin fun a b => `($a ++ $b) + | "contains" => bin fun s v => do boolRes (← `(($s).contains $v)) + | "take!" => bin fun s n => `(($s).extract 0 ($n).toNat) + | "drop!" => bin fun s n => `(($s).extract ($n).toNat ($s).size) + | "select" | "update" | "take" | "drop" => + fail s!"{name} carries a bounds obligation that the translator does not emit yet; the unchecked `{k}!` form is translated" + | _ => fail s!"operator {name} is not supported yet" + else userFn + -- maps + | ["select"] => bin fun m k => `($m $k) + | ["update"] => do + -- a lambda rather than `Function.update`, which lives in Mathlib + match ← vals with + | [m, k, v] => `(fun k' => if k' = $k then $v else $m k') + | _ => fail "update: expected three arguments" + | ["mapConst"] => un fun v => `(fun _ => $v) + | _ => userFn +where + /-- A user-declared function, applied; `= true` in prop mode if its result is `bool`. -/ + userFn : TransM Term := do + let vs ← args.mapM (transExpr .val) + let t ← if vs.isEmpty then pure (ident name : Term) else `($(ident name) $(vs.toArray)*) + match mode with + | .prop => if isBoolTy (resultTy ty args.length) then asProp t else pure t + | .val => pure t + +end + +/-! ## Statements -/ + +/-- The loop-carried variables of a body, as the contract states them: Strata's +`Block.modifiedVars` (`set`, `havoc`, call `inout`/`out` arguments, at any depth) minus the +variables the body itself declares (`Block.initVars`, i.e. `definedVars` with scoped names +included), first occurrence first. -/ +def loopVars (body : List Core.Statement) : List String := + let decl := (Imperative.Block.initVars body).map (·.name) + (((Imperative.Block.modifiedVars body).map (·.name)).filter (· ∉ decl)).eraseDups + +mutual + +partial def transStmts (ss : List Core.Statement) : TransM (Array DoItem) := do + match ss with + | [] => pure #[] + | .cmd (.cmd (.init x ty rhs _)) :: rest => + let some mty := ty.toMonoType? | fail s!"local {x.name} has a polymorphic type" + let tyT ← transTy mty + let xI := ident x.name + let it ← match rhs with + | .det e => do letMut xI tyT (← transExpr .val e) + | .nondet => letMutHavoc xI tyT + let restItems ← withReader + (fun c => { c with vars := c.vars.insert x.name xI, tys := c.tys.insert x.name mty }) + (transStmts rest) + pure (#[← item it] ++ restItems) + | s :: rest => + let items ← transStmt s + let restItems ← transStmts rest + pure (items ++ restItems) + +partial def transStmt (s : Core.Statement) : TransM (Array DoItem) := do + let ctx ← read + match s with + | .cmd (.cmd c) => + match c with + | .init x .. => fail s!"internal: init {x.name} not handled by transStmts" + | .set x (.det e) _ => do pure #[← item (← assign (ident x.name) (← transExpr .val e))] + | .set x .nondet _ => do pure #[← item (← assignHavoc (ident x.name))] + | .assert _ e _ => do pure #[← item (← assert (← transExpr .prop e))] + | .assume _ e _ => do pure #[← item (← assume (← transExpr .prop e))] + | .cover l _ _ => do warn s!"cover {l} ignored: no counterpart in the layer yet"; pure #[] + | .cmd (.call n _ _) => fail s!"call to {n}: procedure calls are not supported yet" + | .block _ ss _ => transStmts ss + | .ite (.det c) t e _ => do + let c ← transExpr .prop c + let t ← transStmts t + let e ← transStmts e + pure #[← item (← ite c t e)] + | .ite .nondet t e _ => do + let b ← fresh "b" + let t ← transStmts t + let e ← transStmts e + let elems ← iteNondet b t e + elems.mapM fun el => do pure (← item el) + | .loop (.det g) measure invs body _ => do + if measure.isSome then warn "loop measure ignored (partial correctness)" + let vars := (loopVars body).toArray + let tys ← vars.mapM fun x => do + let some t := ctx.tys[x]? | fail s!"loop assigns {x}, which is not in scope" + transTy t + let s ← fresh "s" + let k := vars.size + -- in the invariant and guard, each loop variable is a projection of the state + let withProj (st : Term) (act : TransM Term) : TransM Term := do + let mut m := ctx.vars + for j in [:k] do + m := m.insert vars[j]! (← proj st j k) + withReader (fun c => { c with vars := m }) act + let invConj : TransM Term := do + let ps ← invs.mapM fun (_, e) => transExpr .prop e + conj ps + whileInv s (vars.map ident) tys + (inv := fun st => withProj st invConj) + (guard := fun st => withProj st (transExpr .prop g)) + (body := fun _ => withReader (fun c => { c with inLoop := true }) (transStmts body)) + | .loop .nondet .. => fail "nondeterministic loops are not supported yet" + | .exit l _ => + if l == ctx.procLabel then + if ctx.inLoop then fail "exit (return) inside a loop body is not supported yet" + else do pure #[← item (← ret (← tuple (ctx.outputs.map fun o => (o : Term))))] + else fail s!"exit {l}: labelled exits are not supported yet" + | .funcDecl .. => fail "local function declarations are not supported (lift them first)" + | .typeDecl .. => fail "local type declarations are not supported (lift them first)" + +end + +/-! ## Procedures -/ + +def transProc (p : Core.Procedure) : TransM (Array Command) := do + let name := p.header.name.name + let inputs := p.header.inputs.toList + let outputs := p.header.outputs.toList + let inputNames := inputs.map (·.1.name) + let mut vars : Std.HashMap String Term := {} + let mut tys : Std.HashMap String LMonoTy := {} + for (x, t) in inputs ++ outputs do + vars := vars.insert x.name (ident x.name) + tys := tys.insert x.name t + let outIds := (outputs.map fun (o, _) => ident o.name).toArray + let ctx : Ctx := { vars, tys, procLabel := name, outputs := outIds } + let body ← match p.body with + | .structured ss => pure ss + | .cfg _ => fail s!"{name}: CFG bodies are not supported" + if body.isEmpty then + warn s!"{name}: no body (abstract procedure), skipped" + return #[] + -- the definition + let items ← withReader (fun _ => ctx) do + let mut pre : Array DoItem := #[] + for (o, t) in outputs do + let tyT ← transTy t + let oI := ident o.name + if inputNames.contains o.name then pre := pre.push (← item (← letMut oI tyT oI)) + else pre := pre.push (← item (← letMutHavoc oI tyT)) + let bodyItems ← transStmts body + let retItem ← item (← ret (← tuple (outIds.map fun o => (o : Term)))) + pure (pre ++ bodyItems ++ #[retItem]) + let params ← inputs.mapM fun (x, t) => do pure (ident x.name, ← transTy t) + let outTys ← outputs.mapM fun (_, t) => transTy t + let retTy ← tupleType outTys.toArray + let defCmd ← procDef (ident name) params.toArray retTy (← doBlock items) + -- the specification: requires (all) as precondition, non-free ensures as postcondition + let rName := if inputNames.contains "r" || outputs.any (·.1.name == "r") then "__r" else "r" + let r := ident rName + let k := outputs.length + let preT ← withReader (fun _ => ctx) do + conj (← p.spec.preconditions.toList.mapM fun (_, c) => transExpr .prop c.expr) + let postT ← do + let mut m := vars + for j in [:k] do + m := m.insert (outputs[j]!).1.name (← proj (r : Term) j k) + withReader (fun _ => { ctx with vars := m }) do + let checked := p.spec.postconditions.toList.filter fun (_, c) => + match c.attr with | .Free => false | _ => true + conj (← checked.mapM fun (_, c) => transExpr .prop c.expr) + let specCmd ← specTheorem (ident s!"{name}_spec") (ident name) params.toArray preT r postT + pure #[defCmd, specCmd] + +/-! ## The command -/ + +unsafe def evalProgramUnsafe (t : Term) : TermElabM Core.Program := do + let ty := mkApp2 (mkConst ``Except [.zero, .zero]) (mkConst ``String) (mkConst ``Core.Program) + let r ← Term.evalTerm (Except String Core.Program) ty (← `(Strata.Shallow.Translate.typeCheckStr $t)) + match r with + | .ok p => pure p + | .error m => throwError m!"shallow_embed: {m}" + +@[implemented_by evalProgramUnsafe] +opaque evalProgram (t : Term) : TermElabM Core.Program + +/-- `shallow_embed p`: translate every procedure of the Boole program `p` into a `def` on the +`ND` layer and a `_spec` theorem, elaborating both. The generated commands are shown as +info messages. -/ +syntax (name := shallowEmbed) "shallow_embed " term : command + +@[command_elab shallowEmbed] def elabShallowEmbed : CommandElab := fun stx => do + let `(shallow_embed $t:term) := stx | throwUnsupportedSyntax + let prog ← liftTermElabM (evalProgram t) + for d in prog.decls do + match d with + | .proc p _ => + let (cmds, st) ← liftMacroM (((transProc p).run {}).run {}) + for w in st.warnings do logWarning w + for c in cmds do + logInfo m!"{c}" + elabCommand c + | .func f _ => logWarning m!"shallow_embed: function {f.name.name} skipped (not supported yet)" + | .recFuncBlock .. => logWarning "shallow_embed: recursive functions skipped (not supported yet)" + | .ax .. => logWarning "shallow_embed: axiom skipped (not supported yet)" + | .type .. => logWarning "shallow_embed: type declaration skipped (not supported yet)" + | .distinct .. => logWarning "shallow_embed: distinct declaration skipped (not supported yet)" + +end Strata.Shallow.Translate diff --git a/StrataBooleTest.lean b/StrataBooleTest.lean index 4b39e7c..7e12b37 100644 --- a/StrataBooleTest.lean +++ b/StrataBooleTest.lean @@ -55,3 +55,4 @@ import StrataBooleTest.widening_casts import StrataBooleTest.inline_boole_defs import StrataBooleTest.seq_unsafe_ops import StrataBooleTest.shallow_find_max +import StrataBooleTest.shallow_translate diff --git a/StrataBooleTest/shallow_translate.lean b/StrataBooleTest/shallow_translate.lean new file mode 100644 index 0000000..57bcef3 --- /dev/null +++ b/StrataBooleTest/shallow_translate.lean @@ -0,0 +1,142 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.MetaVerifier +import StrataBoole.Shallow.Layer +import StrataBoole.Shallow.Translate + +/-! # The translator against the hand-written programs + +`shallow_embed` must produce, from Boole source, definitions on which the hand-written +specifications of `shallow_find_max.lean` still prove, and its own `_spec` theorems must +close. The three programs: `pick_nat` and `sum_to` (the sources recorded with the first +experiments) and the repository's Verus-emitted `findMax` without its final `call` +(procedure calls are not translated yet). -/ + +set_option mvcgen.warning false + +namespace Strata.Shallow.TranslateTest + +open Strata Std.Do Strata.Shallow Strata.Shallow.ND + +/-! ## `havoc` and `assume` -/ + +def pickNatPgm : StrataDDM.Program := #strata +program Boole; + +procedure pick_nat() returns (x : int) +spec { ensures x >= 0; } +{ havoc x; assume x >= 0; }; +#end + +#guard_msgs (drop info) in +shallow_embed pickNatPgm + +/-- The hand-written specification, unchanged. -/ +theorem pick_nat_spec' : ⦃⌜True⌝⦄ pick_nat ⦃⇓ x => ⌜x ≥ 0⌝⦄ := by + mvcgen [pick_nat] + +/-- info: 'Strata.Shallow.TranslateTest.pick_nat_spec' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms pick_nat_spec + +/-- info: 'Strata.Shallow.TranslateTest.pick_nat_spec'' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms pick_nat_spec' + +/-! ## A loop with an invariant -/ + +def sumToPgm : StrataDDM.Program := #strata +program Boole; + +procedure sum_to(n : int) returns (r : int) +spec { requires n >= 0; ensures 2 * r == n * (n + 1); } +{ + var i : int := 0; + r := 0; + while (i < n) + invariant 0 <= i && i <= n && 2 * r == i * (i + 1) + { + i := i + 1; + r := r + i; + } +}; +#end + +#guard_msgs (drop info) in +shallow_embed sumToPgm + +/-- The hand-written specification, unchanged. -/ +theorem sum_to_spec' (n : Int) (h : n ≥ 0) : + ⦃⌜True⌝⦄ sum_to n ⦃⇓ r => ⌜2 * r = n * (n + 1)⌝⦄ := by + mvcgen [sum_to] + all_goals grind + +/-- info: 'Strata.Shallow.TranslateTest.sum_to_spec' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms sum_to_spec + +/-- info: 'Strata.Shallow.TranslateTest.sum_to_spec'' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms sum_to_spec' + +/-! ## Maps, `if` without `else`, several invariants, quantifiers, a measure + +The program of `find_max_verus.lean` without its last statement, `call witnessOccurs(...)`. -/ + +def findMaxPgm : StrataDDM.Program := #strata +program Boole; + +procedure witnessOccurs(nums: Map int int, n: int, idx: int, value: int) returns () +spec { + requires 0 <= idx && idx < n; + requires value == nums[idx]; + ensures ∃ j: int . 0 <= j && j < n && value == nums[j]; +} +{ + assume ∃ j: int . 0 <= j && j < n && value == nums[j]; +}; + +procedure findMax (nums: Map int int, n: int) returns (ret: int) +spec { + requires n > 0; + ensures ∀ i: int . 0 <= i && i < n ==> ret >= nums[i]; + ensures ∃ j: int . 0 <= j && j < n && ret == nums[j]; +} +{ + var max : int := nums[0]; + var maxIndex : int := 0; + var i : int := 1; + + while (i < n) + decreases n - i + invariant (1 <= i && i <= n) + invariant (∀ k: int . 0 <= k && k < i ==> max >= nums[k]) + invariant (0 <= maxIndex && maxIndex < i && max == nums[maxIndex]) + { + if (nums[i] > max) { + max := nums[i]; + maxIndex := i; + } + i := i + 1; + } + assert 0 <= maxIndex && maxIndex < n && max == nums[maxIndex]; + ret := nums[maxIndex]; +}; +#end + +/-- warning: loop measure ignored (partial correctness) -/ +#guard_msgs (warning, drop info) in +shallow_embed findMaxPgm + +/-- info: 'Strata.Shallow.TranslateTest.witnessOccurs_spec' depends on axioms: [propext, Quot.sound] -/ +#guard_msgs in +#print axioms witnessOccurs_spec + +/-- info: 'Strata.Shallow.TranslateTest.findMax_spec' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms findMax_spec + +end Strata.Shallow.TranslateTest From dd5fa1a03b984e5f973c15de5110e0370fa23276 Mon Sep 17 00:00:00 2001 From: Stephanie Ma Date: Sat, 17 Oct 2026 14:24:02 -0700 Subject: [PATCH 03/64] Improve Emitter design for while loop --- StrataBoole/Shallow/Emit.lean | 55 +++++++++++++++++++---------------- 1 file changed, 30 insertions(+), 25 deletions(-) diff --git a/StrataBoole/Shallow/Emit.lean b/StrataBoole/Shallow/Emit.lean index 487253b..8d92cc1 100644 --- a/StrataBoole/Shallow/Emit.lean +++ b/StrataBoole/Shallow/Emit.lean @@ -105,42 +105,47 @@ def iteNondet (b : Ident) (thenItems elseItems : Array DoItem) : MacroM (Array D pure #[pick, branch] /-- A `while` loop with invariant on the state tuple of the variables `vars` that the body -assigns. `inv` and `guard` receive the state term (so the caller can substitute projections -for the variables); `body` receives it as well and returns the body items, which may assign -the `vars` (they are rebound with `let mut` from the state). Generic in the monad so the -translator can run its own context inside the callbacks. Returns the items: the loop -bound to `s`, then one assignment per variable. -/ +assigns. `inv` and `guard` receive the state term, so the caller can substitute projections +for the variables; `body` receives it as well and returns the body items, which may read and +assign the `vars`. Generic in the monad so the translator can run its own context inside the +callbacks. + +The tuple `(x₁, …, xₖ)` is built once and used in four places: as the pattern that unpacks the +state into mutable copies at the start of the body (`let mut (x₁, …, xₖ) := s`), as the new +state the body returns (`pure (x₁, …, xₖ)`), as the initial state passed to the loop, and as +the pattern that copies the final state back (`(x₁, …, xₖ) ← whileInv …`). Inside the body +the names refer to the body's own copies; outside, to the enclosing variables. With one +variable the pattern is the variable itself; with none the state is `()` and the loop is a +plain statement. Returns the single item for the loop. -/ def whileInv {m : Type → Type} [Monad m] [MonadLiftT MacroM m] (s : Ident) (vars : Array Ident) (tys : Array Term) (inv guard : Term → m Term) (body : Term → m (Array DoItem)) : m (Array DoItem) := do - let k := vars.size let stTy ← (tupleType tys : MacroM Term) let sTerm : Term ← (`($s) : MacroM Term) let invBody ← inv sTerm let guardBody ← guard sTerm let invFn ← (`(fun ($s : $stTy) => $invBody) : MacroM Term) let guardFn ← (`(fun ($s : $stTy) => $guardBody) : MacroM Term) - -- body: rebind each variable mutably from the state, run the body, return the tuple - let mut bodyItems : Array DoItem := #[] - for j in [:k] do - let pj ← (proj sTerm j k : MacroM Term) - let v := vars[j]! - let t := tys[j]! - bodyItems := bodyItems.push (← (do item (← `(doElem| let mut $v:ident : $t := $pj)) : MacroM DoItem)) - bodyItems := bodyItems ++ (← body sTerm) - let tup ← (tuple (vars.map fun v => (v : Term)) : MacroM Term) - bodyItems := bodyItems.push (← (do item (← `(doElem| pure $tup)) : MacroM DoItem)) - let bodyBlock ← (doBlock bodyItems : MacroM Term) + let stateTup ← (tuple (vars.map fun v => (v : Term)) : MacroM Term) + let unpack ← (do + match vars.size with + | 0 => pure #[] + | 1 => pure #[← item (← letMut vars[0]! tys[0]! sTerm)] + | _ => pure #[← item (← `(doElem| let mut $stateTup:term := $sTerm))] + : MacroM (Array DoItem)) + let bodyItems := unpack ++ (← body sTerm) + let ret ← (do item (← `(doElem| pure $stateTup)) : MacroM DoItem) + let bodyBlock ← (doBlock (bodyItems.push ret) : MacroM Term) let bodyFn ← (`(fun ($s : $stTy) => $bodyBlock) : MacroM Term) - let init ← (tuple (vars.map fun v => (v : Term)) : MacroM Term) - let loop ← (do item (← `(doElem| let $s:ident ← Strata.Shallow.ND.whileInv $invFn $guardFn $bodyFn $init)) : MacroM DoItem) - let mut out : Array DoItem := #[loop] - for j in [:k] do - let pj ← (proj sTerm j k : MacroM Term) - let v := vars[j]! - out := out.push (← (do item (← `(doElem| $v:ident := $pj)) : MacroM DoItem)) - pure out + let call ← (`(Strata.Shallow.ND.whileInv $invFn $guardFn $bodyFn $stateTup) : MacroM Term) + let loop ← (do + match vars.size with + | 0 => item (← `(doElem| $call:term)) + | 1 => item (← `(doElem| $(vars[0]!):ident ← $call:term)) + | _ => item (← `(doElem| $stateTup:term ← $call:term)) + : MacroM DoItem) + pure #[loop] /-! ## Declarations -/ From 8f49506862ff403ac567f48a2520acfe176e3103 Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Wed, 21 Oct 2026 12:17:31 +0300 Subject: [PATCH 04/64] Shallow embedding: prototype of the generic datatype model One inductive of constructor applications for all datatypes, with disjointness, injectivity and inversion proved once and pos.toInt by structural recursion. Not covered yet: Map fields keyed by a datatype and parametric datatypes. --- StrataBooleTest.lean | 1 + .../shallow_generic_datatypes.lean | 101 ++++++++++++++++++ docs/ShallowEmbedding.md | 7 +- 3 files changed, 107 insertions(+), 2 deletions(-) create mode 100644 StrataBooleTest/shallow_generic_datatypes.lean diff --git a/StrataBooleTest.lean b/StrataBooleTest.lean index 0581f7a..3c05129 100644 --- a/StrataBooleTest.lean +++ b/StrataBooleTest.lean @@ -62,3 +62,4 @@ import StrataBooleTest.FeatureRequests.seq_empty_literal import StrataBooleTest.FeatureRequests.sha256_compact_indexed import StrataBooleTest.CoreTests.DefineFunRecTests import StrataBooleTest.shallow_find_max +import StrataBooleTest.shallow_generic_datatypes diff --git a/StrataBooleTest/shallow_generic_datatypes.lean b/StrataBooleTest/shallow_generic_datatypes.lean new file mode 100644 index 0000000..6441aee --- /dev/null +++ b/StrataBooleTest/shallow_generic_datatypes.lean @@ -0,0 +1,101 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ + +/-! # A generic model of datatypes + +One Lean inductive of constructor applications interprets every datatype of +every program, so the interpreter knows a single type and nothing is generated +per program. The datatype laws (disjointness, injectivity, inversion) are +proved once; induction is recursion on the term. `pos` and `nat` from Boole's +`nat` library serve as the example. + +Not covered yet: `Map` fields keyed by a datatype (a negative occurrence) and +parametric datatypes. See `docs/ShallowEmbedding.md`. +-/ + +mutual +inductive DT : Type where + | mk (ctor : String) (args : List Arg) +inductive Arg : Type where + | int (i : Int) + | bool (b : Bool) + | dt (d : DT) +end + +namespace DT + +inductive ArgSort | int | bool | dt (name : String) +abbrev Sig := String → List (String × List ArgSort) + +mutual +inductive WS (sig : Sig) : String → DT → Prop where + | mk {d c args sorts} : (c, sorts) ∈ sig d → WSArgs sig sorts args → WS sig d (DT.mk c args) +inductive WSArgs (sig : Sig) : List ArgSort → List Arg → Prop where + | nil : WSArgs sig [] [] + | int {i ss as} : WSArgs sig ss as → WSArgs sig (.int :: ss) (.int i :: as) + | bool {b ss as} : WSArgs sig ss as → WSArgs sig (.bool :: ss) (.bool b :: as) + | dt {name v ss as} : WS sig name v → WSArgs sig ss as → WSArgs sig (.dt name :: ss) (.dt v :: as) +end + +/-- The carrier of datatype `d`: its well-sorted values. -/ +def Carrier (sig : Sig) (d : String) := { v : DT // WS sig d v } + +/-! The datatype laws, once, for all signatures. -/ + +theorem disjoint {c c' : String} {as as' : List Arg} (h : c ≠ c') : DT.mk c as ≠ DT.mk c' as' := by + intro e; cases e; exact h rfl + +theorem injective {c : String} {as as' : List Arg} (h : DT.mk c as = DT.mk c as') : as = as' := by + cases h; rfl + +theorem inversion {sig : Sig} {d : String} {v : DT} (h : WS sig d v) : + ∃ c args sorts, v = DT.mk c args ∧ (c, sorts) ∈ sig d ∧ WSArgs sig sorts args := by + cases h with + | mk hc hargs => exact ⟨_, _, _, rfl, hc, hargs⟩ + +/-! `pos = xH | xO pos | xI pos`, `nat = N0 | Npos pos` on the generic model. -/ + +def posSig : Sig + | "pos" => [("xH", []), ("xO", [.dt "pos"]), ("xI", [.dt "pos"])] + | "nat" => [("N0", []), ("Npos", [.dt "pos"])] + | _ => [] + +def is_xO : DT → Prop | .mk "xO" [_] => True | _ => False +def xO_h : DT → DT | .mk "xO" [.dt h] => h | _ => .mk "xH" [] + +/-- `pos.toInt` by structural recursion on the generic term. -/ +def posToInt : DT → Int + | .mk "xH" [] => 1 + | .mk "xO" [.dt h] => 2 * posToInt h + | .mk "xI" [.dt h] => 2 * posToInt h + 1 + | _ => 0 + +example : posToInt (.mk "xI" [.dt (.mk "xO" [.dt (.mk "xH" [])])]) = 5 := by decide + +example : Carrier posSig "pos" := ⟨.mk "xH" [], .mk (by simp [posSig]) .nil⟩ +example : Carrier posSig "nat" := ⟨.mk "N0" [], .mk (by simp [posSig]) .nil⟩ + +/-- A well-sorted `pos` is `xH`, or `xO`/`xI` of a well-sorted `pos`. -/ +theorem pos_cases {v : DT} (h : WS posSig "pos" v) : + v = .mk "xH" [] ∨ (∃ h', WS posSig "pos" h' ∧ (v = .mk "xO" [.dt h'] ∨ v = .mk "xI" [.dt h'])) := by + cases h with + | mk hc hargs => + simp [posSig] at hc + rcases hc with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩ + · cases hargs; exact .inl rfl + · cases hargs with | dt hv hrest => cases hrest; exact .inr ⟨_, hv, .inl rfl⟩ + · cases hargs with | dt hv hrest => cases hrest; exact .inr ⟨_, hv, .inr rfl⟩ + +/-- Induction over `pos`: recursion on the term size, using `pos_cases`. -/ +theorem posToInt_pos (v : DT) (hw : WS posSig "pos" v) : 0 < posToInt v := by + rcases pos_cases hw with e | ⟨h', hh', e | e⟩ <;> rw [e] + · simp [posToInt] + · have := posToInt_pos h' hh'; simp [posToInt]; omega + · have := posToInt_pos h' hh'; simp [posToInt]; omega +termination_by sizeOf v +decreasing_by all_goals (subst e; simp_wf; (try simp); omega) + +end DT diff --git a/docs/ShallowEmbedding.md b/docs/ShallowEmbedding.md index bcc0dc9..0ef6feb 100644 --- a/docs/ShallowEmbedding.md +++ b/docs/ShallowEmbedding.md @@ -49,8 +49,11 @@ flowchart TD `StrataBoole/Shallow/Layer.lean` provides a nondeterminism monad with `havoc`, `assume`, `assert` and a `while` loop carrying its invariant, each with a proved rule. `StrataBooleTest/shallow_find_max.lean` verifies three hand-written programs with it, -find max among them, and fixes the form the translation should produce. The proofs use -only Lean's standard axioms. +find max among them, and fixes the form the translation should produce. +`StrataBooleTest/shallow_generic_datatypes.lean` is a prototype of the generic datatype +model: one inductive of constructor applications for all datatypes, with the datatype laws +proved once and `pos.toInt` by structural recursion. The proofs use only Lean's standard +axioms. ## Research questions From ffe7e6904dc982f667af3a2ebd4edb51fc9221e5 Mon Sep 17 00:00:00 2001 From: Stephanie Ma Date: Sat, 24 Oct 2026 17:09:48 -0700 Subject: [PATCH 05/64] Ignore .DS_Store --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index 2b00952..d05bdc2 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,4 @@ .lake + +# macOS Finder metadata +.DS_Store From cb7a91ebe811a844c2b690e7af5268a88a1b2e78 Mon Sep 17 00:00:00 2001 From: Stephanie Ma Date: Sun, 25 Oct 2026 21:15:54 -0700 Subject: [PATCH 06/64] Shallow embedding: interpreter prototype (WIP) Add StrataBoole/Shallow/Interpreter/, which interprets Core statements as ND computations. The adequacy proof will be stated about this interpreter. - Interp.lean: the interpreter over a store of Lean values (FreeVarVal); expressions go through LExpr.denote after LExpr.typeCheck; a loop carries only the variables its body assigns. Calls, exit, nondeterministic loops and local type declarations are not interpreted yet. - Model.lean: partial concrete model of Core's built-ins for denote, no consistency proofs yet. - Sort.lean: recursion principle and decidable equality for LSort. - Reflect.lean, Command.lean: `shallow_reflect p` binds each procedure's type-checked Core AST to `_ast : Core.Procedure`. - Pipeline.lean: the type-checked Core program at elaboration time, shared with shallow_embed. --- StrataBoole/Shallow/Interpreter/Command.lean | 30 ++ StrataBoole/Shallow/Interpreter/Interp.lean | 350 +++++++++++++++++++ StrataBoole/Shallow/Interpreter/Model.lean | 209 +++++++++++ StrataBoole/Shallow/Interpreter/Reflect.lean | 188 ++++++++++ StrataBoole/Shallow/Interpreter/Sort.lean | 74 ++++ StrataBoole/Shallow/Pipeline.lean | 40 +++ docs/ShallowEmbedding.md | 10 + 7 files changed, 901 insertions(+) create mode 100644 StrataBoole/Shallow/Interpreter/Command.lean create mode 100644 StrataBoole/Shallow/Interpreter/Interp.lean create mode 100644 StrataBoole/Shallow/Interpreter/Model.lean create mode 100644 StrataBoole/Shallow/Interpreter/Reflect.lean create mode 100644 StrataBoole/Shallow/Interpreter/Sort.lean create mode 100644 StrataBoole/Shallow/Pipeline.lean diff --git a/StrataBoole/Shallow/Interpreter/Command.lean b/StrataBoole/Shallow/Interpreter/Command.lean new file mode 100644 index 0000000..5a84f3c --- /dev/null +++ b/StrataBoole/Shallow/Interpreter/Command.lean @@ -0,0 +1,30 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.Shallow.Pipeline +import StrataBoole.Shallow.Interpreter.Reflect + +/-! # `shallow_reflect`: the interpreter's entry point from Boole source + +`shallow_reflect p` type-checks the Boole program `p` (`Pipeline.lean`) and binds the Core AST +of every procedure to `_ast : Core.Procedure` (`Reflect.lean`). Statements about a +procedure, its meaning `interpProc M _ast` and its specification, are made on that +definition. -/ + +open Lean Elab Command + +namespace Strata.Shallow.Interp + +syntax (name := shallowReflect) "shallow_reflect " term : command + +@[command_elab shallowReflect] def elabShallowReflect : CommandElab := fun stx => do + let `(shallow_reflect $t:term) := stx | throwUnsupportedSyntax + let prog ← liftTermElabM (Pipeline.evalProgram t) + for d in prog.decls do + if let .proc p _ := d then + let astName := (← getCurrNamespace) ++ Name.mkSimple s!"{p.header.name.name}_ast" + liftTermElabM (Reflect.addProcedureAst astName p) + +end Strata.Shallow.Interp diff --git a/StrataBoole/Shallow/Interpreter/Interp.lean b/StrataBoole/Shallow/Interpreter/Interp.lean new file mode 100644 index 0000000..9ce2b51 --- /dev/null +++ b/StrataBoole/Shallow/Interpreter/Interp.lean @@ -0,0 +1,350 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +module + +public import StrataBoole.Verify +public import Strata.DL.Lambda.Denote.LExprDenote +import all Strata.DL.Lambda.Denote.LExprDenote +public import Strata.DL.Lambda.Denote.LExprAnnotated +import all Strata.DL.Lambda.Denote.LExprAnnotated +public import StrataBoole.Shallow.Layer +public import StrataBoole.Shallow.Interpreter.Sort + +/-! # The interpreter: Core statements as `ND` computations + +One Lean function gives every Core program its meaning in the `ND` layer. It is the object +the adequacy theorem is about (Core's operational semantics on one side, `interpStmts` on +the other) and the object that is unfolded on a concrete program to obtain its verification +conditions. + +* **Store.** `FreeVarVal Core.CoreLParams tcInterp`: a Lean value for every variable at every + sort. This is exactly the free-variable valuation that `LExpr.denote` reads, so expressions + are evaluated by `denote` directly; there is no second evaluator. +* **Expressions.** `evalExpr σ e τ` runs Strata's computable type checker `LExpr.typeCheck` + and, on success, `LExpr.denote` with the derivation obtained from `typeCheck_to_HasTypeA`. + An ill-typed expression makes the statement stuck (no outcome), mirroring a missing rule in + Core's semantics. +* **Loops are frame-aware.** The loop state carries only the variables the body assigns + (`Block.modifiedVars` minus `Block.initVars`); all other variables are read from the store + at loop entry (`Store.merge`). Without this the loop invariant would have to restate that + every unmodified variable is unchanged. +* **Blocks** restore the entry values of the names they declare on exit, as Core's + `projectStore` does. +* **Outputs** are arbitrary at procedure entry (`havoc`); an inout parameter keeps its input + value. +* **Unsupported for now** (`ND.fail`): procedure calls, `exit`, nondeterministic loops, local `type` + declarations. + +The model `(tcInterp, opInterp, vt)` is a parameter bundled in `Sem`; `Model.lean` provides +the concrete one for Core's built-ins. +-/ + +@[expose] public section + +namespace Strata.Shallow.Interp + +open Lambda Imperative Strata.Shallow + +/-- The semantic parameters: a type-constructor interpretation, an operator interpretation, +and a type-variable valuation. -/ +structure Sem where + tcInterp : TyConstrInterp + opInterp : OpInterp tcInterp + [inhab : TyConstrInterp.AllInhabited tcInterp] + vt : TyVarVal + +attribute [instance] Sem.inhab + +abbrev Ident := Core.CoreIdent + +/-! ### Re-exported unfolding lemmas for `denote` + +Strata states these without `public`; they are visible here only through `import all`, and a +module may use them in *proofs* of public theorems but not in public statements or exposed +bodies. A proof written in a user's file (or generated into it) can refer to public names only, +so each lemma is restated under a primed name. `denote_op'` and `denote_fvar'` are stated at the +annotated type (`τ := ty`), which is the form `typeCheck` produces, so no cast appears. +(`denote_boolConst`, `denote_eq_true`, `denote_quant_all_true` are already public.) -/ + +section ReExports + +variable {T : LExprParams} {tcInterp : TyConstrInterp} {opInterp : OpInterp tcInterp} + {fvarVal : FreeVarVal T tcInterp} {vt : TyVarVal} {Δ : List LMonoTy} + (bvarVal : BVarVal tcInterp vt Δ) + +theorem denote_intConst' {m : T.mono.base.Metadata} {i : Int} + (h : LExpr.HasTypeA Δ (.const m (.intConst i)) (.tcons "int" [])) : + LExpr.denote tcInterp opInterp fvarVal vt bvarVal (.const m (.intConst i)) (.tcons "int" []) h + = i := + Lambda.denote_intConst tcInterp opInterp fvarVal vt bvarVal h + +theorem denote_op' {m : T.mono.base.Metadata} {o : T.Identifier} {ty : LMonoTy} + (h : LExpr.HasTypeA Δ (.op m o (some ty)) ty) : + LExpr.denote tcInterp opInterp fvarVal vt bvarVal (.op m o (some ty)) ty h + = opInterp o.name (ty.substTyVars vt) := + Lambda.denote_op tcInterp opInterp fvarVal vt bvarVal h + +theorem denote_fvar' {m : T.mono.base.Metadata} {name : T.Identifier} {ty : LMonoTy} + (h : LExpr.HasTypeA Δ (.fvar m name (some ty)) ty) : + LExpr.denote tcInterp opInterp fvarVal vt bvarVal (.fvar m name (some ty)) ty h + = fvarVal name (ty.substTyVars vt) := + Lambda.denote_fvar tcInterp opInterp fvarVal vt bvarVal h + +theorem denote_bvar' {m : T.mono.base.Metadata} {i : Nat} {τ : LMonoTy} + (h : LExpr.HasTypeA Δ (.bvar m i) τ) : + LExpr.denote tcInterp opInterp fvarVal vt bvarVal (.bvar m i) τ h + = bvarVal.get i (HasTypeA.bvar_inv h) := + Lambda.denote_bvar tcInterp opInterp fvarVal vt bvarVal h + +theorem denote_app' {m : T.Metadata} {fn arg : LExpr T.mono} {aty τ : LMonoTy} + (h_fn : LExpr.HasTypeA Δ fn (.arrow aty τ)) (h_arg : LExpr.HasTypeA Δ arg aty) + (h_app : LExpr.HasTypeA Δ (.app m fn arg) τ) : + LExpr.denote tcInterp opInterp fvarVal vt bvarVal (.app m fn arg) τ h_app = + (LExpr.denote tcInterp opInterp fvarVal vt bvarVal fn (.arrow aty τ) h_fn) + (LExpr.denote tcInterp opInterp fvarVal vt bvarVal arg aty h_arg) := + Lambda.denote_app bvarVal h_fn h_arg h_app + +theorem denote_abs' {m : T.Metadata} {name : String} {body : LExpr T.mono} {aty rty : LMonoTy} + (h_body : LExpr.HasTypeA (aty :: Δ) body rty) + (h_abs : LExpr.HasTypeA Δ (.abs m name (some aty) body) (.arrow aty rty)) : + LExpr.denote tcInterp opInterp fvarVal vt bvarVal + (.abs m name (some aty) body) (.arrow aty rty) h_abs = + fun x => LExpr.denote tcInterp opInterp fvarVal vt (.cons x bvarVal) body rty h_body := + Lambda.denote_abs bvarVal h_body h_abs + +theorem denote_eq_false' {m : T.Metadata} {e1 e2 : LExpr T.mono} {ty' : LMonoTy} + (h_1 : LExpr.HasTypeA Δ e1 ty') (h_2 : LExpr.HasTypeA Δ e2 ty') + (h_eq : LExpr.HasTypeA Δ (.eq m e1 e2) .bool) + (hne : LExpr.denote tcInterp opInterp fvarVal vt bvarVal e1 ty' h_1 ≠ + LExpr.denote tcInterp opInterp fvarVal vt bvarVal e2 ty' h_2) : + LExpr.denote tcInterp opInterp fvarVal vt bvarVal (.eq m e1 e2) .bool h_eq = false := + Lambda.denote_eq_false bvarVal h_1 h_2 h_eq hne + +theorem denote_ite' {m : T.Metadata} {c t e : LExpr T.mono} {τ : LMonoTy} + (h_c : LExpr.HasTypeA Δ c .bool) (h_t : LExpr.HasTypeA Δ t τ) (h_e : LExpr.HasTypeA Δ e τ) + (h_ite : LExpr.HasTypeA Δ (.ite m c t e) τ) : + LExpr.denote tcInterp opInterp fvarVal vt bvarVal (.ite m c t e) τ h_ite = + bif LExpr.denote tcInterp opInterp fvarVal vt bvarVal c .bool h_c + then LExpr.denote tcInterp opInterp fvarVal vt bvarVal t τ h_t + else LExpr.denote tcInterp opInterp fvarVal vt bvarVal e τ h_e := + Lambda.denote_ite bvarVal h_c h_t h_e h_ite + +theorem denote_quant_all_false' {m : T.Metadata} {name : String} {tr body : LExpr T.mono} + {qty : LMonoTy} + (h_body : LExpr.HasTypeA (qty :: Δ) body .bool) + (h_quant : LExpr.HasTypeA Δ (.quant m .all name (some qty) tr body) .bool) + (w : TyDenote tcInterp vt qty) + (hw : (LExpr.denote tcInterp opInterp fvarVal vt (.cons w bvarVal) body .bool h_body : Bool) + = false) : + LExpr.denote tcInterp opInterp fvarVal vt bvarVal + (.quant m .all name (some qty) tr body) .bool h_quant = false := + Lambda.denote_quant_all_false bvarVal h_body h_quant w hw + +theorem denote_quant_exist_true' {m : T.Metadata} {name : String} {tr body : LExpr T.mono} + {qty : LMonoTy} + (h_body : LExpr.HasTypeA (qty :: Δ) body .bool) + (h_quant : LExpr.HasTypeA Δ (.quant m .exist name (some qty) tr body) .bool) + (w : TyDenote tcInterp vt qty) + (hw : (LExpr.denote tcInterp opInterp fvarVal vt (.cons w bvarVal) body .bool h_body : Bool) + = true) : + LExpr.denote tcInterp opInterp fvarVal vt bvarVal + (.quant m .exist name (some qty) tr body) .bool h_quant = true := + Lambda.denote_quant_exist_true bvarVal h_body h_quant w hw + +theorem denote_quant_exist_false' {m : T.Metadata} {name : String} {tr body : LExpr T.mono} + {qty : LMonoTy} + (h_body : LExpr.HasTypeA (qty :: Δ) body .bool) + (h_quant : LExpr.HasTypeA Δ (.quant m .exist name (some qty) tr body) .bool) + (hall : ∀ x : TyDenote tcInterp vt qty, + (LExpr.denote tcInterp opInterp fvarVal vt (.cons x bvarVal) body .bool h_body : Bool) + = false) : + LExpr.denote tcInterp opInterp fvarVal vt bvarVal + (.quant m .exist name (some qty) tr body) .bool h_quant = false := + Lambda.denote_quant_exist_false bvarVal h_body h_quant hall + +end ReExports + +/-- The store: a value for every variable at every sort (Strata's `FreeVarVal`). -/ +abbrev Store (M : Sem) := FreeVarVal Core.CoreLParams M.tcInterp + +/-- The sort of a Core type under the type-variable valuation. -/ +abbrev sortOf (M : Sem) (τ : LMonoTy) : LSort := LMonoTy.substTyVars M.vt τ + +namespace Store + +variable {M : Sem} + +/-- Write `v` for `x` at sort `s`; every other (name, sort) pair is unchanged. -/ +def upd (σ : Store M) (x : Ident) (s : LSort) (v : SortDenote M.tcInterp s) : Store M := + fun y s' => + if y = x then + if h : s' = s then cast (congrArg (SortDenote M.tcInterp) h.symm) v else σ y s' + else σ y s' + +/-- Names in `vs` from `t`, everything else from `σ`. -/ +def merge (σ : Store M) (vs : List Ident) (t : Store M) : Store M := + fun y s => if y ∈ vs then t y s else σ y s + +/-- The store with every variable at its default value. -/ +noncomputable def default : Store M := fun _ s => (Inhabited.default : SortDenote M.tcInterp s) + +@[simp] theorem upd_same (σ : Store M) (x : Ident) (s : LSort) (v : SortDenote M.tcInterp s) : + upd σ x s v x s = v := by + simp [upd] + +@[simp] theorem upd_other (σ : Store M) (x y : Ident) (s s' : LSort) (v : SortDenote M.tcInterp s) + (h : y ≠ x) : upd σ x s v y s' = σ y s' := by + simp [upd, h] + +@[simp] theorem merge_mem (σ t : Store M) (vs : List Ident) (y : Ident) (s : LSort) (h : y ∈ vs) : + merge σ vs t y s = t y s := by + simp [merge, h] + +@[simp] theorem merge_not_mem (σ t : Store M) (vs : List Ident) (y : Ident) (s : LSort) + (h : y ∉ vs) : merge σ vs t y s = σ y s := by + simp [merge, h] + +end Store + +/-- A computation with no outcome at all: the statement is stuck. Distinct from `assert` +failure, whose outcome is `none`. -/ +def ND.fail {α : Type} : ND α := ⟨fun _ => False⟩ + +/-! ## Expressions -/ + +/-- The value of the closed, annotated expression `e` at type `τ`, if it type-checks at `τ`. -/ +noncomputable def evalExpr (M : Sem) (σ : Store M) (e : Core.Expression.Expr) (τ : LMonoTy) : + Option (TyDenote M.tcInterp M.vt τ) := + if h : LExpr.typeCheck (T := Core.CoreLParams) [] e = some τ then + some (LExpr.denote (T := Core.CoreLParams) M.tcInterp M.opInterp σ M.vt .nil e τ + (LExpr.typeCheck_to_HasTypeA h)) + else none + +/-- A Boolean condition: `some b` if `e` type-checks at `bool`. -/ +noncomputable def evalBool (M : Sem) (σ : Store M) (e : Core.Expression.Expr) : Option Bool := + evalExpr M σ e LMonoTy.bool + +/-- All invariants of a loop hold in `σ`. -/ +def invsHold (M : Sem) (σ : Store M) : List (String × Core.Expression.Expr) → Prop + | [] => True + | (_, e) :: rest => evalBool M σ e = some true ∧ invsHold M σ rest + +/-! ## Statements -/ + +/-- What the interpreter carries along a statement list: the declared types of the variables +in scope, needed only to pick the sort of a `havoc`. -/ +structure Ctx where + tys : List (Ident × LMonoTy) + +/-- The loop-carried variables of a body: assigned in it, not declared in it. -/ +def loopVars (body : List Core.Statement) : List Ident := + let decl := Imperative.Block.initVars body + (Imperative.Block.modifiedVars body).filter (· ∉ decl) + +/-- `x := e` or `x := *` for a variable of type `τ`. -/ +noncomputable def assignVar (M : Sem) (σ : Store M) (x : Ident) (τ : LMonoTy) : + ExprOrNondet Core.Expression → ND (Store M) + | .det e => + match evalExpr M σ e τ with + | some v => pure (σ.upd x (sortOf M τ) v) + | none => ND.fail + | .nondet => do + let v ← ND.havoc (α := SortDenote M.tcInterp (sortOf M τ)) + pure (σ.upd x (sortOf M τ) v) + +/-- One base command. `init` is handled by `interpStmts`, which also extends the context. -/ +noncomputable def interpCmd (M : Sem) (Γ : Ctx) (σ : Store M) : Cmd Core.Expression → ND (Store M) + | .init .. => ND.fail + | .set x (.det e) _ => + match LExpr.typeCheck (T := Core.CoreLParams) [] e with + | some τ => assignVar M σ x τ (.det e) + | none => ND.fail + | .set x .nondet _ => + match Γ.tys.lookup x with + | some τ => assignVar M σ x τ .nondet + | none => ND.fail + | .assert _ e _ => + match evalBool M σ e with + | some b => do ND.assert (b = true); pure σ + | none => ND.fail + | .assume _ e _ => + match evalBool M σ e with + | some b => do ND.assume (b = true); pure σ + | none => ND.fail + | .cover _ _ _ => pure σ + +mutual + +/-- A statement list. `init` extends the context for the rest of the list. -/ +noncomputable def interpStmts (M : Sem) (Γ : Ctx) : List Core.Statement → Store M → ND (Store M) + | [], σ => pure σ + | .cmd (.cmd (.init x ty rhs _)) :: rest, σ => + match ty.toMonoType? with + | some τ => do + let σ' ← assignVar M σ x τ rhs + interpStmts M { tys := (x, τ) :: Γ.tys } rest σ' + | none => ND.fail + | s :: rest, σ => do + let σ' ← interpStmt M Γ s σ + interpStmts M Γ rest σ' + +/-- One statement. -/ +noncomputable def interpStmt (M : Sem) (Γ : Ctx) : Core.Statement → Store M → ND (Store M) + | .cmd (.cmd c), σ => interpCmd M Γ σ c + | .cmd (.call ..), _ => ND.fail + | .block _ ss _, σ => interpBlock M Γ ss σ + | .ite (.det c) t e _, σ => + match evalBool M σ c with + | some true => interpBlock M Γ t σ + | some false => interpBlock M Γ e σ + | none => ND.fail + | .ite .nondet t e _, σ => do + let b ← ND.havoc (α := Bool) + if b then interpBlock M Γ t σ else interpBlock M Γ e σ + | .loop (.det g) _ invs body _, σ => do + let vs := loopVars body + let t ← ND.whileInv + (fun t => invsHold M (σ.merge vs t) invs) + (fun t => evalBool M (σ.merge vs t) g = some true) + (fun t => interpBlock M Γ body (σ.merge vs t)) + σ + pure (σ.merge vs t) + | .loop .nondet .., _ => ND.fail + | .exit .., _ => ND.fail + | .typeDecl .., _ => ND.fail + +/-- A block: run the statements, then restore the entry values of the names declared inside. -/ +noncomputable def interpBlock (M : Sem) (Γ : Ctx) (ss : List Core.Statement) (σ : Store M) : + ND (Store M) := do + let σ' ← interpStmts M Γ ss σ + pure (σ'.merge (Imperative.Block.initVars ss) σ) + +end + +/-! ## Procedures -/ + +/-- Give each listed variable an arbitrary value of its type. -/ +noncomputable def havocVars (M : Sem) : List (Ident × LMonoTy) → Store M → ND (Store M) + | [], σ => pure σ + | (x, τ) :: rest, σ => do + let v ← ND.havoc (α := SortDenote M.tcInterp (sortOf M τ)) + havocVars M rest (σ.upd x (sortOf M τ) v) + +/-- A procedure from a store holding its inputs: outputs that are not also inputs start +arbitrary, then the body runs. The result is the final store; outputs are read from it. -/ +noncomputable def interpProc (M : Sem) (p : Core.Procedure) (σ₀ : Store M) : ND (Store M) := + let inputs := p.header.inputs.toList + let outputs := p.header.outputs.toList + let outOnly := outputs.filter fun (o, _) => inputs.all fun (i, _) => i ≠ o + do + let σ ← havocVars M outOnly σ₀ + match p.body with + | .structured ss => interpStmts M ⟨inputs ++ outputs⟩ ss σ + | .cfg _ => ND.fail + +end Strata.Shallow.Interp + +end diff --git a/StrataBoole/Shallow/Interpreter/Model.lean b/StrataBoole/Shallow/Interpreter/Model.lean new file mode 100644 index 0000000..ebb9dc2 --- /dev/null +++ b/StrataBoole/Shallow/Interpreter/Model.lean @@ -0,0 +1,209 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +module + +public import Strata.DL.Lambda.Denote.LExprDenote +public import StrataBoole.Shallow.Interpreter.Sort +import all Strata.DL.Lambda.Denote.LExprDenote + +/-! # A concrete model of Core's built-in types and operators + +`LExpr.denote` (`Strata/DL/Lambda/Denote/LExprDenote.lean`) gives Core expressions a +meaning in Lean, but it is parametric in two things Strata does not fix: + +* `tcInterp : TyConstrInterp` — a Lean type for every type constructor that `SortDenote` + does not already map (`SortDenote` fixes `bool`, `int`, `real`, `string`, `bitvec`, `arrow`); +* `opInterp : OpInterp tcInterp` — a Lean value for every operator, by name and sort. + +The model is partial: it covers the four non-built-in type constructors Core uses and the +operators of the `int`/`bool`/`Map`/`Sequence` fragment. Every other operator is interpreted +by `default`; an operator without a `body` or `concreteEval` imposes no consistency +obligation, so these can be refined later without touching any proof. The consistency proofs +relating the model to Strata's `concreteEval` functions (`InterpConsistentEval`) are not part +of this file. + +Conventions: `Int.Div`/`Int.Mod` are Lean's `/`/`%` (`Int.ediv`/`Int.emod`, the SMT-LIB +convention, as Lean's own docstring says), `DivT`/`ModT` are `Int.tdiv`/`Int.tmod`, the +`Safe*` operators denote the same functions as their unchecked versions (their preconditions +are obligations, not part of the value). Comparisons return `Bool`. +-/ + +@[expose] public section + +namespace Strata.Shallow.Model + +open Lambda + +/-! ## Sorts -/ + +/-- A Lean type for every sort. Agrees with `SortDenote` on the built-ins and adds `Map`, +`Sequence`, `Set` and `regex`; unknown constructors get `Unit`. -/ +def coreSortDenote : LSort → Type + | .tcons "bool" [] => Bool + | .tcons "int" [] => Int + | .tcons "real" [] => Rat + | .tcons "string" [] => String + | .bitvec n => BitVec n + | .tcons "arrow" [a, b] => coreSortDenote a → coreSortDenote b + | .tcons "Map" [k, v] => coreSortDenote k → coreSortDenote v + | .tcons "Sequence" [t] => List (coreSortDenote t) + | .tcons "Set" [t] => coreSortDenote t → Prop + | .tcons "regex" [] => String → Prop + | .tcons _ _ => Unit + + +/-- Every sort is inhabited. The catch-all branch of `coreSortDenote` does not reduce on a +variable sort, so this goes through `split`, as Strata's `SortDenote.inhabited` does. -/ +@[reducible] def coreSortDenote.inhabited : (s : LSort) → Inhabited (coreSortDenote s) := + sortRec (P := fun s => Inhabited (coreSortDenote s)) + (fun name args ih => by + unfold coreSortDenote + split + all_goals first + | exact ⟨false⟩ + | exact ⟨(0 : Int)⟩ + | exact ⟨(0 : Rat)⟩ + | exact ⟨""⟩ + | exact ⟨(0 : BitVec _)⟩ + | exact ⟨[]⟩ + | exact ⟨fun _ => False⟩ + | exact ⟨()⟩ + | exact ⟨fun _ => (ih _ (by simp_all)).default⟩) + (fun n => ⟨(0 : BitVec n)⟩) + +/-- The type-constructor interpretation handed to `SortDenote`: whatever `SortDenote` does +not fix is looked up in `coreSortDenote`. -/ +def coreTcInterp : TyConstrInterp := fun name args => coreSortDenote (.tcons name args) + +instance : TyConstrInterp.AllInhabited coreTcInterp := + ⟨fun name args => coreSortDenote.inhabited (.tcons name args)⟩ + +/-- `SortDenote coreTcInterp` and `coreSortDenote` are the same type family (by induction on +the sort; the built-in cases are identical, the others go through `coreTcInterp`). Used to +cast the arguments of polymorphic operators. -/ +theorem sortDenote_eq : ∀ s, SortDenote coreTcInterp s = coreSortDenote s := + sortRec (P := fun s => SortDenote coreTcInterp s = coreSortDenote s) + (fun name args ih => by + unfold SortDenote + split + all_goals first + | rfl + | (rename_i heq + cases heq <;> first + | rfl + | exact congr (congrArg (fun (A B : Type) => A → B) (ih _ (by simp))) (ih _ (by simp)))) + (fun n => rfl) + +/-! ## Sort patterns -/ + +@[match_pattern] def sInt : LSort := .tcons "int" [] +@[match_pattern] def sBool : LSort := .tcons "bool" [] +@[match_pattern] def sArrow (a b : LSort) : LSort := .tcons "arrow" [a, b] +@[match_pattern] def sMap (k v : LSort) : LSort := .tcons "Map" [k, v] +@[match_pattern] def sSeq (t : LSort) : LSort := .tcons "Sequence" [t] + +/-! ## Operators -/ + +/-- Transport a value between the two spellings of a sort's type. -/ +def toSD {s : LSort} (v : coreSortDenote s) : SortDenote coreTcInterp s := + cast (sortDenote_eq s).symm v +def ofSD {s : LSort} (v : SortDenote coreTcInterp s) : coreSortDenote s := + cast (sortDenote_eq s) v + +theorem coreSortDenote_map (k v : LSort) : + coreSortDenote (sMap k v) = (coreSortDenote k → coreSortDenote v) := rfl +theorem coreSortDenote_seq (t : LSort) : + coreSortDenote (sSeq t) = List (coreSortDenote t) := rfl + +/-- A map value as a Lean function, and back. -/ +def mapOf {k v : LSort} (m : SortDenote coreTcInterp (sMap k v)) : coreSortDenote k → coreSortDenote v := + cast (coreSortDenote_map k v) (ofSD m) +def mapTo {k v : LSort} (f : coreSortDenote k → coreSortDenote v) : SortDenote coreTcInterp (sMap k v) := + toSD (cast (coreSortDenote_map k v).symm f) +/-- A sequence value as a Lean list, and back. -/ +def seqOf {t : LSort} (l : SortDenote coreTcInterp (sSeq t)) : List (coreSortDenote t) := + cast (coreSortDenote_seq t) (ofSD l) +def seqTo {t : LSort} (l : List (coreSortDenote t)) : SortDenote coreTcInterp (sSeq t) := + toSD (cast (coreSortDenote_seq t).symm l) + +open Classical in +/-- The operator interpretation: by name (`CoreOp.toString`) and instantiated sort. Monomorphic +`int`/`bool` operators match a literal sort; the polymorphic `Map` and `Sequence` operators +match the sort's shape and transport through `toSD`/`ofSD`. Everything else is `default`. -/ +noncomputable def coreOpInterp : OpInterp coreTcInterp := fun name s => + match name, s with + -- integers + | "Int.Add", sArrow sInt (sArrow sInt sInt) => fun (a b : Int) => a + b + | "Int.Sub", sArrow sInt (sArrow sInt sInt) => fun (a b : Int) => a - b + | "Int.Mul", sArrow sInt (sArrow sInt sInt) => fun (a b : Int) => a * b + | "Int.Div", sArrow sInt (sArrow sInt sInt) => fun (a b : Int) => a / b + | "Int.Mod", sArrow sInt (sArrow sInt sInt) => fun (a b : Int) => a % b + | "Int.DivT", sArrow sInt (sArrow sInt sInt) => fun (a b : Int) => Int.tdiv a b + | "Int.ModT", sArrow sInt (sArrow sInt sInt) => fun (a b : Int) => Int.tmod a b + | "Int.SafeDiv", sArrow sInt (sArrow sInt sInt) => fun (a b : Int) => a / b + | "Int.SafeMod", sArrow sInt (sArrow sInt sInt) => fun (a b : Int) => a % b + | "Int.SafeDivT", sArrow sInt (sArrow sInt sInt) => fun (a b : Int) => Int.tdiv a b + | "Int.SafeModT", sArrow sInt (sArrow sInt sInt) => fun (a b : Int) => Int.tmod a b + | "Int.Neg", sArrow sInt sInt => fun (a : Int) => -a + | "Int.Lt", sArrow sInt (sArrow sInt sBool) => fun (a b : Int) => decide (a < b) + | "Int.Le", sArrow sInt (sArrow sInt sBool) => fun (a b : Int) => decide (a ≤ b) + | "Int.Gt", sArrow sInt (sArrow sInt sBool) => fun (a b : Int) => decide (a > b) + | "Int.Ge", sArrow sInt (sArrow sInt sBool) => fun (a b : Int) => decide (a ≥ b) + -- booleans + | "Bool.And", sArrow sBool (sArrow sBool sBool) => fun (a b : Bool) => a && b + | "Bool.Or", sArrow sBool (sArrow sBool sBool) => fun (a b : Bool) => a || b + | "Bool.Implies", sArrow sBool (sArrow sBool sBool) => fun (a b : Bool) => !a || b + | "Bool.Equiv", sArrow sBool (sArrow sBool sBool) => fun (a b : Bool) => a == b + | "Bool.Not", sArrow sBool sBool => fun (a : Bool) => !a + -- maps: `select m k`, `update m k v`, `mapConst v` + | "select", sArrow (sMap k v) (sArrow k' v') => + if h : k = k' ∧ v = v' then + h.1 ▸ h.2 ▸ (fun (m : SortDenote coreTcInterp (sMap k v)) (x : SortDenote coreTcInterp k) => + toSD (mapOf m (ofSD x))) + else default + | "update", sArrow (sMap k v) (sArrow k' (sArrow v' (sMap k'' v''))) => + if h : k = k' ∧ v = v' ∧ k = k'' ∧ v = v'' then + h.1 ▸ h.2.1 ▸ h.2.2.1 ▸ h.2.2.2 ▸ + (fun (m : SortDenote coreTcInterp (sMap k v)) (x : SortDenote coreTcInterp k) + (y : SortDenote coreTcInterp v) => + mapTo (fun z => if toSD z = x then ofSD y else mapOf m z)) + else default + | "mapConst", sArrow v (sMap k v') => + if h : v = v' then + h ▸ (fun (y : SortDenote coreTcInterp v) => mapTo (fun (_ : coreSortDenote k) => ofSD y)) + else default + -- sequences (as lists): the unchecked operations + | "Sequence.length", sArrow (sSeq t) sInt => + fun (l : SortDenote coreTcInterp (sSeq t)) => ((seqOf l).length : Int) + | "Sequence.empty", sSeq t => seqTo ([] : List (coreSortDenote t)) + | "Sequence.append", sArrow (sSeq t) (sArrow (sSeq t') (sSeq t'')) => + if h : t = t' ∧ t = t'' then + h.1 ▸ h.2 ▸ (fun (a b : SortDenote coreTcInterp (sSeq t)) => seqTo (seqOf a ++ seqOf b)) + else default + | "Sequence.select!", sArrow (sSeq t) (sArrow sInt t') => + if h : t = t' then + h ▸ (fun (l : SortDenote coreTcInterp (sSeq t)) (i : Int) => + toSD ((seqOf l).getD i.toNat (coreSortDenote.inhabited t).default)) + else default + | "Sequence.update!", sArrow (sSeq t) (sArrow sInt (sArrow t' (sSeq t''))) => + if h : t = t' ∧ t = t'' then + h.1 ▸ h.2 ▸ (fun (l : SortDenote coreTcInterp (sSeq t)) (i : Int) (y : SortDenote coreTcInterp t) => + seqTo ((seqOf l).set i.toNat (ofSD y))) + else default + | _, _ => default + +/-! ## Sanity checks: the monomorphic cases compute by `rfl` -/ + +example : coreOpInterp "Int.Add" (sArrow sInt (sArrow sInt sInt)) = fun (a b : Int) => a + b := rfl +example : coreOpInterp "Int.Ge" (sArrow sInt (sArrow sInt sBool)) = fun (a b : Int) => decide (a ≥ b) := rfl +example : coreOpInterp "Bool.And" (sArrow sBool (sArrow sBool sBool)) = fun (a b : Bool) => a && b := rfl +example : coreOpInterp "Int.Neg" (sArrow sInt sInt) = fun (a : Int) => -a := rfl +example : SortDenote coreTcInterp (sMap sInt sInt) = (Int → Int) := rfl +example : SortDenote coreTcInterp (sSeq sInt) = List Int := rfl + +end Strata.Shallow.Model + +end diff --git a/StrataBoole/Shallow/Interpreter/Reflect.lean b/StrataBoole/Shallow/Interpreter/Reflect.lean new file mode 100644 index 0000000..82f2942 --- /dev/null +++ b/StrataBoole/Shallow/Interpreter/Reflect.lean @@ -0,0 +1,188 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.Verify + +/-! # Reflection: a type-checked Core procedure as a Lean term + +`shallow_reflect` obtains the Core program by *running* `Strata.Boole.typeCheck` at elaboration +time. That result is a value in the elaborator's memory, not a term the kernel can compute +with: the lowering is built from `partial` definitions, so `typeCheck p` never reduces. To +state and prove anything about the program, each procedure is turned back into a closed term +made of constructors and literals (`ToExpr`) and bound to a definition +`_ast : Core.Procedure`, on which `rfl`, `simp` and `decide` work by structural +reduction. + +Leaf types derive `ToExpr`. The types parametrised by `PureExpr` or `LExprParamsT` cannot be +derived (the parameter is a bundle of `Type`s, not a `Type`), so their instances are written +for the Core instantiation `Core.Expression`. -/ + +open Lean Meta +open Lambda Imperative + +namespace Strata.Shallow.Reflect + +/-! ## Leaves -/ + +deriving instance ToExpr for Lambda.QuantifierKind +deriving instance ToExpr for Lambda.LMonoTy +deriving instance ToExpr for Lambda.LTy +deriving instance ToExpr for Lambda.LConst +deriving instance ToExpr for Lambda.Identifier +deriving instance ToExpr for Imperative.CheckAttr +deriving instance ToExpr for Boundedness +deriving instance ToExpr for TypeConstructor +deriving instance ToExpr for Strata.SynthesizedOrigin +deriving instance ToExpr for Strata.Uri +deriving instance ToExpr for StrataDDM.SourceRange +deriving instance ToExpr for Strata.Provenance + +/-- `ListMap` is a definition, not an abbreviation, so the `List` instance is not found +through it. -/ +instance {α β : Type} [ToExpr α] [ToExpr β] : ToExpr (ListMap α β) := + inferInstanceAs (ToExpr (List (α × β))) + +deriving instance ToExpr for Core.Procedure.Header + +/-! ## The Core instantiation + +The implicit parameters every constructor takes, as terms. -/ + +/-- `Core.Expression : PureExpr`. -/ +def pureExprE : Expr := mkConst ``Core.Expression +/-- `Core.Command`, the command type of Core statements. -/ +def cmdE : Expr := mkConst ``Core.Command +/-- `Core.CoreLParams.mono : LExprParamsT`, the parameters of Core's `LExpr`. -/ +def lparamsE : Expr := mkApp (mkConst ``Lambda.LExprParams.mono) (mkConst ``Core.CoreLParams) + +/-- Metadata on Core expressions is `Unit`. -/ +def unitE (u : Unit) : Expr := toExpr u + +/-- Core identifiers (`Lambda.Identifier Unit`). -/ +def identE (x : Core.CoreIdent) : Expr := toExpr x + +/-- Expressions. -/ +def exprE : Core.Expression.Expr → Expr + | .const m c => mkApp3 (mkConst ``LExpr.const) lparamsE (unitE m) (toExpr c) + | .op m o ty => mkApp4 (mkConst ``LExpr.op) lparamsE (unitE m) (identE o) (toExpr ty) + | .bvar m i => mkApp3 (mkConst ``LExpr.bvar) lparamsE (unitE m) (toExpr i) + | .fvar m x ty => mkApp4 (mkConst ``LExpr.fvar) lparamsE (unitE m) (identE x) (toExpr ty) + | .abs m n ty e => mkApp5 (mkConst ``LExpr.abs) lparamsE (unitE m) (toExpr n) (toExpr ty) (exprE e) + | .quant m k n ty tr e => + mkApp7 (mkConst ``LExpr.quant) lparamsE (unitE m) (toExpr k) (toExpr n) (toExpr ty) (exprE tr) + (exprE e) + | .app m f a => mkApp4 (mkConst ``LExpr.app) lparamsE (unitE m) (exprE f) (exprE a) + | .ite m c t e => mkApp5 (mkConst ``LExpr.ite) lparamsE (unitE m) (exprE c) (exprE t) (exprE e) + | .eq m a b => mkApp4 (mkConst ``LExpr.eq) lparamsE (unitE m) (exprE a) (exprE b) + +instance : ToExpr Core.Expression.Expr where + toExpr := exprE + toTypeExpr := mkApp (mkConst ``Lambda.LExpr) lparamsE + +instance : ToExpr (ExprOrNondet Core.Expression) where + toExpr + | .det e => mkApp2 (mkConst ``ExprOrNondet.det) pureExprE (toExpr e) + | .nondet => mkApp (mkConst ``ExprOrNondet.nondet) pureExprE + toTypeExpr := mkApp (mkConst ``ExprOrNondet) pureExprE + +instance : ToExpr (MetaDataElem.Field Core.Expression) where + toExpr + | .var v => mkApp2 (mkConst ``MetaDataElem.Field.var) pureExprE (identE v) + | .label l => mkApp2 (mkConst ``MetaDataElem.Field.label) pureExprE (toExpr l) + toTypeExpr := mkApp (mkConst ``MetaDataElem.Field) pureExprE + +instance : ToExpr (MetaDataElem.Value Core.Expression) where + toExpr + | .expr e => mkApp2 (mkConst ``MetaDataElem.Value.expr) pureExprE (toExpr e) + | .msg s => mkApp2 (mkConst ``MetaDataElem.Value.msg) pureExprE (toExpr s) + | .switch b => mkApp2 (mkConst ``MetaDataElem.Value.switch) pureExprE (toExpr b) + | .provenance p => mkApp2 (mkConst ``MetaDataElem.Value.provenance) pureExprE (toExpr p) + toTypeExpr := mkApp (mkConst ``MetaDataElem.Value) pureExprE + +instance : ToExpr (MetaDataElem Core.Expression) where + toExpr e := mkApp3 (mkConst ``MetaDataElem.mk) pureExprE (toExpr e.fld) (toExpr e.value) + toTypeExpr := mkApp (mkConst ``MetaDataElem) pureExprE + +/-- Statement metadata. -/ +def mdE (md : Imperative.MetaData Core.Expression) : Expr := toExpr md + +instance : ToExpr (Cmd Core.Expression) where + toExpr + | .init x ty e md => + mkApp5 (mkConst ``Cmd.init) pureExprE (identE x) (toExpr ty) (toExpr e) (mdE md) + | .set x e md => mkApp4 (mkConst ``Cmd.set) pureExprE (identE x) (toExpr e) (mdE md) + | .assert l b md => mkApp4 (mkConst ``Cmd.assert) pureExprE (toExpr l) (toExpr b) (mdE md) + | .assume l b md => mkApp4 (mkConst ``Cmd.assume) pureExprE (toExpr l) (toExpr b) (mdE md) + | .cover l b md => mkApp4 (mkConst ``Cmd.cover) pureExprE (toExpr l) (toExpr b) (mdE md) + toTypeExpr := mkApp (mkConst ``Cmd) pureExprE + +instance : ToExpr (CallArg Core.Expression) where + toExpr + | .inArg e => mkApp2 (mkConst ``CallArg.inArg) pureExprE (toExpr e) + | .inoutArg x => mkApp2 (mkConst ``CallArg.inoutArg) pureExprE (identE x) + | .outArg x => mkApp2 (mkConst ``CallArg.outArg) pureExprE (identE x) + toTypeExpr := mkApp (mkConst ``CallArg) pureExprE + +instance : ToExpr Core.Command where + toExpr + | .cmd c => mkApp2 (mkConst ``CmdExt.cmd) pureExprE (toExpr c) + | .call n args md => mkApp4 (mkConst ``CmdExt.call) pureExprE (toExpr n) (toExpr args) (mdE md) + toTypeExpr := cmdE + +mutual + +/-- Statements. -/ +partial def stmtE : Core.Statement → Expr + | .cmd c => mkApp3 (mkConst ``Stmt.cmd) pureExprE cmdE (toExpr c) + | .block l b md => mkApp5 (mkConst ``Stmt.block) pureExprE cmdE (toExpr l) (stmtsE b) (mdE md) + | .ite c t e md => + mkApp6 (mkConst ``Stmt.ite) pureExprE cmdE (toExpr c) (stmtsE t) (stmtsE e) (mdE md) + | .loop g m invs b md => + mkApp7 (mkConst ``Stmt.loop) pureExprE cmdE (toExpr g) (toExpr m) (toExpr invs) (stmtsE b) + (mdE md) + | .exit l md => mkApp4 (mkConst ``Stmt.exit) pureExprE cmdE (toExpr l) (mdE md) + | .typeDecl tc md => mkApp4 (mkConst ``Stmt.typeDecl) pureExprE cmdE (toExpr tc) (mdE md) + +/-- Statement lists, as `List Core.Statement` literals. -/ +partial def stmtsE : List Core.Statement → Expr + | [] => mkApp (mkConst ``List.nil [Level.zero]) (mkConst ``Core.Statement) + | s :: ss => mkApp3 (mkConst ``List.cons [Level.zero]) (mkConst ``Core.Statement) (stmtE s) (stmtsE ss) + +end + +instance : ToExpr Core.Statement where + toExpr := stmtE + toTypeExpr := mkConst ``Core.Statement + +instance : ToExpr (Check Core.Expression) where + toExpr c := mkApp4 (mkConst ``Check.mk) pureExprE (toExpr c.expr) (toExpr c.attr) (mdE c.md) + toTypeExpr := mkApp (mkConst ``Check) pureExprE + +instance : ToExpr (Spec Core.Expression) where + toExpr s := + mkApp3 (mkConst ``Spec.mk) pureExprE (toExpr s.preconditions) (toExpr s.postconditions) + toTypeExpr := mkApp (mkConst ``Spec) pureExprE + +/-! ## Procedures -/ + +/-- A procedure body. Only structured bodies are supported; the lowering never produces a CFG. -/ +def bodyE : Core.Procedure.Body → MetaM Expr + | .structured ss => pure (mkApp3 (mkConst ``Body.structured) pureExprE cmdE (stmtsE ss)) + | .cfg _ => throwError "shallow_reflect: a procedure body given as a CFG cannot be reflected" + +/-- The procedure `p` as a closed term of type `Core.Procedure`. -/ +def procedureE (p : Core.Procedure) : MetaM Expr := do + let body ← bodyE p.body + mkAppOptM ``Imperative.Procedure.mk + #[pureExprE, cmdE, mkConst ``Core.Procedure.Header, none, none, + toExpr p.header, toExpr p.spec, body] + +/-- Add `name : Core.Procedure := p` to the environment. -/ +def addProcedureAst (name : Name) (p : Core.Procedure) : MetaM Unit := do + let value ← procedureE p + let _ ← mkAuxDefinition name (mkConst ``Core.Procedure) value + enableRealizationsForConst name + +end Strata.Shallow.Reflect diff --git a/StrataBoole/Shallow/Interpreter/Sort.lean b/StrataBoole/Shallow/Interpreter/Sort.lean new file mode 100644 index 0000000..1a18cfc --- /dev/null +++ b/StrataBoole/Shallow/Interpreter/Sort.lean @@ -0,0 +1,74 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +module +public import Strata.DL.Lambda.Denote.LExprDenote + +/-! # Sorts: recursion principle and decidable equality for `LSort` + +`LSort` is a nested inductive (`tcons` carries a `List LSort`), so the auto-generated recursor +is awkward to use. Strata already has what is needed, in +`Strata/DL/Lambda/Denote/LExprDenote.lean`, but not as public declarations of that module: + +* `LSort.rec'` (and its `Prop` version `LSort.ind`): recursion with the hypothesis available + for every member of the argument list; +* `instance : DecidableEq LSort`, built from the Boolean comparison `LSort_eqb` and the + private lemmas `LSort_eqb_eq` and `LSort_eqb_refl`. + +A non-public declaration can be used in the proof of a public theorem, but not in a public +statement or in the body of an exposed definition, which is where the model and the interpreter +need these. This file therefore provides public replacements: `sortRec` restates `LSort.rec'` +(with the motive implicit), and `LSort.decEq` decides equality directly by structural recursion +instead of going through `LSort_eqb`. Both are shared by `Model.lean` and `Interp.lean`; they +can be dropped once Strata exports its own. -/ + +@[expose] public section + +namespace Strata.Shallow + +open Lambda + +/-- Recursion over `LSort` with the hypothesis available for every member of the argument list: +Strata's `LSort.rec'` (`Strata/DL/Lambda/Denote/LExprDenote.lean`), which is not public. -/ +def sortRec {P : LSort → Sort u} + (htcons : ∀ name args, (∀ x, x ∈ args → P x) → P (.tcons name args)) + (hbitvec : ∀ n, P (.bitvec n)) : ∀ s, P s + | .tcons name args => htcons name args (fun x _ => sortRec htcons hbitvec x) + | .bitvec n => hbitvec n + +/-- Decidable equality on sorts, by structural recursion. Strata's own instance +(`instance : DecidableEq LSort` in `Strata/DL/Lambda/Denote/LExprDenote.lean`, via `LSort_eqb`) +is not public. -/ +def LSort.decEq : (a b : LSort) → Decidable (a = b) + | .tcons n as, .tcons n' as' => + if hn : n = n' then + match decEqList as as' with + | isTrue h => isTrue (by rw [hn, h]) + | isFalse h => isFalse (by intro e; cases e; exact h rfl) + else isFalse (by intro e; cases e; exact hn rfl) + | .tcons .., .bitvec .. => isFalse nofun + | .bitvec .., .tcons .. => isFalse nofun + | .bitvec n, .bitvec n' => + if h : n = n' then isTrue (by rw [h]) else isFalse (by intro e; cases e; exact h rfl) +where + decEqList : (as bs : List LSort) → Decidable (as = bs) + | [], [] => isTrue rfl + | [], _ :: _ => isFalse nofun + | _ :: _, [] => isFalse nofun + | a :: as, b :: bs => + match LSort.decEq a b, decEqList as bs with + | isTrue h1, isTrue h2 => isTrue (by rw [h1, h2]) + | isFalse h1, _ => isFalse (by intro e; cases e; exact h1 rfl) + | _, isFalse h2 => isFalse (by intro e; cases e; exact h2 rfl) + +instance : DecidableEq LSort := LSort.decEq + +example : (LSort.tcons "int" [] = LSort.tcons "int" []) := by decide +example : (LSort.tcons "arrow" [.tcons "int" [], .bitvec 32] ≠ LSort.tcons "arrow" [.tcons "int" [], .bitvec 64]) := by + decide + +end Strata.Shallow + +end diff --git a/StrataBoole/Shallow/Pipeline.lean b/StrataBoole/Shallow/Pipeline.lean new file mode 100644 index 0000000..fd6b435 --- /dev/null +++ b/StrataBoole/Shallow/Pipeline.lean @@ -0,0 +1,40 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.Verify + +/-! # From Boole source to a type-checked Core program, at elaboration time + +The translator (`shallow_embed`) and the interpreter's command (`shallow_reflect`, +`Interpreter/Command.lean`) start from the same object: the Core program +obtained by `Strata.Boole.typeCheck`, that is `getProgram → toCoreProgram → Core.typeCheck`, +before any Core transform phase. This file is the one place that computes it, so the two sides +cannot disagree about which program they talk about. The computation runs compiled code +(`Term.evalTerm`): its result is a value in the elaborator, not a term the kernel can reduce. -/ + +open Lean Elab Term Meta + +namespace Strata.Shallow.Pipeline + +/-- Lower and type-check; render the error as a string so the result can be evaluated at +elaboration time without naming Strata's message type. -/ +def typeCheckStr (p : StrataDDM.Program) : Except String Core.Program := + match Strata.Boole.typeCheck p Core.VerifyOptions.quiet with + | .ok cp => .ok cp + | .error m => .error (toString (m.format none)) + +unsafe def evalProgramUnsafe (t : Term) : TermElabM Core.Program := do + let ty := mkApp2 (mkConst ``Except [.zero, .zero]) (mkConst ``String) (mkConst ``Core.Program) + let r ← Term.evalTerm (Except String Core.Program) ty + (← `(Strata.Shallow.Pipeline.typeCheckStr $t)) + match r with + | .ok p => pure p + | .error m => throwError m!"Core type checking failed: {m}" + +/-- The type-checked Core program denoted by the term `t : StrataDDM.Program`. -/ +@[implemented_by evalProgramUnsafe] +opaque evalProgram (t : Term) : TermElabM Core.Program + +end Strata.Shallow.Pipeline diff --git a/docs/ShallowEmbedding.md b/docs/ShallowEmbedding.md index 0ef6feb..e0cc59d 100644 --- a/docs/ShallowEmbedding.md +++ b/docs/ShallowEmbedding.md @@ -55,6 +55,16 @@ model: one inductive of constructor applications for all datatypes, with the dat proved once and `pos.toInt` by structural recursion. The proofs use only Lean's standard axioms. +`StrataBoole/Shallow/Interpreter/` is a prototype of the interpreter, the object the adequacy +proof is about. `Interp.lean` gives Core statements their meaning as `ND` computations: the +store is `FreeVarVal`, an expression is evaluated by `LExpr.denote` after `LExpr.typeCheck`, +a loop carries only the variables its body assigns and reads the others from the store at +loop entry, a block restores the names it declares. `Model.lean` is a partial concrete model +of Core's built-ins (`int`, `bool`, `Map`, `Sequence`) for the two interpretation parameters +of `denote`; `Sort.lean` has the recursion principle and decidable equality for `LSort`. +`Reflect.lean` and `Command.lean` (`shallow_reflect`) bind each procedure's type-checked Core +AST to `_ast : Core.Procedure`, a literal the kernel can compute with. + ## Research questions 1. **Variables:** represent program variables so that verification conditions range over From df23539c680594d9a0dde7263b5ef6ca76da7f9f Mon Sep 17 00:00:00 2001 From: Stephanie Ma Date: Tue, 27 Oct 2026 01:49:21 -0700 Subject: [PATCH 07/64] Shallow embedding: interpreter fails instead of going vacuous; reflect whole programs - ND.fail is the failed-assert outcome, so unsupported statements and ill-typed expressions or loop guards make a specification unprovable. - shallow_reflect also binds the program as `

_ast : Core.Program`, with its functions, axioms, lemmas and type declarations. --- StrataBoole/Shallow/Interpreter/Command.lean | 18 +++++-- StrataBoole/Shallow/Interpreter/Interp.lean | 35 ++++++------ StrataBoole/Shallow/Interpreter/Reflect.lean | 57 +++++++++++++++++++- docs/ShallowEmbedding.md | 5 +- 4 files changed, 91 insertions(+), 24 deletions(-) diff --git a/StrataBoole/Shallow/Interpreter/Command.lean b/StrataBoole/Shallow/Interpreter/Command.lean index 5a84f3c..f8e05d4 100644 --- a/StrataBoole/Shallow/Interpreter/Command.lean +++ b/StrataBoole/Shallow/Interpreter/Command.lean @@ -8,10 +8,11 @@ import StrataBoole.Shallow.Interpreter.Reflect /-! # `shallow_reflect`: the interpreter's entry point from Boole source -`shallow_reflect p` type-checks the Boole program `p` (`Pipeline.lean`) and binds the Core AST -of every procedure to `_ast : Core.Procedure` (`Reflect.lean`). Statements about a -procedure, its meaning `interpProc M _ast` and its specification, are made on that -definition. -/ +`shallow_reflect p` type-checks the Boole program `p` (`Pipeline.lean`) and binds its Core AST +(`Reflect.lean`): the whole program as `

_ast : Core.Program` when `p` is an identifier, and +every procedure as `_ast : Core.Procedure`. Statements about a procedure, its meaning +`interpProc M _ast` and its specification, are made on these definitions; the program +literal carries the functions, axioms and type declarations the procedure's names refer to. -/ open Lean Elab Command @@ -22,9 +23,16 @@ syntax (name := shallowReflect) "shallow_reflect " term : command @[command_elab shallowReflect] def elabShallowReflect : CommandElab := fun stx => do let `(shallow_reflect $t:term) := stx | throwUnsupportedSyntax let prog ← liftTermElabM (Pipeline.evalProgram t) + let ns ← getCurrNamespace + if let `($x:ident) := t then + let pgmName := ns ++ Name.mkSimple s!"{x.getId.eraseMacroScopes.getString!}_ast" + liftTermElabM (Reflect.addProgramAst pgmName prog) + else + logWarning "shallow_reflect: the program is bound as a whole only when the argument is an \ + identifier; its procedures are bound either way" for d in prog.decls do if let .proc p _ := d then - let astName := (← getCurrNamespace) ++ Name.mkSimple s!"{p.header.name.name}_ast" + let astName := ns ++ Name.mkSimple s!"{p.header.name.name}_ast" liftTermElabM (Reflect.addProcedureAst astName p) end Strata.Shallow.Interp diff --git a/StrataBoole/Shallow/Interpreter/Interp.lean b/StrataBoole/Shallow/Interpreter/Interp.lean index 9ce2b51..7ae4ae9 100644 --- a/StrataBoole/Shallow/Interpreter/Interp.lean +++ b/StrataBoole/Shallow/Interpreter/Interp.lean @@ -25,8 +25,10 @@ conditions. are evaluated by `denote` directly; there is no second evaluator. * **Expressions.** `evalExpr σ e τ` runs Strata's computable type checker `LExpr.typeCheck` and, on success, `LExpr.denote` with the derivation obtained from `typeCheck_to_HasTypeA`. - An ill-typed expression makes the statement stuck (no outcome), mirroring a missing rule in - Core's semantics. +* **Failure, never vacuity.** An ill-typed expression (a loop guard is checked before the loop, + since inside `whileInv` it is a proposition), and every construct the interpreter does not + handle, is `ND.fail`: the outcome `none` of a failed `assert`. A computation with no outcome + at all would satisfy every specification; this one satisfies none. * **Loops are frame-aware.** The loop state carries only the variables the body assigns (`Block.modifiedVars` minus `Block.initVars`); all other variables are read from the store at loop entry (`Store.merge`). Without this the loop invariant would have to restate that @@ -35,8 +37,8 @@ conditions. `projectStore` does. * **Outputs** are arbitrary at procedure entry (`havoc`); an inout parameter keeps its input value. -* **Unsupported for now** (`ND.fail`): procedure calls, `exit`, nondeterministic loops, local `type` - declarations. +* **Unsupported for now** (`ND.fail`): procedure calls, `exit`, nondeterministic loops, local + `type` declarations. The model `(tcInterp, opInterp, vt)` is a parameter bundled in `Sem`; `Model.lean` provides the concrete one for Core's built-ins. @@ -209,9 +211,10 @@ noncomputable def default : Store M := fun _ s => (Inhabited.default : SortDenot end Store -/-- A computation with no outcome at all: the statement is stuck. Distinct from `assert` -failure, whose outcome is `none`. -/ -def ND.fail {α : Type} : ND α := ⟨fun _ => False⟩ +/-- The failing computation: its only outcome is `none`, as after a failed `assert`. Used for +ill-typed expressions and for every statement the interpreter does not handle, so that no +specification holds of them vacuously. -/ +def ND.fail {α : Type} : ND α := ⟨fun r => r = none⟩ /-! ## Expressions -/ @@ -304,14 +307,16 @@ noncomputable def interpStmt (M : Sem) (Γ : Ctx) : Core.Statement → Store M | .ite .nondet t e _, σ => do let b ← ND.havoc (α := Bool) if b then interpBlock M Γ t σ else interpBlock M Γ e σ - | .loop (.det g) _ invs body _, σ => do - let vs := loopVars body - let t ← ND.whileInv - (fun t => invsHold M (σ.merge vs t) invs) - (fun t => evalBool M (σ.merge vs t) g = some true) - (fun t => interpBlock M Γ body (σ.merge vs t)) - σ - pure (σ.merge vs t) + | .loop (.det g) _ invs body _, σ => + if LExpr.typeCheck (T := Core.CoreLParams) [] g = some LMonoTy.bool then do + let vs := loopVars body + let t ← ND.whileInv + (fun t => invsHold M (σ.merge vs t) invs) + (fun t => evalBool M (σ.merge vs t) g = some true) + (fun t => interpBlock M Γ body (σ.merge vs t)) + σ + pure (σ.merge vs t) + else ND.fail | .loop .nondet .., _ => ND.fail | .exit .., _ => ND.fail | .typeDecl .., _ => ND.fail diff --git a/StrataBoole/Shallow/Interpreter/Reflect.lean b/StrataBoole/Shallow/Interpreter/Reflect.lean index 82f2942..9c602b0 100644 --- a/StrataBoole/Shallow/Interpreter/Reflect.lean +++ b/StrataBoole/Shallow/Interpreter/Reflect.lean @@ -12,8 +12,9 @@ time. That result is a value in the elaborator's memory, not a term the kernel c with: the lowering is built from `partial` definitions, so `typeCheck p` never reduces. To state and prove anything about the program, each procedure is turned back into a closed term made of constructors and literals (`ToExpr`) and bound to a definition -`_ast : Core.Procedure`, on which `rfl`, `simp` and `decide` work by structural -reduction. +`_ast : Core.Procedure`; the whole program is bound as well, since its functions, axioms +and type declarations give the procedure's names their meaning. On these definitions `rfl`, +`simp` and `decide` work by structural reduction. Leaf types derive `ToExpr`. The types parametrised by `PureExpr` or `LExprParamsT` cannot be derived (the parameter is a bundle of `Type`s, not a `Type`), so their instances are written @@ -185,4 +186,56 @@ def addProcedureAst (name : Name) (p : Core.Procedure) : MetaM Unit := do let _ ← mkAuxDefinition name (mkConst ``Core.Procedure) value enableRealizationsForConst name +/-! ## Declarations and programs + +Functions, axioms, lemmas and type declarations carry the meaning of the names a procedure +uses, so the whole program is reflected as well. -/ + +/-- The expression type as Core's declarations spell it. -/ +instance : ToExpr (Lambda.LExpr Core.CoreLParams.mono) := inferInstanceAs (ToExpr Core.Expression.Expr) + +deriving instance ToExpr for Strata.DL.Util.FuncAttr +deriving instance ToExpr for Strata.DL.Util.FuncPrecondition +deriving instance ToExpr for Strata.DL.Util.Func +deriving instance ToExpr for Lambda.LConstr +deriving instance ToExpr for Core.TypeSynonym +deriving instance ToExpr for Core.Axiom +deriving instance ToExpr for Core.Lemma + +/-- `LDatatype` carries the proof that it has a constructor; on a literal, `rfl` is that proof. -/ +instance : ToExpr (Lambda.LDatatype Unit) where + toExpr d := + mkApp5 (mkConst ``Lambda.LDatatype.mk) (mkConst ``Unit) (toExpr d.name) (toExpr d.typeArgs) + (toExpr d.constrs) (mkApp2 (mkConst ``Eq.refl [.succ .zero]) (mkConst ``Bool) (mkConst ``Bool.true)) + toTypeExpr := mkApp (mkConst ``Lambda.LDatatype) (mkConst ``Unit) + +instance : ToExpr Core.TypeDecl where + toExpr + | .con tc => mkApp (mkConst ``Core.TypeDecl.con) (toExpr tc) + | .syn ts => mkApp (mkConst ``Core.TypeDecl.syn) (toExpr ts) + | .data ds => mkApp (mkConst ``Core.TypeDecl.data) (toExpr ds) + toTypeExpr := mkConst ``Core.TypeDecl + +/-- A declaration; procedures go through `procedureE`. -/ +def declE : Core.Decl → MetaM Expr + | .type t md => pure (mkApp2 (mkConst ``Core.Decl.type) (toExpr t) (mdE md)) + | .ax a md => pure (mkApp2 (mkConst ``Core.Decl.ax) (toExpr a) (mdE md)) + | .lemma l md => pure (mkApp2 (mkConst ``Core.Decl.lemma) (toExpr l) (mdE md)) + | .distinct x es md => + pure (mkApp3 (mkConst ``Core.Decl.distinct) (identE x) (toExpr es) (mdE md)) + | .proc p md => return mkApp2 (mkConst ``Core.Decl.proc) (← procedureE p) (mdE md) + | .func f md => pure (mkApp2 (mkConst ``Core.Decl.func) (toExpr f) (mdE md)) + | .recFuncBlock fs md => pure (mkApp2 (mkConst ``Core.Decl.recFuncBlock) (toExpr fs) (mdE md)) + +/-- The program `p` as a closed term of type `Core.Program`. -/ +def programE (p : Core.Program) : MetaM Expr := do + let ds ← p.decls.mapM declE + return mkApp (mkConst ``Core.Program.mk) (← mkListLit (mkConst ``Core.Decl) ds) + +/-- Add `name : Core.Program := p` to the environment. -/ +def addProgramAst (name : Name) (p : Core.Program) : MetaM Unit := do + let value ← programE p + let _ ← mkAuxDefinition name (mkConst ``Core.Program) value + enableRealizationsForConst name + end Strata.Shallow.Reflect diff --git a/docs/ShallowEmbedding.md b/docs/ShallowEmbedding.md index e0cc59d..a7b1717 100644 --- a/docs/ShallowEmbedding.md +++ b/docs/ShallowEmbedding.md @@ -62,8 +62,9 @@ a loop carries only the variables its body assigns and reads the others from the loop entry, a block restores the names it declares. `Model.lean` is a partial concrete model of Core's built-ins (`int`, `bool`, `Map`, `Sequence`) for the two interpretation parameters of `denote`; `Sort.lean` has the recursion principle and decidable equality for `LSort`. -`Reflect.lean` and `Command.lean` (`shallow_reflect`) bind each procedure's type-checked Core -AST to `_ast : Core.Procedure`, a literal the kernel can compute with. +`Reflect.lean` and `Command.lean` (`shallow_reflect`) bind the type-checked Core program to +`

_ast : Core.Program` and each procedure to `_ast : Core.Procedure`, literals the +kernel can compute with. ## Research questions From bc3f78617172730db1d05ba085b011fb69763689 Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Tue, 27 Oct 2026 11:49:04 +0200 Subject: [PATCH 08/64] Shallow embedding: write the plan down as ordered steps Interpreter on Core, adequacy against Core's semantics, proof rules and mvcgen on top with find_max as the milestone, the model, then a Boole interpreter. Close the translator-or-interpreter question. Co-Authored-By: Claude Fable 5.1 --- docs/ShallowEmbedding.md | 107 +++++++++++++++++++++++++-------------- 1 file changed, 70 insertions(+), 37 deletions(-) diff --git a/docs/ShallowEmbedding.md b/docs/ShallowEmbedding.md index 0ef6feb..8b5a4d3 100644 --- a/docs/ShallowEmbedding.md +++ b/docs/ShallowEmbedding.md @@ -1,10 +1,11 @@ # Shallow embedding of Strata in Lean -The goal is to interpret Strata Core programs in Lean as computations in a -nondeterministic state monad. Verification conditions come from proved -weakest-precondition rules, so the generator is sound by construction. The design follows -Velvet; the code builds on Lean's `Std.Do` and `mvcgen`. Boole programs reach it through -their lowering to Core. +The goal is to verify Boole programs in Lean with proofs that are sound by construction. +Today's Lean path trusts the VC generator, the SMT encoding and a bridge axiom +(strata-org/Strata#1488 shows it can prove `False`). Here the only trusted parts are Core's +semantics and Lean, and the verification conditions range over Lean values, so Lean tactics +work on them directly, without a solver. Boole programs reach it through their lowering to +Core. ```mermaid flowchart TD @@ -13,21 +14,64 @@ flowchart TD V["VC generation and SMT encoding"] --> S["cvc5, or Lean via lean-smt"] end subgraph lean ["Lean path"] - T["Core to Lean (planned)"] --> G["Std.Do + mvcgen + Layer.lean"] + I["interpreter: Core AST to ND"] --> G["unfold, then Std.Do + mvcgen + Layer.lean"] G --> P["Lean proof"] end C --> V - C --> T + C --> I + O["Core operational semantics"] -. adequacy .- I ``` +## Plan + +The steps, in order. Each one is a theorem or a tool on the branch, not a design choice +left open. + +1. **Interpreter.** One Lean function, `interpProc : Core.Procedure → Store → ND Store`, + gives every Core program its meaning in the `ND` monad of `Layer.lean` + (`StrataBoole/Shallow/Interpreter/`). It keeps the Core AST as data, evaluates + expressions with Strata's own `LExpr.denote`, and has no second evaluator. Unfolding + it on a concrete program yields the monadic term that `mvcgen` works on; this is what + "shallow" refers to. There is no per-program translator: a generated program would be + a second meaning of the source that nothing checks. +2. **Adequacy.** Prove that the interpreter agrees with Core's operational semantics + (`StatementSemantics.lean`): if Core can run `s` from `σ` to `σ'`, then `σ'` is an + outcome of `interpStmts s σ`, and a failed check in Core is the failure outcome. This + single theorem is what makes the Lean path trustworthy. Everything the interpreter does + not cover must fail, never be vacuous, so that a missing case cannot prove a + specification. +3. **Proof rules and tactic.** `Layer.lean` already has the rules (`havoc_spec`, + `assume_spec`, `assert_spec`, `whileInv_spec`, each a proved `@[spec]` theorem) and + `mvcgen` is the tactic that applies them. The first program proved end to end through + the interpreter, `find_max`, is the milestone for this step: `shallow_reflect`, unfold + `interpProc`, `mvcgen`, then `grind`/`omega`. Improvements such as goal names that + follow the program's clauses, `decreases` checks and Core notation in goals go on top + of `mvcgen`, not into a separate semantics. +4. **Model.** Results must hold for every interpretation of Core's types and operators + that is consistent with Core, not for one concrete model: an unmodelled operator or an + out-of-range read must stay unconstrained, as in Core and SMT. A concrete model only + shows that such an interpretation exists. Datatypes: a single model (an inductive of + constructor applications, prototyped in `shallow_generic_datatypes.lean`) carries over + to Core only if every model Core admits is isomorphic to it, which needs + exhaustiveness and induction among Core's datatype laws. `nat` is a binary datatype in + Core; mapping it to Lean's `Nat` needs a proof that the two agree. +5. **Boole semantics.** A Boole interpreter proved to agree with the Core one on + `toCoreProgram p`, so that Boole gets a semantics of its own and the lowering is + verified. `toCoreExpr` is total (strata-org/Strata-Boole#25) and the `nat` library is + added inside `typeCheck` (strata-org/Strata-Boole#26) so that this statement can be made. + ## Decisions -- **Input is Core**, which has a formal semantics (`StatementSemantics.lean`), so the - interpretation can be proved adequate against it. Boole and other front ends lower to - Core. +- **Input is Core**, which has a formal semantics, so the interpretation can be proved + adequate against it. Boole and other front ends lower to Core. +- **Interpreter, not translator.** See step 1. - **Framework: `Std.Do` and `mvcgen`**, available in Lean 4.29 and 4.31. Lean marks - `mvcgen` experimental; its successor `vcgen` needs Lean 4.33. + `mvcgen` experimental; its successor `vcgen` needs Lean 4.33. If `mvcgen` misbehaves + on a construct, the fix is a minimal example and a workaround, not a replacement VC + generator over a second semantics. - **No Velvet dependency:** Velvet needs Lean 4.34. +- **Failure is an outcome.** A failed `assert`, an unsupported statement or an ill-typed + expression is the `none` outcome, which no specification admits. ## Mapping @@ -41,39 +85,25 @@ flowchart TD | `call` | the callee's proved specification | | `in`, `inout`, `out` parameters (Boole's globals and `modifies` become these) | arguments and results | | `int`, `bool`, `nat`, `bv n`, `Sequence`, `Map` | `Int`, `Bool`, `Nat`, `BitVec n`, `List`/`Array`, functions | -| datatypes | inductive types | +| datatypes | see step 4 | | `cover`, local function and type declarations | to do | ## Status -`StrataBoole/Shallow/Layer.lean` provides a nondeterminism monad with `havoc`, `assume`, -`assert` and a `while` loop carrying its invariant, each with a proved rule. -`StrataBooleTest/shallow_find_max.lean` verifies three hand-written programs with it, -find max among them, and fixes the form the translation should produce. -`StrataBooleTest/shallow_generic_datatypes.lean` is a prototype of the generic datatype -model: one inductive of constructor applications for all datatypes, with the datatype laws -proved once and `pos.toInt` by structural recursion. The proofs use only Lean's standard -axioms. - -## Research questions - -1. **Variables:** represent program variables so that verification conditions range over - Lean values. In the hand-written programs they already are; the open part is getting - there from Core, in particular with an interpreter. -2. **Invariants:** pass the invariants recorded in the program to the monadic loop rules. - `whileInv` takes the invariant as an argument and its rule uses it; loops with a - measure are still missing. -3. **Adequacy:** prove the interpretation adequate with respect to Core's operational - semantics. One detail: in Core a failed `assert` sets a failure flag and execution - continues, while in `Layer.lean` it ends the run. -4. **`cover` and frames** have no counterpart in Velvet. Frames follow from Core's - `in`/`inout` parameters. `cover` checks that some path reaches it with its condition - true, which is not a weakest-precondition fact. +- `StrataBoole/Shallow/Layer.lean`: the `ND` monad with `havoc`, `assume`, `assert` and a + `while` loop carrying its invariant, each with a proved rule. + `StrataBooleTest/shallow_find_max.lean` verifies three hand-written programs with it and + fixes the form the interpreter should produce after unfolding. +- `StrataBoole/Shallow/Interpreter/` (on a fork, to be merged here): the interpreter of + step 1, with reflection of the type-checked Core program into a Lean term + (`shallow_reflect`). Not yet: calls, `exit`, nondeterministic loops, measures, + materialization of the unfolded term, and the end-to-end example of step 3. +- `StrataBooleTest/shallow_generic_datatypes.lean`: the datatype model prototype of + step 4, with the datatype laws proved once and `pos.toInt` by structural recursion. +- Step 2 and step 5 are not started. ## Open questions -- **Translator or interpreter:** generate Lean code for each program, or define the - interpretation as one Lean function, which makes adequacy a single theorem. - **Execution:** `ND` is a set of outcomes, so it cannot run programs; Velvet's monad can. - **`assume`:** in Boogie an impossible `assume` makes the path vacuous; Velvet's choice operator instead requires proving that a value exists. `Layer.lean` follows Boogie. @@ -83,6 +113,9 @@ axioms. - **Goal names:** `mvcgen` numbers the goals; they should carry the program's clause names. - **Axioms:** a program's axioms become either Lean axioms, which are trusted, or hypotheses of each theorem. +- **`cover` and frames** have no counterpart in Velvet. Frames follow from Core's + `in`/`inout` parameters. `cover` checks that some path reaches it with its condition + true, which is not a weakest-precondition fact. ## Sources From d3c185b7fda486838262a67340d043faecf9a373 Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Tue, 27 Oct 2026 11:50:58 +0200 Subject: [PATCH 09/64] Shallow embedding: leave the datatype and nat model for after steps 1 to 3 --- docs/ShallowEmbedding.md | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/docs/ShallowEmbedding.md b/docs/ShallowEmbedding.md index 8b5a4d3..6635c3f 100644 --- a/docs/ShallowEmbedding.md +++ b/docs/ShallowEmbedding.md @@ -48,13 +48,9 @@ left open. follow the program's clauses, `decreases` checks and Core notation in goals go on top of `mvcgen`, not into a separate semantics. 4. **Model.** Results must hold for every interpretation of Core's types and operators - that is consistent with Core, not for one concrete model: an unmodelled operator or an - out-of-range read must stay unconstrained, as in Core and SMT. A concrete model only - shows that such an interpretation exists. Datatypes: a single model (an inductive of - constructor applications, prototyped in `shallow_generic_datatypes.lean`) carries over - to Core only if every model Core admits is isomorphic to it, which needs - exhaustiveness and induction among Core's datatype laws. `nat` is a binary datatype in - Core; mapping it to Lean's `Nat` needs a proof that the two agree. + that is consistent with Core, not for one concrete model. How datatypes and `nat` fit + this is decided when steps 1 to 3 are done; `shallow_generic_datatypes.lean` is a first + prototype. 5. **Boole semantics.** A Boole interpreter proved to agree with the Core one on `toCoreProgram p`, so that Boole gets a semantics of its own and the lowering is verified. `toCoreExpr` is total (strata-org/Strata-Boole#25) and the `nat` library is @@ -98,8 +94,7 @@ left open. step 1, with reflection of the type-checked Core program into a Lean term (`shallow_reflect`). Not yet: calls, `exit`, nondeterministic loops, measures, materialization of the unfolded term, and the end-to-end example of step 3. -- `StrataBooleTest/shallow_generic_datatypes.lean`: the datatype model prototype of - step 4, with the datatype laws proved once and `pos.toInt` by structural recursion. +- `StrataBooleTest/shallow_generic_datatypes.lean`: a first prototype for step 4. - Step 2 and step 5 are not started. ## Open questions From d1c9b89cb8d5230d7e03b209886b04497f9ab6b7 Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Tue, 27 Oct 2026 12:07:07 +0200 Subject: [PATCH 10/64] Shallow embedding: state the interpreter and adequacy precisely interpProc takes a model; adequacy relates to Core's small-step semantics and its failure flag, with eval_denote_sound bridging eval and denote; the mapping table reflects what the interpreter does today; #25 and #26 are open PRs. --- docs/ShallowEmbedding.md | 42 +++++++++++++++++++++++----------------- 1 file changed, 24 insertions(+), 18 deletions(-) diff --git a/docs/ShallowEmbedding.md b/docs/ShallowEmbedding.md index 6635c3f..72db229 100644 --- a/docs/ShallowEmbedding.md +++ b/docs/ShallowEmbedding.md @@ -27,17 +27,22 @@ flowchart TD The steps, in order. Each one is a theorem or a tool on the branch, not a design choice left open. -1. **Interpreter.** One Lean function, `interpProc : Core.Procedure → Store → ND Store`, - gives every Core program its meaning in the `ND` monad of `Layer.lean` - (`StrataBoole/Shallow/Interpreter/`). It keeps the Core AST as data, evaluates - expressions with Strata's own `LExpr.denote`, and has no second evaluator. Unfolding - it on a concrete program yields the monadic term that `mvcgen` works on; this is what - "shallow" refers to. There is no per-program translator: a generated program would be - a second meaning of the source that nothing checks. +1. **Interpreter.** One Lean function, `interpProc M p σ`, gives every Core procedure `p` + its meaning in the `ND` monad of `Layer.lean`, from a store `σ` and parametric in a model + `M` of Core's types and operators (`StrataBoole/Shallow/Interpreter/`). It keeps the + Core AST as data, evaluates expressions with Strata's own `LExpr.denote`, and has no + second evaluator. Unfolding it on a concrete program yields the monadic term that + `mvcgen` works on; this is what "shallow" refers to. There is no per-program translator: + a generated program would be a second meaning of the source that nothing checks. 2. **Adequacy.** Prove that the interpreter agrees with Core's operational semantics - (`StatementSemantics.lean`): if Core can run `s` from `σ` to `σ'`, then `σ'` is an - outcome of `interpStmts s σ`, and a failed check in Core is the failure outcome. This - single theorem is what makes the Lean path trustworthy. Everything the interpreter does + (`Imperative/StmtSemantics.lean` and `CmdSemantics.lean`, instantiated for Core in + `Core/StatementSemantics.lean`): if Core runs `s` from `σ` to `σ'` without a failure, + then `some σ'` is an outcome of `interpStmts s σ`, and if a check fails along the way, + `none` is. Core records a failed check in a flag and keeps running, while `ND` stops, + which the statement accounts for. Core's semantics evaluates expressions with Strata's + evaluator `LExpr.eval`, the interpreter with `LExpr.denote`; the two are related by + `eval_denote_sound` (`LExprSemanticsConsistent.lean`). This theorem is what makes the + Lean path trustworthy. Everything the interpreter does not cover must fail, never be vacuous, so that a missing case cannot prove a specification. 3. **Proof rules and tactic.** `Layer.lean` already has the rules (`havoc_spec`, @@ -53,8 +58,8 @@ left open. prototype. 5. **Boole semantics.** A Boole interpreter proved to agree with the Core one on `toCoreProgram p`, so that Boole gets a semantics of its own and the lowering is - verified. `toCoreExpr` is total (strata-org/Strata-Boole#25) and the `nat` library is - added inside `typeCheck` (strata-org/Strata-Boole#26) so that this statement can be made. + verified. This needs `toCoreExpr` total and the `nat` library added inside `typeCheck`, + which are strata-org/Strata-Boole#25 and #26. ## Decisions @@ -67,19 +72,20 @@ left open. generator over a second semantics. - **No Velvet dependency:** Velvet needs Lean 4.34. - **Failure is an outcome.** A failed `assert`, an unsupported statement or an ill-typed - expression is the `none` outcome, which no specification admits. + expression is the `none` outcome (`ND.fail` in the interpreter), which no specification + admits. ## Mapping | Core | Lean | | --- | --- | | assignments, `if`, locals | `do` notation | -| `exit` from a loop or the procedure | `break`, `return` | -| other labeled `exit` | to do, e.g. one exception per label | +| `exit`, labeled or not | to do | | `while` without a measure, `havoc`, `assume`, `assert` | `Layer.lean` | -| `while` with a measure, nondeterministic `init`, `if *`, `while *` | to do | -| `call` | the callee's proved specification | -| `in`, `inout`, `out` parameters (Boole's globals and `modifies` become these) | arguments and results | +| `if *` | a `havoc` of the condition | +| `while` with a measure, `while *` | to do | +| `call` | to decide: the callee's specification, or its body | +| `in`, `inout`, `out` parameters (Boole's globals and `modifies` become these) | store entries; an `out` starts arbitrary, an `inout` keeps its input | | `int`, `bool`, `nat`, `bv n`, `Sequence`, `Map` | `Int`, `Bool`, `Nat`, `BitVec n`, `List`/`Array`, functions | | datatypes | see step 4 | | `cover`, local function and type declarations | to do | From 6e77eec22cf763cf1256d27d4d82035d4653538b Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Tue, 27 Oct 2026 12:10:32 +0200 Subject: [PATCH 11/64] Shallow embedding: shorten the design doc --- docs/ShallowEmbedding.md | 148 +++++++++++++++++---------------------- 1 file changed, 63 insertions(+), 85 deletions(-) diff --git a/docs/ShallowEmbedding.md b/docs/ShallowEmbedding.md index 72db229..b418a07 100644 --- a/docs/ShallowEmbedding.md +++ b/docs/ShallowEmbedding.md @@ -1,11 +1,12 @@ # Shallow embedding of Strata in Lean -The goal is to verify Boole programs in Lean with proofs that are sound by construction. -Today's Lean path trusts the VC generator, the SMT encoding and a bridge axiom -(strata-org/Strata#1488 shows it can prove `False`). Here the only trusted parts are Core's -semantics and Lean, and the verification conditions range over Lean values, so Lean tactics -work on them directly, without a solver. Boole programs reach it through their lowering to -Core. +## Goal + +Verify Boole programs in Lean with proofs that are sound by construction. Today's Lean +path trusts the VC generator, the SMT encoding and a bridge axiom, and strata-org/Strata#1488 +shows it can prove `False`. Here the trusted parts are Core's semantics and Lean, and the +goals range over Lean values, so Lean tactics work on them without a solver. Boole programs +reach it through their lowering to Core. ```mermaid flowchart TD @@ -14,7 +15,7 @@ flowchart TD V["VC generation and SMT encoding"] --> S["cvc5, or Lean via lean-smt"] end subgraph lean ["Lean path"] - I["interpreter: Core AST to ND"] --> G["unfold, then Std.Do + mvcgen + Layer.lean"] + I["interpreter: Core AST to ND"] --> G["unfold, then mvcgen with Layer.lean"] G --> P["Lean proof"] end C --> V @@ -24,99 +25,76 @@ flowchart TD ## Plan -The steps, in order. Each one is a theorem or a tool on the branch, not a design choice -left open. - -1. **Interpreter.** One Lean function, `interpProc M p σ`, gives every Core procedure `p` - its meaning in the `ND` monad of `Layer.lean`, from a store `σ` and parametric in a model - `M` of Core's types and operators (`StrataBoole/Shallow/Interpreter/`). It keeps the - Core AST as data, evaluates expressions with Strata's own `LExpr.denote`, and has no - second evaluator. Unfolding it on a concrete program yields the monadic term that - `mvcgen` works on; this is what "shallow" refers to. There is no per-program translator: - a generated program would be a second meaning of the source that nothing checks. -2. **Adequacy.** Prove that the interpreter agrees with Core's operational semantics - (`Imperative/StmtSemantics.lean` and `CmdSemantics.lean`, instantiated for Core in - `Core/StatementSemantics.lean`): if Core runs `s` from `σ` to `σ'` without a failure, - then `some σ'` is an outcome of `interpStmts s σ`, and if a check fails along the way, - `none` is. Core records a failed check in a flag and keeps running, while `ND` stops, - which the statement accounts for. Core's semantics evaluates expressions with Strata's - evaluator `LExpr.eval`, the interpreter with `LExpr.denote`; the two are related by - `eval_denote_sound` (`LExprSemanticsConsistent.lean`). This theorem is what makes the - Lean path trustworthy. Everything the interpreter does - not cover must fail, never be vacuous, so that a missing case cannot prove a - specification. -3. **Proof rules and tactic.** `Layer.lean` already has the rules (`havoc_spec`, - `assume_spec`, `assert_spec`, `whileInv_spec`, each a proved `@[spec]` theorem) and - `mvcgen` is the tactic that applies them. The first program proved end to end through - the interpreter, `find_max`, is the milestone for this step: `shallow_reflect`, unfold - `interpProc`, `mvcgen`, then `grind`/`omega`. Improvements such as goal names that - follow the program's clauses, `decreases` checks and Core notation in goals go on top - of `mvcgen`, not into a separate semantics. +1. **Interpreter.** `interpProc M p σ` gives a Core procedure `p` its meaning in the `ND` + monad of `Layer.lean`, from a store `σ`, for a model `M` of Core's types and + operators (`StrataBoole/Shallow/Interpreter/`). The Core AST stays data. Expressions + are evaluated with Strata's `LExpr.denote`, so there is no second evaluator. Unfolding + the interpreter on a program gives the monadic term that `mvcgen` works on. That term + is the shallow embedding. There is no per-program translator: a generated program + would be a second meaning of the source that nothing checks. +2. **Adequacy.** Prove the interpreter agrees with Core's operational semantics + (`Imperative/StmtSemantics.lean`, `CmdSemantics.lean`, instantiated in + `Core/StatementSemantics.lean`). If Core runs `s` from `σ` to `σ'` without a failure, + `some σ'` is an outcome of `interpStmts s σ`; if a check fails on the way, `none` is. + Two details: Core sets a failure flag and keeps running where `ND` stops, and Core + evaluates expressions with `LExpr.eval` where the interpreter uses `LExpr.denote`, + which `eval_denote_sound` relates. Anything the interpreter does not cover must fail, + so a missing case cannot prove a specification. +3. **Proof rules and tactic.** `Layer.lean` has the rules (`havoc_spec`, `assume_spec`, + `assert_spec`, `whileInv_spec`, proved `@[spec]` theorems) and `mvcgen` applies them. + Milestone: `find_max` proved end to end, by `shallow_reflect`, unfolding `interpProc`, + `mvcgen`, then `grind` or `omega`. Goal names from the program, `decreases` checks and + Core notation in goals go on top of `mvcgen`, not into a separate semantics. 4. **Model.** Results must hold for every interpretation of Core's types and operators - that is consistent with Core, not for one concrete model. How datatypes and `nat` fit - this is decided when steps 1 to 3 are done; `shallow_generic_datatypes.lean` is a first - prototype. + consistent with Core, not for one concrete model. Datatypes and `nat` are decided after + steps 1 to 3; `shallow_generic_datatypes.lean` is a first prototype. 5. **Boole semantics.** A Boole interpreter proved to agree with the Core one on - `toCoreProgram p`, so that Boole gets a semantics of its own and the lowering is - verified. This needs `toCoreExpr` total and the `nat` library added inside `typeCheck`, - which are strata-org/Strata-Boole#25 and #26. + `toCoreProgram p`. Needs `toCoreExpr` total and the `nat` library inside `typeCheck` + (strata-org/Strata-Boole#25 and #26). ## Decisions -- **Input is Core**, which has a formal semantics, so the interpretation can be proved - adequate against it. Boole and other front ends lower to Core. -- **Interpreter, not translator.** See step 1. -- **Framework: `Std.Do` and `mvcgen`**, available in Lean 4.29 and 4.31. Lean marks - `mvcgen` experimental; its successor `vcgen` needs Lean 4.33. If `mvcgen` misbehaves - on a construct, the fix is a minimal example and a workaround, not a replacement VC - generator over a second semantics. -- **No Velvet dependency:** Velvet needs Lean 4.34. -- **Failure is an outcome.** A failed `assert`, an unsupported statement or an ill-typed - expression is the `none` outcome (`ND.fail` in the interpreter), which no specification - admits. +- Input is Core, because Core has a semantics to prove adequacy against. +- Interpreter, not translator (step 1). +- `Std.Do` and `mvcgen`, available on Lean 4.29 and 4.31. `vcgen` needs 4.33, Velvet + 4.34. If `mvcgen` misbehaves on a construct, the fix is a minimal example and a + workaround, not a replacement VC generator over a second semantics. +- Failure is an outcome. A failed `assert`, an unsupported statement or an ill-typed + expression is the `none` outcome (`ND.fail`), which no specification admits. -## Mapping +## Coverage -| Core | Lean | +| Core | Lean path | | --- | --- | -| assignments, `if`, locals | `do` notation | -| `exit`, labeled or not | to do | -| `while` without a measure, `havoc`, `assume`, `assert` | `Layer.lean` | -| `if *` | a `havoc` of the condition | -| `while` with a measure, `while *` | to do | -| `call` | to decide: the callee's specification, or its body | +| assignments, `if`, `if *`, locals, blocks | interpreter | +| `havoc`, `assume`, `assert`, `while` with invariants | `Layer.lean` | | `in`, `inout`, `out` parameters (Boole's globals and `modifies` become these) | store entries; an `out` starts arbitrary, an `inout` keeps its input | -| `int`, `bool`, `nat`, `bv n`, `Sequence`, `Map` | `Int`, `Bool`, `Nat`, `BitVec n`, `List`/`Array`, functions | -| datatypes | see step 4 | -| `cover`, local function and type declarations | to do | +| `int`, `bool`, `bv n`, `Map`, `Sequence` | `Int`, `Bool`, `BitVec n`, functions, `List` | +| `exit`, `call`, `while *`, loop measures, `cover`, local functions and types | to do; for `call`, callee's spec or body is to decide | +| datatypes, `nat` | step 4 | ## Status -- `StrataBoole/Shallow/Layer.lean`: the `ND` monad with `havoc`, `assume`, `assert` and a - `while` loop carrying its invariant, each with a proved rule. - `StrataBooleTest/shallow_find_max.lean` verifies three hand-written programs with it and - fixes the form the interpreter should produce after unfolding. -- `StrataBoole/Shallow/Interpreter/` (on a fork, to be merged here): the interpreter of - step 1, with reflection of the type-checked Core program into a Lean term - (`shallow_reflect`). Not yet: calls, `exit`, nondeterministic loops, measures, - materialization of the unfolded term, and the end-to-end example of step 3. -- `StrataBooleTest/shallow_generic_datatypes.lean`: a first prototype for step 4. -- Step 2 and step 5 are not started. +- `StrataBoole/Shallow/Layer.lean`: the `ND` monad and the rules. + `StrataBooleTest/shallow_find_max.lean` verifies three hand-written programs with it, in + the form the interpreter should produce after unfolding. +- `StrataBoole/Shallow/Interpreter/` (on a fork, to be merged here): the interpreter and + `shallow_reflect`, which reflects the type-checked Core program into a Lean term. Missing + for the step 3 milestone: a `simp` set for `denote` over annotated expressions, and + metadata stripped from the reflected term. +- `StrataBooleTest/shallow_generic_datatypes.lean`: step 4 prototype. +- Steps 2 and 5 not started. ## Open questions -- **Execution:** `ND` is a set of outcomes, so it cannot run programs; Velvet's monad can. -- **`assume`:** in Boogie an impossible `assume` makes the path vacuous; Velvet's choice - operator instead requires proving that a value exists. `Layer.lean` follows Boogie. -- **Reads:** a checked read needs an `assert` or Lean's `a[i]'h`. Core leaves an - out-of-range `select!` unconstrained, while Lean's `a[i]!` returns a default value, - which proofs must not rely on. -- **Goal names:** `mvcgen` numbers the goals; they should carry the program's clause names. -- **Axioms:** a program's axioms become either Lean axioms, which are trusted, or - hypotheses of each theorem. -- **`cover` and frames** have no counterpart in Velvet. Frames follow from Core's - `in`/`inout` parameters. `cover` checks that some path reaches it with its condition - true, which is not a weakest-precondition fact. +- `ND` is a set of outcomes, so it cannot run programs; Velvet's monad can. +- `assume`: Boogie makes an impossible `assume` vacuous; Velvet's choice operator requires + a witness. `Layer.lean` follows Boogie. +- Out-of-range reads: Core leaves `select!` unconstrained, Lean's `a[i]!` returns a + default. Proofs must not rely on the default. +- `mvcgen` numbers goals; they should carry the program's clause names. +- A program's axioms become Lean axioms, which are trusted, or hypotheses of each theorem. +- `cover` is a reachability check, not a weakest-precondition fact. ## Sources From ca376cfc8af0cfc7b81cd9bbf215f430e06522ae Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Tue, 27 Oct 2026 12:16:10 +0200 Subject: [PATCH 12/64] Shallow embedding: shorten the design doc and spell out the path --- docs/ShallowEmbedding.md | 61 +++++++++++++++++++++++++--------------- 1 file changed, 38 insertions(+), 23 deletions(-) diff --git a/docs/ShallowEmbedding.md b/docs/ShallowEmbedding.md index b418a07..bd5bcea 100644 --- a/docs/ShallowEmbedding.md +++ b/docs/ShallowEmbedding.md @@ -25,26 +25,37 @@ flowchart TD ## Plan +Steps 2 and 3 are independent and proceed in parallel; step 3 is the first milestone. + 1. **Interpreter.** `interpProc M p σ` gives a Core procedure `p` its meaning in the `ND` monad of `Layer.lean`, from a store `σ`, for a model `M` of Core's types and operators (`StrataBoole/Shallow/Interpreter/`). The Core AST stays data. Expressions are evaluated with Strata's `LExpr.denote`, so there is no second evaluator. Unfolding the interpreter on a program gives the monadic term that `mvcgen` works on. That term is the shallow embedding. There is no per-program translator: a generated program - would be a second meaning of the source that nothing checks. + would be a second meaning of the source that nothing checks. Entry point: + `shallow_reflect` takes a `#strata program Boole` block, lowers and type checks it with + `Strata.Boole.typeCheck`, and binds the Core AST as a Lean term `_ast`. Every + statement is about that term. 2. **Adequacy.** Prove the interpreter agrees with Core's operational semantics - (`Imperative/StmtSemantics.lean`, `CmdSemantics.lean`, instantiated in - `Core/StatementSemantics.lean`). If Core runs `s` from `σ` to `σ'` without a failure, - `some σ'` is an outcome of `interpStmts s σ`; if a check fails on the way, `none` is. + (`Strata/DL/Imperative/StmtSemantics.lean` and `CmdSemantics.lean`, instantiated in + `Strata/Languages/Core/StatementSemantics.lean`). If Core runs `s` from `σ` to `σ'` + without a failure, `some σ'` is an outcome of `interpStmts s σ`; if a check fails on + the way, `none` is. Two details: Core sets a failure flag and keeps running where `ND` stops, and Core evaluates expressions with `LExpr.eval` where the interpreter uses `LExpr.denote`, - which `eval_denote_sound` relates. Anything the interpreter does not cover must fail, - so a missing case cannot prove a specification. + which `eval_denote_sound` relates. Core's semantics is still growing; adequacy covers + what it covers. Anything the interpreter does not cover must fail, so a missing case + cannot prove a specification. 3. **Proof rules and tactic.** `Layer.lean` has the rules (`havoc_spec`, `assume_spec`, `assert_spec`, `whileInv_spec`, proved `@[spec]` theorems) and `mvcgen` applies them. - Milestone: `find_max` proved end to end, by `shallow_reflect`, unfolding `interpProc`, - `mvcgen`, then `grind` or `omega`. Goal names from the program, `decreases` checks and - Core notation in goals go on top of `mvcgen`, not into a separate semantics. + A procedure's contract is read as the triple to prove: `requires` is the precondition, + the checked `ensures` the postcondition, both as Lean propositions about the store. + Milestone: `find_max` proved end to end. The path: `shallow_reflect` with metadata + stripped, unfold `interpProc`, a `simp` set that turns `denote` of an annotated + expression into the Lean operation on store values, `mvcgen`, then `grind` or `omega`. + Goal names from the program, `decreases` checks and Core notation in goals go on top of + `mvcgen`, not into a separate semantics. 4. **Model.** Results must hold for every interpretation of Core's types and operators consistent with Core, not for one concrete model. Datatypes and `nat` are decided after steps 1 to 3; `shallow_generic_datatypes.lean` is a first prototype. @@ -54,13 +65,18 @@ flowchart TD ## Decisions -- Input is Core, because Core has a semantics to prove adequacy against. +- Core first, then Boole. The Core interpreter is proved against Core's semantics; the + Boole interpreter is then proved to agree with it on `toCoreProgram p` (step 5), which + also verifies the Boole to Core lowering. Starting from Boole directly would leave nothing + to prove adequacy against. - Interpreter, not translator (step 1). - `Std.Do` and `mvcgen`, available on Lean 4.29 and 4.31. `vcgen` needs 4.33, Velvet 4.34. If `mvcgen` misbehaves on a construct, the fix is a minimal example and a workaround, not a replacement VC generator over a second semantics. - Failure is an outcome. A failed `assert`, an unsupported statement or an ill-typed expression is the `none` outcome (`ND.fail`), which no specification admits. +- `assume` follows Boogie: an impossible `assume` makes the path vacuous. Velvet's choice + operator requires a witness instead. ## Coverage @@ -70,7 +86,7 @@ flowchart TD | `havoc`, `assume`, `assert`, `while` with invariants | `Layer.lean` | | `in`, `inout`, `out` parameters (Boole's globals and `modifies` become these) | store entries; an `out` starts arbitrary, an `inout` keeps its input | | `int`, `bool`, `bv n`, `Map`, `Sequence` | `Int`, `Bool`, `BitVec n`, functions, `List` | -| `exit`, `call`, `while *`, loop measures, `cover`, local functions and types | to do; for `call`, callee's spec or body is to decide | +| `exit`, `call`, `while *`, loop measures, `cover`, local type declarations | to do; for `call`, callee's spec or body is to decide | | datatypes, `nat` | step 4 | ## Status @@ -78,23 +94,22 @@ flowchart TD - `StrataBoole/Shallow/Layer.lean`: the `ND` monad and the rules. `StrataBooleTest/shallow_find_max.lean` verifies three hand-written programs with it, in the form the interpreter should produce after unfolding. -- `StrataBoole/Shallow/Interpreter/` (on a fork, to be merged here): the interpreter and - `shallow_reflect`, which reflects the type-checked Core program into a Lean term. Missing - for the step 3 milestone: a `simp` set for `denote` over annotated expressions, and - metadata stripped from the reflected term. +- `StrataBoole/Shallow/Interpreter/` (not yet on this branch): the interpreter and + `shallow_reflect`. Missing for the step 3 milestone: the contract as a triple, the + `simp` set for `denote`, and metadata stripping. - `StrataBooleTest/shallow_generic_datatypes.lean`: step 4 prototype. - Steps 2 and 5 not started. ## Open questions -- `ND` is a set of outcomes, so it cannot run programs; Velvet's monad can. -- `assume`: Boogie makes an impossible `assume` vacuous; Velvet's choice operator requires - a witness. `Layer.lean` follows Boogie. -- Out-of-range reads: Core leaves `select!` unconstrained, Lean's `a[i]!` returns a - default. Proofs must not rely on the default. -- `mvcgen` numbers goals; they should carry the program's clause names. -- A program's axioms become Lean axioms, which are trusted, or hypotheses of each theorem. -- `cover` is a reachability check, not a weakest-precondition fact. +- `call`: interpret a call by the callee's specification, or by its body? +- Loop measures: the loop rule gives partial correctness. Check `decreases` in the + interpreter, or prove termination separately? +- Goal names: `mvcgen` numbers goals; they should carry the program's clause names. +- Axioms of a program: Lean axioms, which are trusted, or hypotheses of each theorem? +- `cover`: a reachability check, not a weakest-precondition fact. How to state it? +- Execution: `ND` is a set of outcomes and cannot run programs, Velvet's monad can. Is + running programs needed? ## Sources From 951cd5cdd2af2cf80d5a06f2e799cf5860dfd45f Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Wed, 28 Oct 2026 07:53:45 +0200 Subject: [PATCH 13/64] Shallow embedding: build on Lean 4.34 `assert` is a reserved `do` element since 4.33, so the layer's is written `ND.assert`. Note in the doc that `vcgen` and Velvet are now available. Co-Authored-By: Claude Fable 5.1 --- StrataBooleTest/shallow_find_max.lean | 6 +++--- docs/ShallowEmbedding.md | 8 +++++--- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/StrataBooleTest/shallow_find_max.lean b/StrataBooleTest/shallow_find_max.lean index bbe2d68..c5fe678 100644 --- a/StrataBooleTest/shallow_find_max.lean +++ b/StrataBooleTest/shallow_find_max.lean @@ -41,7 +41,7 @@ theorem sum_to_spec (n : Int) (h : n ≥ 0) : /-- Find max, from the Verus translator's Boole output. State: `(max, i)`. -/ def find_max (nums : Array (BitVec 32)) : ND (BitVec 32) := do - assert (0 < nums.size) + ND.assert (0 < nums.size) let s ← whileInv (fun s : BitVec 32 × Int => (∃ j : Int, 0 ≤ j ∧ j < s.2 ∧ s.1 = nums[j.toNat]!) ∧ @@ -49,9 +49,9 @@ def find_max (nums : Array (BitVec 32)) : ND (BitVec 32) := do 0 ≤ s.2 ∧ s.2 ≤ nums.size) (fun s => s.2 < nums.size) (fun s => do - assert (0 ≤ s.2 ∧ s.2 < nums.size) + ND.assert (0 ≤ s.2 ∧ s.2 < nums.size) let max := if BitVec.slt s.1 nums[s.2.toNat]! then nums[s.2.toNat]! else s.1 - assert (0 ≤ s.2 + 1 ∧ s.2 + 1 ≤ 18446744073709551615) + ND.assert (0 ≤ s.2 + 1 ∧ s.2 + 1 ≤ 18446744073709551615) pure (max, (s.2 + 1) % 18446744073709551616)) (nums[0]!, 1) return s.1 diff --git a/docs/ShallowEmbedding.md b/docs/ShallowEmbedding.md index bd5bcea..0c7bd53 100644 --- a/docs/ShallowEmbedding.md +++ b/docs/ShallowEmbedding.md @@ -70,9 +70,11 @@ Steps 2 and 3 are independent and proceed in parallel; step 3 is the first miles also verifies the Boole to Core lowering. Starting from Boole directly would leave nothing to prove adequacy against. - Interpreter, not translator (step 1). -- `Std.Do` and `mvcgen`, available on Lean 4.29 and 4.31. `vcgen` needs 4.33, Velvet - 4.34. If `mvcgen` misbehaves on a construct, the fix is a minimal example and a - workaround, not a replacement VC generator over a second semantics. +- `Std.Do` and `mvcgen`. Since the move to Lean 4.34, `vcgen` (`Std.Internal.Do`) and + Velvet are available too; switching is an option once the end-to-end milestone works + on `mvcgen`. If `mvcgen` misbehaves on a construct, the fix is a minimal example and + a workaround, not a replacement VC generator over a second semantics. Note that in a + `do` block `assert` now names Lean's own gadget, so the layer's is written `ND.assert`. - Failure is an outcome. A failed `assert`, an unsupported statement or an ill-typed expression is the `none` outcome (`ND.fail`), which no specification admits. - `assume` follows Boogie: an impossible `assume` makes the path vacuous. Velvet's choice From e88f689a94416051bad4835dd6488c99275c427e Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Wed, 28 Oct 2026 17:24:59 +0200 Subject: [PATCH 14/64] Lean path: build on Core's Hoare logic Strata main has a Hoare logic for Core over its operational semantics, with proved rules, a contract reading and model genericity. The plan becomes a VC tactic over that triple plus lifting of goals to Lean values; the interpreter into ND and a separate semantics are superseded. Co-Authored-By: Claude Opus 5.5 --- docs/ShallowEmbedding.md | 160 +++++++++++++++++++-------------------- 1 file changed, 77 insertions(+), 83 deletions(-) diff --git a/docs/ShallowEmbedding.md b/docs/ShallowEmbedding.md index 0c7bd53..211baf4 100644 --- a/docs/ShallowEmbedding.md +++ b/docs/ShallowEmbedding.md @@ -1,4 +1,4 @@ -# Shallow embedding of Strata in Lean +# Verifying Boole programs in Lean ## Goal @@ -15,107 +15,101 @@ flowchart TD V["VC generation and SMT encoding"] --> S["cvc5, or Lean via lean-smt"] end subgraph lean ["Lean path"] - I["interpreter: Core AST to ND"] --> G["unfold, then mvcgen with Layer.lean"] - G --> P["Lean proof"] + H["Core.Logic.Hoare: contract as a triple"] --> T["tactic applies the proved rules"] + T --> G["lifted goals over Lean values"] --> P["Lean proof"] end C --> V - C --> I - O["Core operational semantics"] -. adequacy .- I + C --> H + O["Core operational semantics"] -. rules are theorems about it .- H ``` +## What Strata already provides + +`Strata/Languages/Core/Logic/` (on Strata `main` since September 2026) is a Hoare logic for +Core over Core's own operational semantics: + +- `Core.Logic.Hoare.Triple π params Pre ss Post`, quantified over every model of the + program's uninterpreted symbols (`Lambda.Interp Core.Factory`). +- Proved rules for `cmd`, `set`, `init`, `seq`, `block`, `exit`, `ite`, `while_rule` + (partial correctness) and `call_of_contract`. +- `Procedure.contractTriple`, which reads `requires` and `ensures` as the triple to prove, + with `old` snapshots and typed parameters, and `SpecHoareConnection`, which relates the + triple to Strata's own notion of assertion validity. +- Conditions are interpreted with `LExpr.denote`; statements evaluate expressions with + `Expression.eval` over `Core.Factory`. + +Its tests prove eleven procedures by applying the rules by hand, with `native_decide` +for facts about the AST. There is no automation and no lifting: a goal reads +`Expression.eval ρ.factory ρ.store e = some v`, not `x ≥ y`. + ## Plan -Steps 2 and 3 are independent and proceed in parallel; step 3 is the first milestone. - -1. **Interpreter.** `interpProc M p σ` gives a Core procedure `p` its meaning in the `ND` - monad of `Layer.lean`, from a store `σ`, for a model `M` of Core's types and - operators (`StrataBoole/Shallow/Interpreter/`). The Core AST stays data. Expressions - are evaluated with Strata's `LExpr.denote`, so there is no second evaluator. Unfolding - the interpreter on a program gives the monadic term that `mvcgen` works on. That term - is the shallow embedding. There is no per-program translator: a generated program - would be a second meaning of the source that nothing checks. Entry point: - `shallow_reflect` takes a `#strata program Boole` block, lowers and type checks it with - `Strata.Boole.typeCheck`, and binds the Core AST as a Lean term `_ast`. Every - statement is about that term. -2. **Adequacy.** Prove the interpreter agrees with Core's operational semantics - (`Strata/DL/Imperative/StmtSemantics.lean` and `CmdSemantics.lean`, instantiated in - `Strata/Languages/Core/StatementSemantics.lean`). If Core runs `s` from `σ` to `σ'` - without a failure, `some σ'` is an outcome of `interpStmts s σ`; if a check fails on - the way, `none` is. - Two details: Core sets a failure flag and keeps running where `ND` stops, and Core - evaluates expressions with `LExpr.eval` where the interpreter uses `LExpr.denote`, - which `eval_denote_sound` relates. Core's semantics is still growing; adequacy covers - what it covers. Anything the interpreter does not cover must fail, so a missing case - cannot prove a specification. -3. **Proof rules and tactic.** `Layer.lean` has the rules (`havoc_spec`, `assume_spec`, - `assert_spec`, `whileInv_spec`, proved `@[spec]` theorems) and `mvcgen` applies them. - A procedure's contract is read as the triple to prove: `requires` is the precondition, - the checked `ensures` the postcondition, both as Lean propositions about the store. - Milestone: `find_max` proved end to end. The path: `shallow_reflect` with metadata - stripped, unfold `interpProc`, a `simp` set that turns `denote` of an annotated - expression into the Lean operation on store values, `mvcgen`, then `grind` or `omega`. - Goal names from the program, `decreases` checks and Core notation in goals go on top of - `mvcgen`, not into a separate semantics. -4. **Model.** Results must hold for every interpretation of Core's types and operators - consistent with Core, not for one concrete model. Datatypes and `nat` are decided after - steps 1 to 3; `shallow_generic_datatypes.lean` is a first prototype. -5. **Boole semantics.** A Boole interpreter proved to agree with the Core one on - `toCoreProgram p`. Needs `toCoreExpr` total and the `nat` library inside `typeCheck` - (strata-org/Strata-Boole#25 and #26). +1. **VC generation tactic over `Core.Logic.Hoare`.** From `Procedure.contractTriple p params + name`, apply the rules backwards statement by statement and discharge their side + conditions (`InitEnvWF`, `PostWF`, `exitsCoveredByBlocks`) by evaluation on the + concrete AST. The result is one goal per `assert`, loop invariant and `ensures`, over + the store. This is the shape of `core_vcgen` in `StrataBoole/Deep/` (branch + `exp/deep-embedding`), retargeted from its own `Exec` to Strata's `Triple`. +2. **Lifting.** Turn each goal into a proposition over Lean values: a store slot of type + `int` is an `Int` (`inputAsPredicate` gives the literal), `Expression.eval` of an + operator on literals is the Lean operation (`eval_intGe_value_of_numerals` and its + siblings exist; the missing operators are added), and a contract clause under + `denote` becomes the corresponding proposition. This is the shape of `core_lift`. + Milestone: `max2`, then `find_max`, proved by the tactic, lifting, and `omega`/`grind`. +3. **Boole entry.** `shallow_reflect` already produces the type-checked Core program as a + Lean term; it is the input of step 1, so a user writes a `#strata program Boole` block + and states `contractTriple` on its procedures. +4. **Gaps shared with Strata, fixed in Strata.** Rules for nondeterministic `if` and + `while` (today only the deterministic forms have rules); user-defined functions in the + model (Strata's own TODO); a denotation for datatypes, which is strata-org/Strata#1480 + and is also what makes Boole's `nat` provable. +5. **Boole semantics.** A Boole interpreter proved to agree with `toCoreProgram`, so Boole + gets a semantics of its own. Needs `toCoreExpr` total and the `nat` library inside + `typeCheck`, both merged (strata-org/Strata-Boole#25, #26). Later. ## Decisions -- Core first, then Boole. The Core interpreter is proved against Core's semantics; the - Boole interpreter is then proved to agree with it on `toCoreProgram p` (step 5), which - also verifies the Boole to Core lowering. Starting from Boole directly would leave nothing - to prove adequacy against. -- Interpreter, not translator (step 1). -- `Std.Do` and `mvcgen`. Since the move to Lean 4.34, `vcgen` (`Std.Internal.Do`) and - Velvet are available too; switching is an option once the end-to-end milestone works - on `mvcgen`. If `mvcgen` misbehaves on a construct, the fix is a minimal example and - a workaround, not a replacement VC generator over a second semantics. Note that in a - `do` block `assert` now names Lean's own gadget, so the layer's is written `ND.assert`. -- Failure is an outcome. A failed `assert`, an unsupported statement or an ill-typed - expression is the `none` outcome (`ND.fail`), which no specification admits. -- `assume` follows Boogie: an impossible `assume` makes the path vacuous. Velvet's choice - operator requires a witness instead. - -## Coverage - -| Core | Lean path | +- Build on `Core.Logic.Hoare`, not on a semantics of our own. `Deep/` defines its own + `Exec` and `eval`, which nothing connects to Core's semantics; the interpreter plan + needed an adequacy proof that would redo what Strata's rules already prove. Both are + replaced by the tactic and lifting over Strata's triple. +- Core first, then Boole. Starting from Boole directly would leave nothing to prove + adequacy against. +- Goals over Lean values are what makes this usable; they come from lifting, not from a + monadic encoding. `Std.Do`/`mvcgen` (`StrataBoole/Shallow/Layer.lean`) is no longer on + the path; the files stay until the milestone is reached on the new path. +- Failure is never vacuous: a construct the tactic cannot handle leaves the goal open + instead of closing it. + +## Coverage of the rules + +| Core | `Core.Logic.Hoare` | | --- | --- | -| assignments, `if`, `if *`, locals, blocks | interpreter | -| `havoc`, `assume`, `assert`, `while` with invariants | `Layer.lean` | -| `in`, `inout`, `out` parameters (Boole's globals and `modifies` become these) | store entries; an `out` starts arbitrary, an `inout` keeps its input | -| `int`, `bool`, `bv n`, `Map`, `Sequence` | `Int`, `Bool`, `BitVec n`, functions, `List` | -| `exit`, `call`, `while *`, loop measures, `cover`, local type declarations | to do; for `call`, callee's spec or body is to decide | -| datatypes, `nat` | step 4 | +| assignments, `init`, `assert`, `assume`, `havoc` (as `set x *` through `cmd`), blocks, `exit`, deterministic `if` and `while`, `call` | rules exist | +| `if *`, `while *`, loop measures, `cover` | to add | +| `int`, `bool`, `bv n`, `Map`, `Sequence` | denoted; lifting lemmas exist for `Int` comparisons, `+`, `*`, `not` | +| user functions, datatypes, `nat` | step 4 | ## Status -- `StrataBoole/Shallow/Layer.lean`: the `ND` monad and the rules. - `StrataBooleTest/shallow_find_max.lean` verifies three hand-written programs with it, in - the form the interpreter should produce after unfolding. -- `StrataBoole/Shallow/Interpreter/` (not yet on this branch): the interpreter and - `shallow_reflect`. Missing for the step 3 milestone: the contract as a triple, the - `simp` set for `denote`, and metadata stripping. -- `StrataBooleTest/shallow_generic_datatypes.lean`: step 4 prototype. -- Steps 2 and 5 not started. +- Nothing of steps 1 and 2 exists yet against Strata's triple. `Deep/` has both pieces + against its own semantics, with `max2` and a counting loop proved; the retargeting is + the work. +- `StrataBoole/Shallow/Interpreter/` (interpreter into `ND`) and `Layer.lean` are + superseded by the decision above. `shallow_reflect` is kept for step 3. +- `StrataBooleTest/shallow_generic_datatypes.lean` is a first prototype for the datatype + denotation of step 4. ## Open questions -- `call`: interpret a call by the callee's specification, or by its body? -- Loop measures: the loop rule gives partial correctness. Check `decreases` in the - interpreter, or prove termination separately? -- Goal names: `mvcgen` numbers goals; they should carry the program's clause names. -- Axioms of a program: Lean axioms, which are trusted, or hypotheses of each theorem? -- `cover`: a reachability check, not a weakest-precondition fact. How to state it? -- Execution: `ND` is a set of outcomes and cannot run programs, Velvet's monad can. Is - running programs needed? +- Loop measures: `while_rule` is partial correctness. Add a total-correctness rule, or + check `decreases` separately? +- `cover` is a reachability check, not a Hoare fact. How to state it? +- Goal names: carry the program's clause names into the goals the tactic leaves. +- `native_decide` for AST facts: acceptable in the tactic, or avoid it? ## Sources - [Velvet (CAV'26)](https://ilyasergey.net/assets/pdf/papers/velvet-cav26.pdf) - [Foundational Multi-Modal Program Verifiers (Loom, POPL'26)](https://ilyasergey.net/assets/pdf/papers/loom-popl26.pdf) -- [verse-lab/velvet](https://github.com/verse-lab/velvet) - [ilyasergey/lean-vcgen-tutorial](https://github.com/ilyasergey/lean-vcgen-tutorial) From 218e6082de106e6d606e0e852cd3e28f4ac9687d Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Wed, 28 Oct 2026 17:31:30 +0200 Subject: [PATCH 15/64] Lean path doc: remove repeated points Co-Authored-By: Claude Opus 5.5 --- docs/ShallowEmbedding.md | 24 ++++++++++-------------- 1 file changed, 10 insertions(+), 14 deletions(-) diff --git a/docs/ShallowEmbedding.md b/docs/ShallowEmbedding.md index 211baf4..eac7a9c 100644 --- a/docs/ShallowEmbedding.md +++ b/docs/ShallowEmbedding.md @@ -69,15 +69,13 @@ for facts about the AST. There is no automation and no lifting: a goal reads ## Decisions -- Build on `Core.Logic.Hoare`, not on a semantics of our own. `Deep/` defines its own - `Exec` and `eval`, which nothing connects to Core's semantics; the interpreter plan - needed an adequacy proof that would redo what Strata's rules already prove. Both are - replaced by the tactic and lifting over Strata's triple. +- Build on `Core.Logic.Hoare`, not on a semantics of our own: neither `Deep/`'s `Exec`, + which nothing connects to Core's semantics, nor an interpreter with an adequacy proof + that would redo what Strata's rules already prove. - Core first, then Boole. Starting from Boole directly would leave nothing to prove adequacy against. -- Goals over Lean values are what makes this usable; they come from lifting, not from a - monadic encoding. `Std.Do`/`mvcgen` (`StrataBoole/Shallow/Layer.lean`) is no longer on - the path; the files stay until the milestone is reached on the new path. +- Goals over Lean values come from lifting, not from a monadic encoding, so + `Std.Do`/`mvcgen` (`StrataBoole/Shallow/Layer.lean`) is off the path. - Failure is never vacuous: a construct the tactic cannot handle leaves the goal open instead of closing it. @@ -92,13 +90,11 @@ for facts about the AST. There is no automation and no lifting: a goal reads ## Status -- Nothing of steps 1 and 2 exists yet against Strata's triple. `Deep/` has both pieces - against its own semantics, with `max2` and a counting loop proved; the retargeting is - the work. -- `StrataBoole/Shallow/Interpreter/` (interpreter into `ND`) and `Layer.lean` are - superseded by the decision above. `shallow_reflect` is kept for step 3. -- `StrataBooleTest/shallow_generic_datatypes.lean` is a first prototype for the datatype - denotation of step 4. +- Steps 1 and 2: not started against Strata's triple. `Deep/` has both against its own + semantics, with `max2` and a counting loop proved. +- `StrataBoole/Shallow/Interpreter/` and `Layer.lean` are kept until the milestone is + reached; `shallow_reflect` stays for step 3. +- `StrataBooleTest/shallow_generic_datatypes.lean`: first prototype for step 4. ## Open questions From 60020eb909137b2207eb933124da828f7122ae6a Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Thu, 29 Oct 2026 11:34:43 +0200 Subject: [PATCH 16/64] Lean path doc: record what the Hoare logic's authors intend for it Co-Authored-By: Claude Fable 5.1 --- docs/ShallowEmbedding.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/ShallowEmbedding.md b/docs/ShallowEmbedding.md index eac7a9c..01a0c19 100644 --- a/docs/ShallowEmbedding.md +++ b/docs/ShallowEmbedding.md @@ -42,6 +42,12 @@ Its tests prove eleven procedures by applying the rules by hand, with `native_de for facts about the AST. There is no automation and no lifting: a goal reads `Expression.eval ρ.factory ρ.store e = some v`, not `x ≥ y`. +Its authors confirmed (October 2026) that the triple was written as the specification of +partial correctness, the invariant a correct program transformation must preserve, and +that they have no plans to automate it. Generating verification conditions against it is +open to others, and they see no blocker once the generator's correctness is established. +So the tactic below is ours to build, and the triple is a stable target. + ## Plan 1. **VC generation tactic over `Core.Logic.Hoare`.** From `Procedure.contractTriple p params From 1c2bc057f298accb4bc9c24f989e0561bfc18526 Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Thu, 29 Oct 2026 11:39:26 +0200 Subject: [PATCH 17/64] Lean path doc: correct rule names, counts, issue state and what lives where Co-Authored-By: Claude Fable 5.1 --- docs/ShallowEmbedding.md | 39 +++++++++++++++++++++------------------ 1 file changed, 21 insertions(+), 18 deletions(-) diff --git a/docs/ShallowEmbedding.md b/docs/ShallowEmbedding.md index 01a0c19..252f448 100644 --- a/docs/ShallowEmbedding.md +++ b/docs/ShallowEmbedding.md @@ -3,8 +3,9 @@ ## Goal Verify Boole programs in Lean with proofs that are sound by construction. Today's Lean -path trusts the VC generator, the SMT encoding and a bridge axiom, and strata-org/Strata#1488 -shows it can prove `False`. Here the trusted parts are Core's semantics and Lean, and the +path trusts the VC generator, the SMT encoding and a bridge axiom; strata-org/Strata#1488 +showed it could prove `False`, and strata-org/Strata#1490 closed that by refusing every +VC the denotation does not cover. Here the trusted parts are Core's semantics and Lean, and the goals range over Lean values, so Lean tactics work on them without a solver. Boole programs reach it through their lowering to Core. @@ -30,15 +31,16 @@ Core over Core's own operational semantics: - `Core.Logic.Hoare.Triple π params Pre ss Post`, quantified over every model of the program's uninterpreted symbols (`Lambda.Interp Core.Factory`). -- Proved rules for `cmd`, `set`, `init`, `seq`, `block`, `exit`, `ite`, `while_rule` - (partial correctness) and `call_of_contract`. +- Proved rules for `cmd`, `set`, `init`, `seq`, `block`, `exit_cons`, `ite`, `while_rule` + (partial correctness) and `Procedure.call_of_contract`. - `Procedure.contractTriple`, which reads `requires` and `ensures` as the triple to prove, - with `old` snapshots and typed parameters, and `SpecHoareConnection`, which relates the - triple to Strata's own notion of assertion validity. + with `old` snapshots and typed parameters, and the generic `SpecHoareConnection` + (`Strata/DL/Imperative/Logic/`), which relates a triple to Strata's own notion of + assertion validity. - Conditions are interpreted with `LExpr.denote`; statements evaluate expressions with `Expression.eval` over `Core.Factory`. -Its tests prove eleven procedures by applying the rules by hand, with `native_decide` +Its tests prove some twenty procedures by applying the rules by hand, with `native_decide` for facts about the AST. There is no automation and no lifting: a goal reads `Expression.eval ρ.factory ρ.store e = some v`, not `x ≥ y`. @@ -54,21 +56,22 @@ So the tactic below is ours to build, and the triple is a stable target. name`, apply the rules backwards statement by statement and discharge their side conditions (`InitEnvWF`, `PostWF`, `exitsCoveredByBlocks`) by evaluation on the concrete AST. The result is one goal per `assert`, loop invariant and `ensures`, over - the store. This is the shape of `core_vcgen` in `StrataBoole/Deep/` (branch - `exp/deep-embedding`), retargeted from its own `Exec` to Strata's `Triple`. + the store. This is the shape of `core_vcgen` in the `StrataBoole/Deep/` experiment (fork + branch `exp/deep-embedding`), retargeted from its own `Exec` to Strata's `Triple`. 2. **Lifting.** Turn each goal into a proposition over Lean values: a store slot of type `int` is an `Int` (`inputAsPredicate` gives the literal), `Expression.eval` of an - operator on literals is the Lean operation (`eval_intGe_value_of_numerals` and its - siblings exist; the missing operators are added), and a contract clause under + operator on literals is the Lean operation (one lemma per operator; Strata has none + yet, `Deep/` has a first set against its own semantics), and a contract clause under `denote` becomes the corresponding proposition. This is the shape of `core_lift`. Milestone: `max2`, then `find_max`, proved by the tactic, lifting, and `omega`/`grind`. -3. **Boole entry.** `shallow_reflect` already produces the type-checked Core program as a - Lean term; it is the input of step 1, so a user writes a `#strata program Boole` block +3. **Boole entry.** The interpreter prototype's `shallow_reflect` (fork branch, not merged) + already produces the type-checked Core program as a Lean term; it is the input of step 1, so a user writes a `#strata program Boole` block and states `contractTriple` on its procedures. 4. **Gaps shared with Strata, fixed in Strata.** Rules for nondeterministic `if` and `while` (today only the deterministic forms have rules); user-defined functions in the - model (Strata's own TODO); a denotation for datatypes, which is strata-org/Strata#1480 - and is also what makes Boole's `nat` provable. + model (Strata's own TODO); a denotation for datatypes, under review in Strata as its own PR, with their + translation to Lean in strata-org/Strata#1480; that is also what makes Boole's `nat` + provable. 5. **Boole semantics.** A Boole interpreter proved to agree with `toCoreProgram`, so Boole gets a semantics of its own. Needs `toCoreExpr` total and the `nat` library inside `typeCheck`, both merged (strata-org/Strata-Boole#25, #26). Later. @@ -91,15 +94,15 @@ So the tactic below is ours to build, and the triple is a stable target. | --- | --- | | assignments, `init`, `assert`, `assume`, `havoc` (as `set x *` through `cmd`), blocks, `exit`, deterministic `if` and `while`, `call` | rules exist | | `if *`, `while *`, loop measures, `cover` | to add | -| `int`, `bool`, `bv n`, `Map`, `Sequence` | denoted; lifting lemmas exist for `Int` comparisons, `+`, `*`, `not` | +| `int`, `bool`, `bv n`, `Map`, `Sequence` | denoted; lifting lemmas to add (step 2) | | user functions, datatypes, `nat` | step 4 | ## Status - Steps 1 and 2: not started against Strata's triple. `Deep/` has both against its own semantics, with `max2` and a counting loop proved. -- `StrataBoole/Shallow/Interpreter/` and `Layer.lean` are kept until the milestone is - reached; `shallow_reflect` stays for step 3. +- `StrataBoole/Shallow/Layer.lean` is kept until the milestone is reached. The interpreter + prototype stays on its fork branch; its `shallow_reflect` is what step 3 needs. - `StrataBooleTest/shallow_generic_datatypes.lean`: first prototype for step 4. ## Open questions From b5c88d6b494035851f6dae19c87122083bf60e8b Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Thu, 29 Oct 2026 20:19:24 +0200 Subject: [PATCH 18/64] Lean path doc: executable Core evaluator, step 5 conditional, risks, reuse of the concrete model Co-Authored-By: Claude Fable 5.1 --- docs/ShallowEmbedding.md | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/docs/ShallowEmbedding.md b/docs/ShallowEmbedding.md index 252f448..bd6623f 100644 --- a/docs/ShallowEmbedding.md +++ b/docs/ShallowEmbedding.md @@ -63,6 +63,8 @@ So the tactic below is ours to build, and the triple is a stable target. operator on literals is the Lean operation (one lemma per operator; Strata has none yet, `Deep/` has a first set against its own semantics), and a contract clause under `denote` becomes the corresponding proposition. This is the shape of `core_lift`. + The interpreter prototype's `Model.lean` and `Sort.lean`, a concrete interpretation of + Core's types and operators over `LExpr.denote`, is this layer and carries over. Milestone: `max2`, then `find_max`, proved by the tactic, lifting, and `omega`/`grind`. 3. **Boole entry.** The interpreter prototype's `shallow_reflect` (fork branch, not merged) already produces the type-checked Core program as a Lean term; it is the input of step 1, so a user writes a `#strata program Boole` block @@ -72,9 +74,12 @@ So the tactic below is ours to build, and the triple is a stable target. model (Strata's own TODO); a denotation for datatypes, under review in Strata as its own PR, with their translation to Lean in strata-org/Strata#1480; that is also what makes Boole's `nat` provable. -5. **Boole semantics.** A Boole interpreter proved to agree with `toCoreProgram`, so Boole - gets a semantics of its own. Needs `toCoreExpr` total and the `nat` library inside - `typeCheck`, both merged (strata-org/Strata-Boole#25, #26). Later. +5. **Boole semantics, if required.** Running programs is not a reason for an interpreter + of our own: Strata has an executable small-step evaluator for Core + (`Strata/Languages/Core/StatementEval.lean`). A Boole interpreter, proved to agree with + `toCoreProgram`, is needed only if Boole must have a semantics stated without Core. + Its prerequisites, `toCoreExpr` total and the `nat` library inside `typeCheck`, are + merged (strata-org/Strata-Boole#25, #26). Decide when steps 1 to 3 are done. ## Decisions @@ -87,6 +92,10 @@ So the tactic below is ours to build, and the triple is a stable target. `Std.Do`/`mvcgen` (`StrataBoole/Shallow/Layer.lean`) is off the path. - Failure is never vacuous: a construct the tactic cannot handle leaves the goal open instead of closing it. +- This is a deep embedding with shallow goals: the program stays data, and the Lean term + is the proof about it. The shallow part is what the user sees, goals over Lean values. + It was first discussed as a shallow embedding in the Velvet sense; say so when the + difference matters. ## Coverage of the rules @@ -104,6 +113,11 @@ So the tactic below is ours to build, and the triple is a stable target. - `StrataBoole/Shallow/Layer.lean` is kept until the milestone is reached. The interpreter prototype stays on its fork branch; its `shallow_reflect` is what step 3 needs. - `StrataBooleTest/shallow_generic_datatypes.lean`: first prototype for step 4. +- Risks. Strata's own hand proof of a two-branch `if` is some twenty-five lines with + `native_decide` and explicit store facts, so discharging the well-formedness, frame and + typing side conditions automatically is the bulk of step 1, not a detail. Two Strata + TODOs gate step 4: the model factory does not yet include user-defined functions, and + the typed-contract invariant is not yet a hypothesis of `contractTriple`. ## Open questions From 294b0c373da2d64e3c8dd83364e8b2ab6687561e Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Thu, 29 Oct 2026 20:19:50 +0200 Subject: [PATCH 19/64] Lean path doc: record the datatype decision shared with the SMT denotation Co-Authored-By: Claude Fable 5.1 --- docs/ShallowEmbedding.md | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/docs/ShallowEmbedding.md b/docs/ShallowEmbedding.md index bd6623f..9ea151d 100644 --- a/docs/ShallowEmbedding.md +++ b/docs/ShallowEmbedding.md @@ -92,6 +92,19 @@ So the tactic below is ours to build, and the triple is a stable target. `Std.Do`/`mvcgen` (`StrataBoole/Shallow/Layer.lean`) is off the path. - Failure is never vacuous: a construct the tactic cannot handle leaves the goal open instead of closing it. +- Datatypes get one generic model, written once, not one Lean inductive per program. The + carrier is a single inductive of constructor applications with a well-sortedness + predicate (`DT.Carrier` in `Strata/DL/SMT/DenoteDatatypes.lean`, the SMT denotation under + review in Strata); disjointness, injectivity, exhaustiveness and field typing are proved + once, and a program's datatypes are declarations the model reads, so the semantics has + no per-program step and nothing assumed. In the Hoare route the same carrier is the + interpretation of datatype sorts in the model that `Triple` quantifies over, which is + what discharges the datatype laws the Lambda denotation leaves as assumptions. `nat` + is this model's `pos`/`nat` with `toInt` by structural recursion. + strata-org/Strata#1480's per-program inductives (`#strata_datatypes`) serve the SMT-IR + Lean path and readability; they are not part of this route's semantics. Readable goals + (`pos.xO h` for `mk "xO" [h]`) are a presentation layer, added later with simp lemmas + and notation. - This is a deep embedding with shallow goals: the program stays data, and the Lean term is the proof about it. The shallow part is what the user sees, goals over Lean values. It was first discussed as a shallow embedding in the Velvet sense; say so when the @@ -104,7 +117,8 @@ So the tactic below is ours to build, and the triple is a stable target. | assignments, `init`, `assert`, `assume`, `havoc` (as `set x *` through `cmd`), blocks, `exit`, deterministic `if` and `while`, `call` | rules exist | | `if *`, `while *`, loop measures, `cover` | to add | | `int`, `bool`, `bv n`, `Map`, `Sequence` | denoted; lifting lemmas to add (step 2) | -| user functions, datatypes, `nat` | step 4 | +| datatypes, `nat` | generic carrier (decision above); wiring into the model is step 4 | +| user functions | step 4, Strata's TODO on the model factory | ## Status From ea78528d5d5fa8ff6a7791388728cfbc151be2a9 Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Thu, 29 Oct 2026 20:21:42 +0200 Subject: [PATCH 20/64] Lean path doc: remove repeated points Co-Authored-By: Claude Fable 5.1 --- docs/ShallowEmbedding.md | 65 +++++++++++++++++----------------------- 1 file changed, 28 insertions(+), 37 deletions(-) diff --git a/docs/ShallowEmbedding.md b/docs/ShallowEmbedding.md index 9ea151d..94628cd 100644 --- a/docs/ShallowEmbedding.md +++ b/docs/ShallowEmbedding.md @@ -60,20 +60,18 @@ So the tactic below is ours to build, and the triple is a stable target. branch `exp/deep-embedding`), retargeted from its own `Exec` to Strata's `Triple`. 2. **Lifting.** Turn each goal into a proposition over Lean values: a store slot of type `int` is an `Int` (`inputAsPredicate` gives the literal), `Expression.eval` of an - operator on literals is the Lean operation (one lemma per operator; Strata has none - yet, `Deep/` has a first set against its own semantics), and a contract clause under - `denote` becomes the corresponding proposition. This is the shape of `core_lift`. - The interpreter prototype's `Model.lean` and `Sort.lean`, a concrete interpretation of - Core's types and operators over `LExpr.denote`, is this layer and carries over. - Milestone: `max2`, then `find_max`, proved by the tactic, lifting, and `omega`/`grind`. -3. **Boole entry.** The interpreter prototype's `shallow_reflect` (fork branch, not merged) - already produces the type-checked Core program as a Lean term; it is the input of step 1, so a user writes a `#strata program Boole` block - and states `contractTriple` on its procedures. + operator on literals is the Lean operation (one lemma per operator, none in Strata yet), + and a contract clause under `denote` becomes the corresponding proposition. This is + the shape of `core_lift`. The interpreter prototype's `Model.lean` and `Sort.lean`, a + concrete interpretation of Core's types and operators over `LExpr.denote`, carry over + as this layer. Milestone: `max2`, then `find_max`, proved by the tactic, lifting, and + `omega`/`grind`. +3. **Boole entry.** The prototype's `shallow_reflect` (on its fork branch) already produces + the type-checked Core program as a Lean term. It is the input of step 1, so a user + writes a `#strata program Boole` block and states `contractTriple` on its procedures. 4. **Gaps shared with Strata, fixed in Strata.** Rules for nondeterministic `if` and - `while` (today only the deterministic forms have rules); user-defined functions in the - model (Strata's own TODO); a denotation for datatypes, under review in Strata as its own PR, with their - translation to Lean in strata-org/Strata#1480; that is also what makes Boole's `nat` - provable. + `while`; user-defined functions in the model; the generic datatype carrier wired into + the model (decision below), which also covers `nat`. 5. **Boole semantics, if required.** Running programs is not a reason for an interpreter of our own: Strata has an executable small-step evaluator for Core (`Strata/Languages/Core/StatementEval.lean`). A Boole interpreter, proved to agree with @@ -92,23 +90,18 @@ So the tactic below is ours to build, and the triple is a stable target. `Std.Do`/`mvcgen` (`StrataBoole/Shallow/Layer.lean`) is off the path. - Failure is never vacuous: a construct the tactic cannot handle leaves the goal open instead of closing it. -- Datatypes get one generic model, written once, not one Lean inductive per program. The - carrier is a single inductive of constructor applications with a well-sortedness - predicate (`DT.Carrier` in `Strata/DL/SMT/DenoteDatatypes.lean`, the SMT denotation under - review in Strata); disjointness, injectivity, exhaustiveness and field typing are proved - once, and a program's datatypes are declarations the model reads, so the semantics has - no per-program step and nothing assumed. In the Hoare route the same carrier is the - interpretation of datatype sorts in the model that `Triple` quantifies over, which is - what discharges the datatype laws the Lambda denotation leaves as assumptions. `nat` - is this model's `pos`/`nat` with `toInt` by structural recursion. - strata-org/Strata#1480's per-program inductives (`#strata_datatypes`) serve the SMT-IR - Lean path and readability; they are not part of this route's semantics. Readable goals - (`pos.xO h` for `mk "xO" [h]`) are a presentation layer, added later with simp lemmas - and notation. -- This is a deep embedding with shallow goals: the program stays data, and the Lean term - is the proof about it. The shallow part is what the user sees, goals over Lean values. - It was first discussed as a shallow embedding in the Velvet sense; say so when the - difference matters. +- Datatypes get one generic model, not one Lean inductive per program: a single inductive + of constructor applications with a well-sortedness predicate (`DT.Carrier` in + `Strata/DL/SMT/DenoteDatatypes.lean`, the SMT denotation under review in Strata). Its laws + are proved once, a program's datatypes are declarations the model reads, and `nat` is + its `pos`/`nat` with `toInt` by structural recursion. The same carrier interprets + datatype sorts in the model `Triple` quantifies over, which discharges the laws the + Lambda denotation leaves as assumptions. The per-program inductives of + strata-org/Strata#1480 serve the SMT-IR path; readable goals (`pos.xO h` for + `mk "xO" [h]`) are notation and simp lemmas added later. +- This is a deep embedding with shallow goals: the program stays data, the Lean term is + the proof about it, and what the user sees are goals over Lean values. It started as a + shallow embedding in the Velvet sense; say so when the difference matters. ## Coverage of the rules @@ -124,14 +117,12 @@ So the tactic below is ours to build, and the triple is a stable target. - Steps 1 and 2: not started against Strata's triple. `Deep/` has both against its own semantics, with `max2` and a counting loop proved. -- `StrataBoole/Shallow/Layer.lean` is kept until the milestone is reached. The interpreter - prototype stays on its fork branch; its `shallow_reflect` is what step 3 needs. -- `StrataBooleTest/shallow_generic_datatypes.lean`: first prototype for step 4. +- `StrataBoole/Shallow/Layer.lean` is kept until the milestone is reached. +- `StrataBooleTest/shallow_generic_datatypes.lean`: first prototype of the carrier. - Risks. Strata's own hand proof of a two-branch `if` is some twenty-five lines with - `native_decide` and explicit store facts, so discharging the well-formedness, frame and - typing side conditions automatically is the bulk of step 1, not a detail. Two Strata - TODOs gate step 4: the model factory does not yet include user-defined functions, and - the typed-contract invariant is not yet a hypothesis of `contractTriple`. + `native_decide` and explicit store facts, so discharging the side conditions + automatically is the bulk of step 1. Step 4 also waits on Strata carrying the + typed-contract invariant as a hypothesis of `contractTriple`. ## Open questions From 8d08f06d66b0f38f36e9acacba8b553dcc7cc345 Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Thu, 29 Oct 2026 20:22:13 +0200 Subject: [PATCH 21/64] Lean path doc: Boole semantics is a goal, after Core Co-Authored-By: Claude Fable 5.1 --- docs/ShallowEmbedding.md | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/docs/ShallowEmbedding.md b/docs/ShallowEmbedding.md index 94628cd..98178d1 100644 --- a/docs/ShallowEmbedding.md +++ b/docs/ShallowEmbedding.md @@ -72,20 +72,24 @@ So the tactic below is ours to build, and the triple is a stable target. 4. **Gaps shared with Strata, fixed in Strata.** Rules for nondeterministic `if` and `while`; user-defined functions in the model; the generic datatype carrier wired into the model (decision below), which also covers `nat`. -5. **Boole semantics, if required.** Running programs is not a reason for an interpreter - of our own: Strata has an executable small-step evaluator for Core - (`Strata/Languages/Core/StatementEval.lean`). A Boole interpreter, proved to agree with - `toCoreProgram`, is needed only if Boole must have a semantics stated without Core. - Its prerequisites, `toCoreExpr` total and the `nat` library inside `typeCheck`, are - merged (strata-org/Strata-Boole#25, #26). Decide when steps 1 to 3 are done. +5. **Boole semantics.** A Boole interpreter proved to agree with `toCoreProgram`, so that + Boole has a meaning stated in its own terms and the lowering to Core is proved correct + rather than definitional. This is what makes Boole a language rather than a front end. + It comes after steps 1 to 3 because the agreement theorem needs Core's semantics on the + other side. Its prerequisites, `toCoreExpr` total and the `nat` library inside + `typeCheck`, are merged (strata-org/Strata-Boole#25, #26). Running programs is not + what it is for: Strata already has an executable evaluator for Core + (`Strata/Languages/Core/StatementEval.lean`). ## Decisions - Build on `Core.Logic.Hoare`, not on a semantics of our own: neither `Deep/`'s `Exec`, which nothing connects to Core's semantics, nor an interpreter with an adequacy proof that would redo what Strata's rules already prove. -- Core first, then Boole. Starting from Boole directly would leave nothing to prove - adequacy against. +- Core first, then Boole. Boole is the language users write and the one this work is + about; Core is where the proved semantics lives today. Starting from Boole directly + would leave nothing to prove adequacy against, so the Boole semantics is step 5, not + step 1. - Goals over Lean values come from lifting, not from a monadic encoding, so `Std.Do`/`mvcgen` (`StrataBoole/Shallow/Layer.lean`) is off the path. - Failure is never vacuous: a construct the tactic cannot handle leaves the goal open From 92bfd6b7adee9a6f306ecc3e7ae9c236e7f9a3be Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Thu, 29 Oct 2026 22:09:47 +0200 Subject: [PATCH 22/64] Lean path doc: Velvet's monad as a candidate for the Boole interpreter Co-Authored-By: Claude Fable 5.1 --- docs/ShallowEmbedding.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/ShallowEmbedding.md b/docs/ShallowEmbedding.md index 98178d1..724d9e7 100644 --- a/docs/ShallowEmbedding.md +++ b/docs/ShallowEmbedding.md @@ -79,7 +79,9 @@ So the tactic below is ours to build, and the triple is a stable target. other side. Its prerequisites, `toCoreExpr` total and the `nat` library inside `typeCheck`, are merged (strata-org/Strata-Boole#25, #26). Running programs is not what it is for: Strata already has an executable evaluator for Core - (`Strata/Languages/Core/StatementEval.lean`). + (`Strata/Languages/Core/StatementEval.lean`). Open design choice: Velvet's + nondeterministic state monad, with its VC generator, is a candidate for the + interpreter now that Strata and Velvet share a Lean version. ## Decisions From 6a7ba1be66dc5e810ba7377fe64a1dd8d5cccb32 Mon Sep 17 00:00:00 2001 From: Abdalrhman M Mohamed Date: Thu, 29 Oct 2026 23:35:37 -0700 Subject: [PATCH 23/64] Hoare-logic route: name the doc and the datatype test for what they are The route this branch now takes keeps the program as data and proves contracts against Core's Hoare logic, so it is a deep embedding; only the Std.Do prototype in StrataBoole/Shallow/ and its test are shallow. Rename docs/ShallowEmbedding.md to docs/HoareLogic.md, and shallow_generic_datatypes.lean, the generic datatype carrier for the model, to generic_datatypes.lean. Mark the Std.Do layer as a prototype the route does not build on. Co-Authored-By: Claude Opus 5.5 --- StrataBoole.lean | 4 ++-- StrataBoole/Shallow/Layer.lean | 3 ++- StrataBooleTest.lean | 2 +- ...hallow_generic_datatypes.lean => generic_datatypes.lean} | 2 +- StrataBooleTest/shallow_find_max.lean | 2 +- docs/{ShallowEmbedding.md => HoareLogic.md} | 6 ++++-- 6 files changed, 11 insertions(+), 8 deletions(-) rename StrataBooleTest/{shallow_generic_datatypes.lean => generic_datatypes.lean} (98%) rename docs/{ShallowEmbedding.md => HoareLogic.md} (97%) diff --git a/StrataBoole.lean b/StrataBoole.lean index 4a4bf75..d4d445b 100644 --- a/StrataBoole.lean +++ b/StrataBoole.lean @@ -31,9 +31,9 @@ dialect of Strata. ### `import StrataBoole.Shallow.Layer` -The shallow embedding's layer on `Std.Do`: the `ND` monad with `havoc`, +A shallow-embedding prototype on `Std.Do`: the `ND` monad with `havoc`, `assume`, `assert` and `whileInv`, each with its `@[spec]` rule for `mvcgen`. -See `docs/ShallowEmbedding.md`. +The Hoare-logic route in `docs/HoareLogic.md` does not build on it. ### `import StrataBoole.MetaVerifier` diff --git a/StrataBoole/Shallow/Layer.lean b/StrataBoole/Shallow/Layer.lean index 860a340..1741e57 100644 --- a/StrataBoole/Shallow/Layer.lean +++ b/StrataBoole/Shallow/Layer.lean @@ -16,7 +16,8 @@ whose invariant is part of the program. Each construct comes with its proof rule (`@[spec]`), so `mvcgen` generates the verification conditions. The design follows Velvet (verse-lab/velvet); the code is ours and runs on the -Lean version Strata is on. See `docs/ShallowEmbedding.md`. +Lean version Strata is on. It is a prototype: the Hoare-logic route in +`docs/HoareLogic.md` does not build on it. -/ public section diff --git a/StrataBooleTest.lean b/StrataBooleTest.lean index 3c05129..650fdec 100644 --- a/StrataBooleTest.lean +++ b/StrataBooleTest.lean @@ -62,4 +62,4 @@ import StrataBooleTest.FeatureRequests.seq_empty_literal import StrataBooleTest.FeatureRequests.sha256_compact_indexed import StrataBooleTest.CoreTests.DefineFunRecTests import StrataBooleTest.shallow_find_max -import StrataBooleTest.shallow_generic_datatypes +import StrataBooleTest.generic_datatypes diff --git a/StrataBooleTest/shallow_generic_datatypes.lean b/StrataBooleTest/generic_datatypes.lean similarity index 98% rename from StrataBooleTest/shallow_generic_datatypes.lean rename to StrataBooleTest/generic_datatypes.lean index 6441aee..11e5d8a 100644 --- a/StrataBooleTest/shallow_generic_datatypes.lean +++ b/StrataBooleTest/generic_datatypes.lean @@ -13,7 +13,7 @@ proved once; induction is recursion on the term. `pos` and `nat` from Boole's `nat` library serve as the example. Not covered yet: `Map` fields keyed by a datatype (a negative occurrence) and -parametric datatypes. See `docs/ShallowEmbedding.md`. +parametric datatypes. See `docs/HoareLogic.md`. -/ mutual diff --git a/StrataBooleTest/shallow_find_max.lean b/StrataBooleTest/shallow_find_max.lean index c5fe678..d28238c 100644 --- a/StrataBooleTest/shallow_find_max.lean +++ b/StrataBooleTest/shallow_find_max.lean @@ -9,7 +9,7 @@ import StrataBoole.Shallow.Layer should produce, verified with `mvcgen` on the layer. This file is the contract between the translation and the layer. -/ --- Lean marks `mvcgen` experimental; see docs/ShallowEmbedding.md. +-- Lean marks `mvcgen` experimental; see docs/HoareLogic.md. set_option mvcgen.warning false namespace Strata.Shallow.Test diff --git a/docs/ShallowEmbedding.md b/docs/HoareLogic.md similarity index 97% rename from docs/ShallowEmbedding.md rename to docs/HoareLogic.md index 724d9e7..6017791 100644 --- a/docs/ShallowEmbedding.md +++ b/docs/HoareLogic.md @@ -107,7 +107,9 @@ So the tactic below is ours to build, and the triple is a stable target. `mk "xO" [h]`) are notation and simp lemmas added later. - This is a deep embedding with shallow goals: the program stays data, the Lean term is the proof about it, and what the user sees are goals over Lean values. It started as a - shallow embedding in the Velvet sense; say so when the difference matters. + shallow embedding in the Velvet sense; say so when the difference matters. The + `Shallow` names left in the tree (`StrataBoole/Shallow/`, `shallow_find_max`) are that + prototype's. ## Coverage of the rules @@ -124,7 +126,7 @@ So the tactic below is ours to build, and the triple is a stable target. - Steps 1 and 2: not started against Strata's triple. `Deep/` has both against its own semantics, with `max2` and a counting loop proved. - `StrataBoole/Shallow/Layer.lean` is kept until the milestone is reached. -- `StrataBooleTest/shallow_generic_datatypes.lean`: first prototype of the carrier. +- `StrataBooleTest/generic_datatypes.lean`: first prototype of the carrier. - Risks. Strata's own hand proof of a two-branch `if` is some twenty-five lines with `native_decide` and explicit store facts, so discharging the side conditions automatically is the bulk of step 1. Step 4 also waits on Strata carrying the From 47ea58d8676d8ebb917ffb2dce04eb1e8180dc71 Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Sun, 8 Nov 2026 16:55:22 +0100 Subject: [PATCH 24/64] Hoare-logic doc: record the evaluator vacuity on Map and Sequence statements Co-Authored-By: Claude Fable 5.1 --- docs/HoareLogic.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/docs/HoareLogic.md b/docs/HoareLogic.md index 6017791..32fd09e 100644 --- a/docs/HoareLogic.md +++ b/docs/HoareLogic.md @@ -131,6 +131,15 @@ So the tactic below is ours to build, and the triple is a stable target. `native_decide` and explicit store facts, so discharging the side conditions automatically is the bulk of step 1. Step 4 also waits on Strata carrying the typed-contract invariant as a hypothesis of `contractTriple`. +- Vacuity in the evaluator. `set` and `init` require `Expression.eval` to return a value, + and `evalFully` returns `none` for any full application of an operator without a + concrete evaluation, which includes `select`, `update` and the sequence and string + operators. A statement such as `x := m[0]` then has no execution, and its triple holds + for any postcondition. This affects every program over `Map` or `Sequence`, `find_max` + included, and must be fixed in Strata before step 2's milestone: either give those + operators an evaluation on their value forms, or interpret `set` and `init` through + `denote` as the conditions already are. Until then the tactic must refuse such + statements rather than prove them. ## Open questions @@ -138,6 +147,9 @@ So the tactic below is ours to build, and the triple is a stable target. check `decreases` separately? - `cover` is a reachability check, not a Hoare fact. How to state it? - Goal names: carry the program's clause names into the goals the tactic leaves. +- Evaluator vacuity (see Risks): evaluation rules for `Map` and `Sequence` operators, or + `set`/`init` through `denote`? The second keeps one interpretation for expressions + everywhere; the first keeps Strata's semantics unchanged. - `native_decide` for AST facts: acceptable in the tactic, or avoid it? ## Sources From 07451914715f7019e8e501c47d390292c87c75cb Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Sun, 8 Nov 2026 17:02:02 +0100 Subject: [PATCH 25/64] Hoare-logic doc: Map and Sequence are outside the logic until Strata gives them a model and value forms Co-Authored-By: Claude Fable 5.1 --- docs/HoareLogic.md | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/docs/HoareLogic.md b/docs/HoareLogic.md index 32fd09e..c4ca8b2 100644 --- a/docs/HoareLogic.md +++ b/docs/HoareLogic.md @@ -64,8 +64,8 @@ So the tactic below is ours to build, and the triple is a stable target. and a contract clause under `denote` becomes the corresponding proposition. This is the shape of `core_lift`. The interpreter prototype's `Model.lean` and `Sort.lean`, a concrete interpretation of Core's types and operators over `LExpr.denote`, carry over - as this layer. Milestone: `max2`, then `find_max`, proved by the tactic, lifting, and - `omega`/`grind`. + as this layer. Milestone: `max2`, then the counting loop of `demo.lean`, proved by the + tactic, lifting, and `omega`/`grind`; `find_max` once `Map` is in (see Risks). 3. **Boole entry.** The prototype's `shallow_reflect` (on its fork branch) already produces the type-checked Core program as a Lean term. It is the input of step 1, so a user writes a `#strata program Boole` block and states `contractTriple` on its procedures. @@ -117,7 +117,8 @@ So the tactic below is ours to build, and the triple is a stable target. | --- | --- | | assignments, `init`, `assert`, `assume`, `havoc` (as `set x *` through `cmd`), blocks, `exit`, deterministic `if` and `while`, `call` | rules exist | | `if *`, `while *`, loop measures, `cover` | to add | -| `int`, `bool`, `bv n`, `Map`, `Sequence` | denoted; lifting lemmas to add (step 2) | +| `int`, `bool`, `bv n` | denoted; lifting lemmas to add (step 2) | +| `Map`, `Sequence`, `string` operators | not usable yet: no value forms in the evaluator, and the triple quantifies over models that need not satisfy their axioms (see Risks) | | datatypes, `nat` | generic carrier (decision above); wiring into the model is step 4 | | user functions | step 4, Strata's TODO on the model factory | @@ -131,15 +132,20 @@ So the tactic below is ours to build, and the triple is a stable target. `native_decide` and explicit store facts, so discharging the side conditions automatically is the bulk of step 1. Step 4 also waits on Strata carrying the typed-contract invariant as a hypothesis of `contractTriple`. -- Vacuity in the evaluator. `set` and `init` require `Expression.eval` to return a value, - and `evalFully` returns `none` for any full application of an operator without a - concrete evaluation, which includes `select`, `update` and the sequence and string - operators. A statement such as `x := m[0]` then has no execution, and its triple holds - for any postcondition. This affects every program over `Map` or `Sequence`, `find_max` - included, and must be fixed in Strata before step 2's milestone: either give those - operators an evaluation on their value forms, or interpret `set` and `init` through - `denote` as the conditions already are. Until then the tactic must refuse such - statements rather than prove them. +- `Map` and `Sequence` are outside the Hoare logic today, for two reasons that both + need a Strata change. First, `set` and `init` require `Expression.eval` to return a + value, and `evalFully` returns `none` for a full application of an operator without a + concrete evaluation (`select`, `update`, the sequence and string operators), so + `x := m[0]` has no execution and its triple holds for any postcondition. Second, + `Triple` quantifies over every `Lambda.Interp`, which must agree with function bodies + and concrete evaluations but not with the factory axioms, so nothing about + `m[k := v][k]` is provable in any case. The fix is to give these operators a fixed + interpretation in the model (maps as functions, sequences as lists) together with + value forms for the evaluator, or to interpret `set` and `init` through `denote`. + `Strata/Languages/Core/ProgramEval.lean` already has the evaluation of `select` over + `update`/`mapConst` terms for the concrete interpreter. Until this lands the tactic + refuses such statements, and the milestone is an integer program with a loop + (`demo.lean`'s), not `find_max`. ## Open questions From 852f5183ef513dd6f2cde12529751e9e64d526ef Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Sun, 8 Nov 2026 17:25:22 +0100 Subject: [PATCH 26/64] Hoare-logic doc: what the dalek benchmark needs from the route, step by step Co-Authored-By: Claude Fable 5.1 --- docs/HoareLogic.md | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/docs/HoareLogic.md b/docs/HoareLogic.md index c4ca8b2..d74e66d 100644 --- a/docs/HoareLogic.md +++ b/docs/HoareLogic.md @@ -70,8 +70,10 @@ So the tactic below is ours to build, and the triple is a stable target. the type-checked Core program as a Lean term. It is the input of step 1, so a user writes a `#strata program Boole` block and states `contractTriple` on its procedures. 4. **Gaps shared with Strata, fixed in Strata.** Rules for nondeterministic `if` and - `while`; user-defined functions in the model; the generic datatype carrier wired into - the model (decision below), which also covers `nat`. + `while`; the program's own declarations in the model, that is its functions (with + bodies, recursive ones included), its uninterpreted functions and its axioms, which + `Triple` does not see today; the generic datatype carrier wired into the model + (decision below), which also covers `nat`; `Map` and `Sequence` (see Risks). 5. **Boole semantics.** A Boole interpreter proved to agree with `toCoreProgram`, so that Boole has a meaning stated in its own terms and the lowering to Core is proved correct rather than definitional. This is what makes Boole a language rather than a front end. @@ -122,6 +124,29 @@ So the tactic below is ours to build, and the triple is a stable target. | datatypes, `nat` | generic carrier (decision above); wiring into the model is step 4 | | user functions | step 4, Strata's TODO on the model factory | +## Target: the benchmark the solver path already verifies + +`StrataBooleTest/dalek_sum_of_slice.lean` (36 obligations, cvc5 and lean-smt) is the +program this route has to reach. What it uses, and where each item sits: + +| In the program | Needs | Step | +| --- | --- | --- | +| `for` loop with six invariants, `call` in the body, `exit` | rules exist; the tactic must discharge the loop and call side conditions | 1 | +| integer and `bv W8` arithmetic, `as_uint`, comparisons | lifting lemmas per operator | 2 | +| quantified `requires` and invariants | lifting of `denote` on quantifiers to Lean `∀` over `Int` | 2 | +| `Sequence (bv W8)` and `Sequence Scalar`, `select`, `length` | a model and value forms in Strata | 4 | +| native `nat`, the `nat_*` library | the generic carrier in the model, library functions as program functions | 4 | +| `function` definitions, one `rec function` with `requires` and `decreases`, `function f();` without body | program declarations in the model | 4 | +| `axiom` declarations, including the unfolding axiom of the recursive function | program axioms as hypotheses on the model | 4 | +| a callee whose body is `assume false` | `call_of_contract` with a trivially proved contract | 1 | + +The lifted goals must stay solver-friendly: lean-smt closes goals over `Int`, `Bool` and +`BitVec`, so sequences should lift to a length and an index function rather than to +`List`, and `nat` to `Nat`. Decide this with step 4; it does not affect steps 1 to 3. + +Order: `max2`, the counting loop, then this program as soon as step 4 lands in Strata. +Everything in steps 1 to 3 is exercised by the first two and reused unchanged by the third. + ## Status - Steps 1 and 2: not started against Strata's triple. `Deep/` has both against its own From a6d6e98b0af88f4f2c094ebcd8695c8c13cb9b27 Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Sun, 8 Nov 2026 18:17:05 +0100 Subject: [PATCH 27/64] Hoare-logic route: max2 proved against Core's triple, with the lifting lemmas StrataBooleTest/hoare_max2.lean states the Boole procedure max2, lowers it to Core inside Lean, and proves contractTriple for it by applying Core's Hoare rules: contractTriple_of_core_typed, block, block, ite, set. Side conditions are decided on the reflected program. StrataBoole/HoareLift.lean holds the lemmas that turn the rules' goals into goals over Lean values: the evaluator on Int.Ge over a store of integer literals, and the denotation of Int.Ge, Bool.And, Bool.Or and == on literals in every consistent model, each from the model's agreement with the operator's concrete evaluation. The proof is the specification of the step 1 tactic; docs/HoareLogic.md records it and what the hand proof settled. Co-Authored-By: Claude Fable 5.1 --- StrataBoole.lean | 1 + StrataBoole/HoareLift.lean | 428 ++++++++++++++++++++++++++++++++ StrataBooleTest.lean | 1 + StrataBooleTest/hoare_max2.lean | 241 ++++++++++++++++++ docs/HoareLogic.md | 15 +- 5 files changed, 685 insertions(+), 1 deletion(-) create mode 100644 StrataBoole/HoareLift.lean create mode 100644 StrataBooleTest/hoare_max2.lean diff --git a/StrataBoole.lean b/StrataBoole.lean index d4d445b..3386c4f 100644 --- a/StrataBoole.lean +++ b/StrataBoole.lean @@ -7,6 +7,7 @@ module public import StrataBoole.Boole public import StrataBoole.Verify +public import StrataBoole.HoareLift /-! ## Strata Boole Public Interface diff --git a/StrataBoole/HoareLift.lean b/StrataBoole/HoareLift.lean new file mode 100644 index 0000000..282a9c9 --- /dev/null +++ b/StrataBoole/HoareLift.lean @@ -0,0 +1,428 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +module + +public import Strata.Languages.Core.Logic.Hoare +public import Strata.Languages.Core.Logic.ContractToHoareTripleProps +public import Strata.Languages.Core.Logic.HoareCall +public import Strata.Languages.Core.Factory +import all Strata.DL.Lambda.LExprEval +import all Strata.DL.Lambda.LExprEvalProps +import all Strata.DL.Util.FuncAttr +import all Strata.DL.Lambda.FactoryProps +import all Strata.DL.Lambda.Factory +import all Strata.DL.Lambda.IntBoolFactory +import all Strata.Languages.Core.Factory +import all Strata.DL.Lambda.Denote.LExprDenote + +/-! # Lifting lemmas for the Hoare-logic route + +Facts about Core's evaluator on the operators a program uses, stated so that a +goal left by Core's Hoare rules (`Expression.eval ρ.store e = some v`) becomes a +proposition over Lean values. Step 2 of `docs/HoareLogic.md`. Each operator gets +one block like the `Int.Ge` one below. +-/ + +public section + +open Lambda Core + +namespace HoareLift + +abbrev E := Core.Expression.Expr + +/-! ## Literals and variables -/ + +theorem isValue_intConst (a : Int) : LExpr.isValue Core.Factory (LExpr.intConst () a : E) = true := + Lambda.isValue_const_true _ _ _ + +theorem eval_const (n : Nat) (env : Lambda.Env CoreLParams) (m : Unit) (κ : LConst) : + LExpr.eval n Core.Factory env (.const m κ) = (.const m κ, .value true) := by + cases n <;> simp [LExpr.eval, Lambda.isValue_const_true] + +/-- Core's expression metadata is `Unit`, so every metadata is `()`. -/ +theorem unit_metadata (e : E) : LExpr.metadata e = () := rfl + +theorem eval_intConst (n : Nat) (env : Lambda.Env CoreLParams) (a : Int) : + LExpr.eval n Core.Factory env (.intConst () a) = (.intConst () a, .value true) := + eval_const n env () _ + +theorem eval_boolConst (n : Nat) (env : Lambda.Env CoreLParams) (b : Bool) : + LExpr.eval n Core.Factory env (.boolConst () b) = (.boolConst () b, .value true) := + eval_const n env () _ + +theorem callOfLFunc_fvar_partial_none (x : Core.Expression.Ident) (ty : Option LMonoTy) : + Core.Factory.callOfLFunc (LExpr.fvar () x ty : E) (allowPartialApp := true) = none := by + simp [Factory.callOfLFunc, getLFuncCall, getLFuncCall.go] + +theorem isValue_fvar_false' (x : Core.Expression.Ident) (ty : Option LMonoTy) : + LExpr.isValue Core.Factory (LExpr.fvar () x ty : E) = false := by + rw [LExpr.isValue.eq_def] + split <;> (try (rename_i h; simp at h)) + split + · rename_i h; rw [callOfLFunc_fvar_partial_none] at h; cases h + · rfl + +/-- A variable bound to a value evaluates to it in one step. -/ +theorem eval_fvar_value (env : Lambda.Env CoreLParams) (x : Core.Expression.Ident) + (ty : Option LMonoTy) (v : E) (hx : env x = some v) (hv : LExpr.isValue Core.Factory v = true) : + LExpr.eval 1 Core.Factory env (.fvar () x ty) = (v, .value true) := by + show LExpr.eval (Nat.succ 0) Core.Factory env _ = _ + rw [LExpr.eval.eq_2 (TBase := CoreLParams), isValue_fvar_false'] + simp only [Bool.false_eq_true, ↓reduceIte] + rw [Lambda.callOfLFunc_fvar_none] + simp only [LExpr.evalCore, hx, hv, ↓reduceIte] + +/-! The empty attribute array answers every attribute query negatively. -/ + +theorem attr_findInlineIfConstr_empty : + Strata.DL.Util.FuncAttr.findInlineIfConstr (#[] : Array Strata.DL.Util.FuncAttr) = none := by + simp [Strata.DL.Util.FuncAttr.findInlineIfConstr] +theorem attr_findEvalIfConstr_empty : + Strata.DL.Util.FuncAttr.findEvalIfConstr (#[] : Array Strata.DL.Util.FuncAttr) = none := by + simp [Strata.DL.Util.FuncAttr.findEvalIfConstr] +theorem attr_findEvalIfValue_empty : + Strata.DL.Util.FuncAttr.findEvalIfValue (#[] : Array Strata.DL.Util.FuncAttr) = none := by + simp [Strata.DL.Util.FuncAttr.findEvalIfValue] +theorem attr_hasInlineIfAllValues_empty : + Strata.DL.Util.FuncAttr.hasInlineIfAllValues (#[] : Array Strata.DL.Util.FuncAttr) = false := by + simp [Strata.DL.Util.FuncAttr.hasInlineIfAllValues] +theorem attr_contains_inline_empty : + (#[] : Array Strata.DL.Util.FuncAttr).contains .inline = false := by simp + +/-! ## `Int.Ge` -/ + +/-- `Int.Ge a b`, as the lowering of `a >= b` writes it. -/ +def intGe (a b : E) : E := + .app () (.app () (.op () ⟨"Int.Ge", ()⟩ (some (.arrow .int (.arrow .int .bool)))) a) b + +set_option maxRecDepth 4000 in +theorem intGeFunc_mem : (Lambda.intGeFunc : WFLFunc CoreLParams) ∈ Core.WFFactoryArray := by + rw [Array.mem_def] + unfold Core.WFFactoryArray + simp only [Array.toList_appendList, List.mem_append, List.mem_cons, List.not_mem_nil, + or_false, true_or, or_true] + +theorem factory_get_intGe : + Core.Factory.get? "Int.Ge" = some (Lambda.intGeFunc : WFLFunc CoreLParams).func := by + have hmem : (Lambda.intGeFunc : WFLFunc CoreLParams).func ∈ Core.WFFactoryArray.map (·.func) := + Array.mem_map.mpr ⟨_, intGeFunc_mem, rfl⟩ + exact Lambda.Factory.get?_ofArray_of_mem hmem Core.WFFactoryArray_func_name_nodup + +theorem callOfLFunc_intGe (a b : E) (aPA : Bool) : + Core.Factory.callOfLFunc (intGe a b) (allowPartialApp := aPA) + = some (.op () ⟨"Int.Ge", ()⟩ (some (.arrow .int (.arrow .int .bool))), [a, b], + (Lambda.intGeFunc : WFLFunc CoreLParams).func) := by + have hget : Core.Factory[("Int.Ge" : String)]? = + some (Lambda.intGeFunc : WFLFunc CoreLParams).func := factory_get_intGe + simp [Factory.callOfLFunc, getLFuncCall, getLFuncCall.go, intGe, hget] + cases aPA <;> simp [Lambda.intGeFunc, Lambda.binaryOp] + +theorem isValue_intGe_false (a b : E) : LExpr.isValue Core.Factory (intGe a b) = false := by + rw [LExpr.isValue.eq_def] + split <;> (try (rename_i h; simp [intGe] at h)) + split + · rename_i h + rw [callOfLFunc_intGe] at h + simp only [Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨-, rfl, rfl⟩ := h + simp [Lambda.intGeFunc, Lambda.binaryOp] + · rfl + +theorem intGeFunc_attr : (Lambda.intGeFunc : WFLFunc CoreLParams).func.attr = #[] := by + simp [Lambda.intGeFunc, Lambda.binaryOp] +theorem intGeFunc_body : (Lambda.intGeFunc : WFLFunc CoreLParams).func.body = none := by + simp [Lambda.intGeFunc, Lambda.binaryOp] + +theorem shortCircuitCall_intGe (args : List E) : + LExpr.shortCircuitCall? (Lambda.intGeFunc : WFLFunc CoreLParams).func args = none := by + unfold LExpr.shortCircuitCall? + rw [intGeFunc_attr] + rfl + +/-- `Int.Ge` on two arguments that evaluate to integer literals in one step. -/ +theorem eval_intGe_args (env : Lambda.Env CoreLParams) (a' b' : E) (a b : Int) + (ha : LExpr.eval 1 Core.Factory env a' = (.intConst () a, .value true)) + (hb : LExpr.eval 1 Core.Factory env b' = (.intConst () b, .value true)) : + LExpr.eval 2 Core.Factory env (intGe a' b') = (.boolConst () (decide (a ≥ b)), .value true) := by + show LExpr.eval (Nat.succ 1) Core.Factory env _ = _ + rw [LExpr.eval.eq_2 (TBase := CoreLParams), isValue_intGe_false] + simp only [Bool.false_eq_true, ↓reduceIte] + rw [callOfLFunc_intGe] + dsimp only + rw [shortCircuitCall_intGe] + simp only [List.map_cons, List.map_nil, ha, hb, intGeFunc_body, intGeFunc_attr, + Option.isSome_none, Bool.false_and, Bool.false_or, Bool.false_eq_true, ↓reduceDIte, + attr_findInlineIfConstr_empty, attr_findEvalIfConstr_empty, attr_findEvalIfValue_empty, + attr_hasInlineIfAllValues_empty, attr_contains_inline_empty, + List.all_cons, List.all_nil, Lambda.isValue_const_true, Bool.and_true, Bool.true_and, + Bool.true_or, Bool.or_false, ↓reduceIte, unit_metadata, + Lambda.intGeFunc, Lambda.binaryOp, LambdaLeanType.cevalTy, LambdaLeanType.mkConst, + LExpr.denoteInt, LExpr.intConst, LExpr.boolConst, + eval_const, LExpr.combineEvalResValueFlag_eq_pair, + LExpr.EvalResult.isValueTrue, LExpr.EvalResult.combineValueFlag, Bool.and_self] + +/-- The lifting lemma the `if` rule needs: `x >= y` in a store binding `x` and `y` to + integer literals evaluates to the Boolean literal `a ≥ b`. -/ +theorem evalFully_intGe_store (env : Lambda.Env CoreLParams) (x y : Core.Expression.Ident) + (tx ty : Option LMonoTy) (a b : Int) + (hx : env x = some (.intConst () a)) (hy : env y = some (.intConst () b)) : + LExpr.evalFully Core.Factory env (intGe (.fvar () x tx) (.fvar () y ty)) + = some (.boolConst () (decide (a ≥ b))) := + Lambda.evalFully_of_value_true Core.Factory env _ 2 _ + (eval_intGe_args env _ _ a b + (eval_fvar_value env x tx _ hx (isValue_intConst a)) + (eval_fvar_value env y ty _ hy (isValue_intConst b))) + +/-! ## `Int.Ge` under any consistent model + +The denotation half of the lifting: in every `Lambda.Interp Core.Factory`, the operator +applied to two integer literals denotes the Boolean the evaluator computes, because the +model agrees with the operator's concrete evaluation. -/ + +theorem intGe_mem_factory : "Int.Ge" ∈ Core.Factory := + Lambda.Factory.getElem?_some_implies_mem factory_get_intGe + +theorem factory_getElem_intGe : + Core.Factory["Int.Ge"]'intGe_mem_factory = (Lambda.intGeFunc : WFLFunc CoreLParams).func := + Lambda.Factory.getElem?_some_getElem factory_get_intGe + +/-- `denote_intConst` with the type spelled as the lowering annotates it. -/ +theorem denote_intConst' (tcInterp : TyConstrInterp) (opInterp : OpInterp tcInterp) + (fv : FreeVarVal CoreLParams tcInterp) (vt : TyVarVal) {m : Unit} {i : Int} + (h : LExpr.HasTypeA [] (LExpr.intConst m i : E) LMonoTy.int) : + LExpr.denote tcInterp opInterp fv vt .nil (LExpr.intConst m i) LMonoTy.int h = i := + denote_intConst tcInterp opInterp fv vt .nil h + +theorem hasTypeA_intGe_consts (c a : Int) : + LExpr.HasTypeA [] (intGe (.intConst () c) (.intConst () a)) .bool := + .app (.app .op .const) .const + +theorem denote_intGe_consts (I : Lambda.Interp Core.Factory) + (fv : FreeVarVal CoreLParams I.tcInterp) (vt : TyVarVal) (c a : Int) + (h : LExpr.HasTypeA [] (intGe (.intConst () c) (.intConst () a)) .bool) : + LExpr.denote I.tcInterp I.opInterp fv vt .nil (intGe (.intConst () c) (.intConst () a)) .bool h + = decide (c ≥ a) := by + have hic := I.interpConsistent + unfold Lambda.Factory.InterpConsistent at hic + have hcons := hic.2 "Int.Ge" intGe_mem_factory + rw [factory_getElem_intGe] at hcons + cases hce : (Lambda.intGeFunc : WFLFunc CoreLParams).func.concreteEval with + | none => simp [Lambda.intGeFunc, Lambda.binaryOp] at hce + | some ceval => + have happ : ceval () [.intConst () c, .intConst () a] = some (.boolConst () (decide (c ≥ a))) := by + simp [Lambda.intGeFunc, Lambda.binaryOp] at hce + subst hce + simp [LambdaLeanType.cevalTy, LambdaLeanType.mkConst, LExpr.denoteInt, LExpr.boolConst] + have hspec := hcons ceval hce vt fv () Subst.empty [.intConst () c, .intConst () a] + (.boolConst () (decide (c ≥ a))) happ + have hs := hspec (.cons .const (.cons .const .nil)) .const + have hc : LExpr.HasTypeA [] (LExpr.intConst () c : E) (.tcons "int" []) := .const + have ha : LExpr.HasTypeA [] (LExpr.intConst () a : E) (.tcons "int" []) := .const + have hop : LExpr.HasTypeA [] + (LExpr.op () ⟨"Int.Ge", ()⟩ (some (.arrow .int (.arrow .int .bool))) : E) + (.arrow .int (.arrow .int .bool)) := .op + have hfn : LExpr.HasTypeA [] + (LExpr.app () (LExpr.op () ⟨"Int.Ge", ()⟩ (some (.arrow .int (.arrow .int .bool)))) + (LExpr.intConst () c) : E) (.arrow .int .bool) := .app hop hc + revert h + unfold intGe + intro h + rw [denote_app (h_fn := hfn) (h_arg := ha), denote_app (h_fn := hop) (h_arg := hc), + denote_op] + first + | exact hs.symm + | (simp only [denote_intConst'] ; exact hs.symm) + +/-! ## `Bool.And`, `Bool.Or` and `==` on literals, under any consistent model -/ + +set_option maxRecDepth 4000 in +theorem boolAndFunc_mem : (Lambda.boolAndFunc : WFLFunc CoreLParams) ∈ Core.WFFactoryArray := by + rw [Array.mem_def] + unfold Core.WFFactoryArray + simp only [Array.toList_appendList, List.mem_append, List.mem_cons, List.not_mem_nil, + or_false, true_or, or_true] + +set_option maxRecDepth 4000 in +theorem boolOrFunc_mem : (Lambda.boolOrFunc : WFLFunc CoreLParams) ∈ Core.WFFactoryArray := by + rw [Array.mem_def] + unfold Core.WFFactoryArray + simp only [Array.toList_appendList, List.mem_append, List.mem_cons, List.not_mem_nil, + or_false, true_or, or_true] + +theorem factory_get_of_mem (wf : WFLFunc CoreLParams) (h : wf ∈ Core.WFFactoryArray) : + Core.Factory.get? wf.func.name.name = some wf.func := + Lambda.Factory.get?_ofArray_of_mem (Array.mem_map.mpr ⟨_, h, rfl⟩) + Core.WFFactoryArray_func_name_nodup + +theorem factory_get_boolAnd : + Core.Factory.get? "Bool.And" = some (Lambda.boolAndFunc : WFLFunc CoreLParams).func := + factory_get_of_mem _ boolAndFunc_mem +theorem factory_get_boolOr : + Core.Factory.get? "Bool.Or" = some (Lambda.boolOrFunc : WFLFunc CoreLParams).func := + factory_get_of_mem _ boolOrFunc_mem + +/-- The denotation of a short-circuit Boolean operator on two Boolean literals: the + model agrees with the operator's concrete evaluation, which decides the result from + the first literal or returns the second. Shared by `Bool.And` and `Bool.Or`. -/ +theorem denote_shortCircuit_consts (I : Lambda.Interp Core.Factory) + (fv : FreeVarVal CoreLParams I.tcInterp) (vt : TyVarVal) + (name : String) (absorb decided : Bool) + (hget : Core.Factory.get? name + = some (Lambda.shortCircuitOp (T := CoreLParams) ⟨name, ()⟩ absorb decided).func) + (p q : Bool) + (h : LExpr.HasTypeA [] + (.app () (.app () (.op () ⟨name, ()⟩ (some (.arrow .bool (.arrow .bool .bool)))) + (.boolConst () p)) (.boolConst () q) : E) .bool) : + LExpr.denote I.tcInterp I.opInterp fv vt .nil + (.app () (.app () (.op () ⟨name, ()⟩ (some (.arrow .bool (.arrow .bool .bool)))) + (.boolConst () p)) (.boolConst () q)) .bool h + = (if p == absorb then decided else q) := by + have hmem : name ∈ Core.Factory := Lambda.Factory.getElem?_some_implies_mem hget + have hic := I.interpConsistent + unfold Lambda.Factory.InterpConsistent at hic + have hcons := hic.2 name hmem + rw [Lambda.Factory.getElem?_some_getElem hget] at hcons + cases hceq : (Lambda.shortCircuitOp (T := CoreLParams) ⟨name, ()⟩ absorb decided).func.concreteEval with + | none => simp [Lambda.shortCircuitOp] at hceq + | some ceval => + have happ : ceval () [.boolConst () p, .boolConst () q] + = some (.boolConst () (if p == absorb then decided else q)) := by + simp [Lambda.shortCircuitOp] at hceq + subst hceq + cases p <;> cases absorb <;> + simp [LambdaLeanType.cevalTy, LambdaLeanType.mkConst, LExpr.denoteBool, LExpr.boolConst] + have hspec := hcons ceval hceq vt fv () Subst.empty [.boolConst () p, .boolConst () q] + (.boolConst () (if p == absorb then decided else q)) happ + have hs := hspec (.cons .const (.cons .const .nil)) .const + have hp : LExpr.HasTypeA [] (LExpr.boolConst () p : E) (.tcons "bool" []) := .const + have hq : LExpr.HasTypeA [] (LExpr.boolConst () q : E) (.tcons "bool" []) := .const + have hop : LExpr.HasTypeA [] + (LExpr.op () ⟨name, ()⟩ (some (.arrow .bool (.arrow .bool .bool))) : E) + (.arrow .bool (.arrow .bool .bool)) := .op + have hfn : LExpr.HasTypeA [] + (LExpr.app () (LExpr.op () ⟨name, ()⟩ (some (.arrow .bool (.arrow .bool .bool)))) + (LExpr.boolConst () p) : E) (.arrow .bool .bool) := .app hop hp + rw [denote_app (h_fn := hfn) (h_arg := hq), denote_app (h_fn := hop) (h_arg := hp), + denote_op] + exact hs.symm + +theorem denote_boolAnd_consts (I : Lambda.Interp Core.Factory) + (fv : FreeVarVal CoreLParams I.tcInterp) (vt : TyVarVal) (p q : Bool) + (h : LExpr.HasTypeA [] + (.app () (.app () (.op () ⟨"Bool.And", ()⟩ (some (.arrow .bool (.arrow .bool .bool)))) + (.boolConst () p)) (.boolConst () q) : E) .bool) : + LExpr.denote I.tcInterp I.opInterp fv vt .nil + (.app () (.app () (.op () ⟨"Bool.And", ()⟩ (some (.arrow .bool (.arrow .bool .bool)))) + (.boolConst () p)) (.boolConst () q)) .bool h = (p && q) := by + rw [denote_shortCircuit_consts I fv vt "Bool.And" false false factory_get_boolAnd p q h] + cases p <;> (try simp) <;> (try rfl) + +theorem denote_boolOr_consts (I : Lambda.Interp Core.Factory) + (fv : FreeVarVal CoreLParams I.tcInterp) (vt : TyVarVal) (p q : Bool) + (h : LExpr.HasTypeA [] + (.app () (.app () (.op () ⟨"Bool.Or", ()⟩ (some (.arrow .bool (.arrow .bool .bool)))) + (.boolConst () p)) (.boolConst () q) : E) .bool) : + LExpr.denote I.tcInterp I.opInterp fv vt .nil + (.app () (.app () (.op () ⟨"Bool.Or", ()⟩ (some (.arrow .bool (.arrow .bool .bool)))) + (.boolConst () p)) (.boolConst () q)) .bool h = (p || q) := by + rw [denote_shortCircuit_consts I fv vt "Bool.Or" true true factory_get_boolOr p q h] + cases p <;> (try simp) <;> (try rfl) + +/-- `Bool.And` on any two Boolean expressions: the operator denotes `&&`. The literal case + carries the model fact; the general case follows because the denotation of a literal + is, definitionally, its value. -/ +theorem denote_boolAnd (I : Lambda.Interp Core.Factory) + (fv : FreeVarVal CoreLParams I.tcInterp) (vt : TyVarVal) (e1 e2 : E) + (h1 : LExpr.HasTypeA [] e1 .bool) (h2 : LExpr.HasTypeA [] e2 .bool) + (h : LExpr.HasTypeA [] + (.app () (.app () (.op () ⟨"Bool.And", ()⟩ (some (.arrow .bool (.arrow .bool .bool)))) e1) e2) + .bool) : + LExpr.denote I.tcInterp I.opInterp fv vt .nil + (.app () (.app () (.op () ⟨"Bool.And", ()⟩ (some (.arrow .bool (.arrow .bool .bool)))) e1) e2) + .bool h + = (LExpr.denote I.tcInterp I.opInterp fv vt .nil e1 .bool h1 && + LExpr.denote I.tcInterp I.opInterp fv vt .nil e2 .bool h2) := by + have hop : LExpr.HasTypeA [] + (LExpr.op () ⟨"Bool.And", ()⟩ (some (.arrow .bool (.arrow .bool .bool))) : E) + (.arrow .bool (.arrow .bool .bool)) := .op + have hfn : LExpr.HasTypeA [] + (LExpr.app () (LExpr.op () ⟨"Bool.And", ()⟩ (some (.arrow .bool (.arrow .bool .bool)))) e1 : E) + (.arrow .bool .bool) := .app hop h1 + have hp : LExpr.HasTypeA [] + (LExpr.boolConst () (LExpr.denote I.tcInterp I.opInterp fv vt .nil e1 .bool h1) : E) + (.tcons "bool" []) := .const + have hq : LExpr.HasTypeA [] + (LExpr.boolConst () (LExpr.denote I.tcInterp I.opInterp fv vt .nil e2 .bool h2) : E) + (.tcons "bool" []) := .const + have hfnL : LExpr.HasTypeA [] + (LExpr.app () (LExpr.op () ⟨"Bool.And", ()⟩ (some (.arrow .bool (.arrow .bool .bool)))) + (LExpr.boolConst () (LExpr.denote I.tcInterp I.opInterp fv vt .nil e1 .bool h1)) : E) + (.arrow .bool .bool) := .app hop hp + have hlit := denote_boolAnd_consts I fv vt + (LExpr.denote I.tcInterp I.opInterp fv vt .nil e1 .bool h1) + (LExpr.denote I.tcInterp I.opInterp fv vt .nil e2 .bool h2) (.app hfnL hq) + rw [denote_app (h_fn := hfnL) (h_arg := hq), denote_app (h_fn := hop) (h_arg := hp), + denote_op] at hlit + rw [denote_app (h_fn := hfn) (h_arg := h2), denote_app (h_fn := hop) (h_arg := h1), denote_op] + exact hlit + +theorem denote_boolOr (I : Lambda.Interp Core.Factory) + (fv : FreeVarVal CoreLParams I.tcInterp) (vt : TyVarVal) (e1 e2 : E) + (h1 : LExpr.HasTypeA [] e1 .bool) (h2 : LExpr.HasTypeA [] e2 .bool) + (h : LExpr.HasTypeA [] + (.app () (.app () (.op () ⟨"Bool.Or", ()⟩ (some (.arrow .bool (.arrow .bool .bool)))) e1) e2) + .bool) : + LExpr.denote I.tcInterp I.opInterp fv vt .nil + (.app () (.app () (.op () ⟨"Bool.Or", ()⟩ (some (.arrow .bool (.arrow .bool .bool)))) e1) e2) + .bool h + = (LExpr.denote I.tcInterp I.opInterp fv vt .nil e1 .bool h1 || + LExpr.denote I.tcInterp I.opInterp fv vt .nil e2 .bool h2) := by + have hop : LExpr.HasTypeA [] + (LExpr.op () ⟨"Bool.Or", ()⟩ (some (.arrow .bool (.arrow .bool .bool))) : E) + (.arrow .bool (.arrow .bool .bool)) := .op + have hfn : LExpr.HasTypeA [] + (LExpr.app () (LExpr.op () ⟨"Bool.Or", ()⟩ (some (.arrow .bool (.arrow .bool .bool)))) e1 : E) + (.arrow .bool .bool) := .app hop h1 + have hp : LExpr.HasTypeA [] + (LExpr.boolConst () (LExpr.denote I.tcInterp I.opInterp fv vt .nil e1 .bool h1) : E) + (.tcons "bool" []) := .const + have hq : LExpr.HasTypeA [] + (LExpr.boolConst () (LExpr.denote I.tcInterp I.opInterp fv vt .nil e2 .bool h2) : E) + (.tcons "bool" []) := .const + have hfnL : LExpr.HasTypeA [] + (LExpr.app () (LExpr.op () ⟨"Bool.Or", ()⟩ (some (.arrow .bool (.arrow .bool .bool)))) + (LExpr.boolConst () (LExpr.denote I.tcInterp I.opInterp fv vt .nil e1 .bool h1)) : E) + (.arrow .bool .bool) := .app hop hp + have hlit := denote_boolOr_consts I fv vt + (LExpr.denote I.tcInterp I.opInterp fv vt .nil e1 .bool h1) + (LExpr.denote I.tcInterp I.opInterp fv vt .nil e2 .bool h2) (.app hfnL hq) + rw [denote_app (h_fn := hfnL) (h_arg := hq), denote_app (h_fn := hop) (h_arg := hp), + denote_op] at hlit + rw [denote_app (h_fn := hfn) (h_arg := h2), denote_app (h_fn := hop) (h_arg := h1), denote_op] + exact hlit + +/-- `==` on two integer literals denotes their equality. -/ +theorem denote_eq_ints (I : Lambda.Interp Core.Factory) + (fv : FreeVarVal CoreLParams I.tcInterp) (vt : TyVarVal) (c a : Int) + (h : LExpr.HasTypeA [] (.eq () (LExpr.intConst () c) (LExpr.intConst () a) : E) .bool) : + LExpr.denote I.tcInterp I.opInterp fv vt .nil + (.eq () (LExpr.intConst () c) (LExpr.intConst () a)) .bool h = decide (c = a) := by + have hc : LExpr.HasTypeA [] (LExpr.intConst () c : E) LMonoTy.int := .const + have ha : LExpr.HasTypeA [] (LExpr.intConst () a : E) LMonoTy.int := .const + by_cases hca : c = a + · subst hca + rw [denote_eq_true _ hc ha h rfl] + show (true : Bool) = decide (c = c) + simp + · rw [denote_eq_false _ hc ha h (by rw [denote_intConst', denote_intConst']; exact hca)] + show (false : Bool) = decide (c = a) + simp [hca] + +end HoareLift + + +end -- public section diff --git a/StrataBooleTest.lean b/StrataBooleTest.lean index 650fdec..c6744bd 100644 --- a/StrataBooleTest.lean +++ b/StrataBooleTest.lean @@ -62,4 +62,5 @@ import StrataBooleTest.FeatureRequests.seq_empty_literal import StrataBooleTest.FeatureRequests.sha256_compact_indexed import StrataBooleTest.CoreTests.DefineFunRecTests import StrataBooleTest.shallow_find_max +import StrataBooleTest.hoare_max2 import StrataBooleTest.generic_datatypes diff --git a/StrataBooleTest/hoare_max2.lean b/StrataBooleTest/hoare_max2.lean new file mode 100644 index 0000000..1c0cc2b --- /dev/null +++ b/StrataBooleTest/hoare_max2.lean @@ -0,0 +1,241 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.HoareLift +import StrataBoole.MetaVerifier + +/-! # `max2` against Core's Hoare logic, by hand + +The first procedure proved on the Lean route of `docs/HoareLogic.md`. Everything the +tactic of step 1 will automate is written out once here; the lifting lemmas it uses +are in `StrataBoole.HoareLift`. +-/ + +open Strata Lambda Core HoareLift + +namespace HoareMax2 + +/-! ## The program -/ + +def max2Pgm : StrataDDM.Program := +#strata +program Boole; +procedure max2 (x: int, y: int) returns (r: int) +spec { + ensures r >= x && r >= y; + ensures r == x || r == y; +} +{ + if (x >= y) { r := x; } else { r := y; } +}; +#end + +/-- The type-checked Core program the Boole block lowers to. -/ +def max2Core : Core.Program := + match Strata.Boole.typeCheck max2Pgm with + | .ok p => p + | .error _ => default + +def max2Proc : Core.Procedure := (max2Core.findProcByString? "max2").get! + +theorem max2_findProc : max2Core.findProcByString? "max2" = some max2Proc := by native_decide + +def intTy : Option LMonoTy := some (.tcons "int" []) +def xV : Core.Expression.Ident := ⟨"x", ()⟩ +def yV : Core.Expression.Ident := ⟨"y", ()⟩ +def rV : Core.Expression.Ident := ⟨"r", ()⟩ + +/-- Metadata of the statements, read off the program so the shapes below are exact. -/ +def max2Body : Core.Statements := + match max2Proc.body with | .structured ss => ss | _ => [] + +def md4 : Imperative.MetaData Core.Expression := + match max2Body with | [.block _ _ md] => md | _ => #[] +def md3 : Imperative.MetaData Core.Expression := + match max2Body with | [.block _ [.ite _ _ _ md] _] => md | _ => #[] +def md1 : Imperative.MetaData Core.Expression := + match max2Body with | [.block _ [.ite _ [.cmd (.cmd (.set _ _ md))] _ _] _] => md | _ => #[] +def md2 : Imperative.MetaData Core.Expression := + match max2Body with | [.block _ [.ite _ _ [.cmd (.cmd (.set _ _ md))] _] _] => md | _ => #[] + +theorem max2_body_eq : max2Proc.body = .structured + [.block "max2" + [.ite (.det (intGe (.fvar () xV intTy) (.fvar () yV intTy))) + [.cmd (.cmd (.set rV (.det (.fvar () xV intTy)) md1))] + [.cmd (.cmd (.set rV (.det (.fvar () yV intTy)) md2))] md3] md4] := by + native_decide + +/-! ## The contract as a triple -/ + +/-- Gate parameters: no reserved prefixes, every operator counts as declared. -/ +def params : Core.Logic.InitEnvWFParams := ⟨[], fun _ => true⟩ + +theorem max2_checksTyped : Core.Logic.Hoare.Procedure.contractChecksTyped max2Proc := by + native_decide + +theorem max2_inputs : max2Proc.header.inputs.toList = [(xV, .tcons "int" []), (yV, .tcons "int" [])] := by + native_decide + +/-- `Bool.And a b` and `Bool.Or a b` as the lowering writes `a && b` and `a || b`. -/ +abbrev andE (a b : E) : E := + .app () (.app () (.op () ⟨"Bool.And", ()⟩ (some (.arrow .bool (.arrow .bool .bool)))) a) b +abbrev orE (a b : E) : E := + .app () (.app () (.op () ⟨"Bool.Or", ()⟩ (some (.arrow .bool (.arrow .bool .bool)))) a) b + +/-- The clause labels carry source offsets, so they are read off the program too. -/ +def lbl0 : Core.CoreLabel := + match max2Proc.spec.postconditions.toList with | (l, _) :: _ => l | _ => "" +def lbl1 : Core.CoreLabel := + match max2Proc.spec.postconditions.toList with | _ :: (l, _) :: _ => l | _ => "" + +def mdP0 : Imperative.MetaData Core.Expression := + match max2Proc.spec.postconditions.toList with | (_, c) :: _ => c.md | _ => #[] +def mdP1 : Imperative.MetaData Core.Expression := + match max2Proc.spec.postconditions.toList with | _ :: (_, c) :: _ => c.md | _ => #[] + +theorem max2_posts : max2Proc.spec.postconditions.toList = + [(lbl0, + { expr := andE (intGe (.fvar () rV intTy) (.fvar () xV intTy)) + (intGe (.fvar () rV intTy) (.fvar () yV intTy)), + attr := .Default, md := mdP0 }), + (lbl1, + { expr := orE (.eq () (.fvar () rV intTy) (.fvar () xV intTy)) + (.eq () (.fvar () rV intTy) (.fvar () yV intTy)), + attr := .Default, md := mdP1 })] := by + native_decide + +/-- A clause holds in every world once its captured form is a closed expression that + denotes `true` under every valuation. -/ +theorem check_of_captured (model : Lambda.Interp Core.Factory) + (ρ : Imperative.Env Core.Expression) (label : Core.CoreLabel) (check : Core.Procedure.Check) + (e : E) (hfac : ρ.factory = Core.Factory) + (hcap : Core.Logic.capturedExpr + { factory := ρ.factory, store := ρ.store, label := label, + expr := check.expr, metadata := check.md } = e) + (ht : LExpr.HasTypeA [] e .bool) + (hd : ∀ (fv : FreeVarVal CoreLParams model.tcInterp) (vt : TyVarVal), + LExpr.denote model.tcInterp model.opInterp fv vt .nil e .bool ht = true) : + Core.Logic.Hoare.Procedure.checkAsPredicate model ρ label check := by + intro world + refine Or.inl ⟨hfac, ?_⟩ + rw [hcap] + exact ⟨ht, hd _ _⟩ + +/-- The two `ensures` clauses, read in every world of `model`, once the store binds the + three variables to integer literals satisfying them. -/ +theorem max2_post (model : Lambda.Interp Core.Factory) (ρ : Imperative.Env Core.Expression) + (a b c : Int) (hfac : ρ.factory = Core.Factory) + (hx : ρ.store xV = some (.intConst () a)) (hy : ρ.store yV = some (.intConst () b)) + (hr : ρ.store rV = some (.intConst () c)) + (h1 : c ≥ a) (h2 : c ≥ b) (h3 : c = a ∨ c = b) : + Core.Logic.Hoare.Procedure.contractPost model max2Proc ρ := by + intro label check hmem _ + rw [max2_posts] at hmem + simp only [List.mem_cons, List.not_mem_nil, or_false, Prod.mk.injEq] at hmem + have hc : LExpr.HasTypeA [] (LExpr.intConst () c : E) LMonoTy.int := .const + have ha : LExpr.HasTypeA [] (LExpr.intConst () a : E) LMonoTy.int := .const + have hb : LExpr.HasTypeA [] (LExpr.intConst () b : E) LMonoTy.int := .const + rcases hmem with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩ + · refine check_of_captured model ρ _ _ + (andE (intGe (.intConst () c) (.intConst () a)) (intGe (.intConst () c) (.intConst () b))) + hfac ?_ (.app (.app .op (hasTypeA_intGe_consts c a)) (hasTypeA_intGe_consts c b)) ?_ + · simp [Core.Logic.capturedExpr, LExpr.substFvarsFromEnv, Lambda.Env.mk, hx, hy, hr, intGe] + · intro fv vt + rw [denote_boolAnd _ _ _ _ _ (hasTypeA_intGe_consts c a) (hasTypeA_intGe_consts c b), + denote_intGe_consts, denote_intGe_consts] + show (decide (c ≥ a) && decide (c ≥ b)) = true + simp [h1, h2] + · refine check_of_captured model ρ _ _ + (orE (.eq () (.intConst () c) (.intConst () a)) (.eq () (.intConst () c) (.intConst () b))) + hfac ?_ (.app (.app .op (.eq hc ha)) (.eq hc hb)) ?_ + · simp [Core.Logic.capturedExpr, LExpr.substFvarsFromEnv, Lambda.Env.mk, hx, hy, hr] + · intro fv vt + rw [denote_boolOr _ _ _ _ _ (.eq hc ha) (.eq hc hb), denote_eq_ints, denote_eq_ints] + show (decide (c = a) || decide (c = b)) = true + rcases h3 with rfl | rfl <;> simp + +/-- From `contractPre`: the inputs are integer literals. -/ +theorem max2_pre_ints (model : Lambda.Interp Core.Factory) (ρ : Imperative.Env Core.Expression) + (hpre : Core.Logic.Hoare.Procedure.contractPre model max2Proc ρ) : + ρ.factory = Core.Factory ∧ + ∃ a b : Int, ρ.store xV = some (.intConst () a) ∧ ρ.store yV = some (.intConst () b) := by + obtain ⟨-, hfac, -, hin⟩ := hpre + refine ⟨hfac, ?_⟩ + have hx := hin xV (.tcons "int" []) (by rw [max2_inputs]; simp) + have hy := hin yV (.tcons "int" []) (by rw [max2_inputs]; simp) + obtain ⟨vx, hvx, a, rfl⟩ := hx + obtain ⟨vy, hvy, b, rfl⟩ := hy + exact ⟨a, b, hvx, hvy⟩ + +/-- `Core.Logic.Hoare.set` where the right-hand side is a variable the store binds to an + integer literal: the assigned value is that literal. -/ +theorem set_int_var (π : String → Option Core.Procedure) (x src : Core.Expression.Ident) + (ty : Option LMonoTy) (md : Imperative.MetaData Core.Expression) + (Pre Post : Imperative.Env Core.Expression → Prop) + (hsrc : ∀ ρ₀, Pre ρ₀ → ∃ a : Int, ρ₀.store src = some (.intConst () a)) + (hpost : ∀ (ρ₀ : Imperative.Env Core.Expression) (σ' : Core.CoreStore) (a : Int), Pre ρ₀ → + ρ₀.store src = some (.intConst () a) → + σ' x = some (.intConst () a) → (∀ w, x ≠ w → σ' w = ρ₀.store w) → + Post { ρ₀ with store := σ' }) : + Core.Logic.Hoare.Triple π params Pre [Core.Statement.set x (.fvar () src ty) md] Post := + Core.Logic.Hoare.set π params x _ md Pre Post + (fun ρ₀ σ' v hpre hev hup => by + obtain ⟨a, ha⟩ := hsrc ρ₀ hpre + have hv : v = .intConst () a := (Option.some.injEq _ _).mp + (hev.symm.trans (Lambda.evalFully_fvar_of_value ρ₀.factory ρ₀.store () src ty _ ha + (Lambda.isValue_const_true _ _ _))) + subst hv + cases hup with + | update _hold hnew hoth => exact hpost ρ₀ σ' a hpre ha hnew hoth) + +theorem max2_triple : Core.Logic.Hoare.Procedure.contractTriple max2Core params "max2" := by + refine Core.Logic.Hoare.Procedure.contractTriple_of_core_typed max2Core params "max2" max2Proc _ + max2_findProc max2_body_eq max2_checksTyped (fun model => ?_) + -- the procedure block, then the labelled block + refine (Core.Logic.Hoare.block max2Core.findProcByString? params ?_ + (Imperative.Logic.Hoare.postWF_of_definedVars_nil _ (by native_decide))) model + refine Core.Logic.Hoare.block max2Core.findProcByString? params ?_ + (Imperative.Logic.Hoare.postWF_of_definedVars_nil _ (by native_decide)) + -- the if: each branch is one assignment whose value we know + refine Core.Logic.Hoare.ite max2Core.findProcByString? params ?_ ?_ + (Imperative.Logic.Hoare.postWF_of_definedVars_nil _ (by native_decide)) + (Imperative.Logic.Hoare.postWF_of_definedVars_nil _ (by native_decide)) + · -- then: r := x under x >= y + refine set_int_var _ rV xV intTy md1 _ _ ?_ ?_ + · intro ρ₀ ⟨hpre, _⟩ + obtain ⟨_, a, b, hx, _⟩ := max2_pre_ints model ρ₀ hpre + exact ⟨a, hx⟩ + · intro ρ₀ σ' a ⟨hpre, hcond⟩ hxa hnew hoth + obtain ⟨hfac, a', b, hx, hy⟩ := max2_pre_ints model ρ₀ hpre + rw [hx] at hxa; cases hxa + have hge : b ≤ a := by + rw [hfac, show Core.Expression.eval = Lambda.LExpr.evalFully (TBase := CoreLParams) from rfl, + evalFully_intGe_store _ _ _ _ _ a b hx hy] at hcond + have htt : (Imperative.HasBool.tt : E) = .const () (.boolConst true) := rfl + simpa [htt, LExpr.boolConst] using hcond + have hne : rV ≠ xV := by decide + have hne' : rV ≠ yV := by decide + exact max2_post model _ a b a hfac (by simpa [hoth _ hne] using hx) + (by simpa [hoth _ hne'] using hy) hnew (Int.le_refl a) hge (Or.inl rfl) + · -- else: r := y under ¬ (x >= y) + refine set_int_var _ rV yV intTy md2 _ _ ?_ ?_ + · intro ρ₀ ⟨hpre, _⟩ + obtain ⟨_, a, b, _, hy⟩ := max2_pre_ints model ρ₀ hpre + exact ⟨b, hy⟩ + · intro ρ₀ σ' b ⟨hpre, hcond⟩ hyb hnew hoth + obtain ⟨hfac, a, b', hx, hy⟩ := max2_pre_ints model ρ₀ hpre + rw [hy] at hyb; cases hyb + have hlt : ¬ b ≤ a := by + rw [hfac, show Core.Expression.eval = Lambda.LExpr.evalFully (TBase := CoreLParams) from rfl, + evalFully_intGe_store _ _ _ _ _ a b hx hy] at hcond + have hff : (Imperative.HasBool.ff : E) = .const () (.boolConst false) := rfl + simpa [hff, LExpr.boolConst] using hcond + have hne : rV ≠ xV := by decide + have hne' : rV ≠ yV := by decide + exact max2_post model _ a b b hfac (by simpa [hoth _ hne] using hx) + (by simpa [hoth _ hne'] using hy) hnew (by omega) (Int.le_refl b) (Or.inr rfl) + +end HoareMax2 + diff --git a/docs/HoareLogic.md b/docs/HoareLogic.md index d74e66d..a6a6247 100644 --- a/docs/HoareLogic.md +++ b/docs/HoareLogic.md @@ -149,9 +149,22 @@ Everything in steps 1 to 3 is exercised by the first two and reused unchanged by ## Status -- Steps 1 and 2: not started against Strata's triple. `Deep/` has both against its own +- `max2` is proved against Strata's triple, by hand, in `StrataBooleTest/hoare_max2.lean`: + `contractTriple_of_core_typed`, then `block`, `block`, `ite` and `set`, every side + condition by `native_decide` on the reflected program. The lifting lemmas it uses are + in `StrataBoole/HoareLift.lean`: the evaluator on `Int.Ge` over a store of literals + (one unfolding of `LExpr.eval.eq_2` plus the factory entry's facts), and the denotation + of `Int.Ge`, `Bool.And`, `Bool.Or` and `==` on literals in every model, each from the + model's agreement with the operator's concrete evaluation. The proof is the + specification of the step 1 tactic: it does these steps for any straight-line body with + `if`. Steps 1 and 2 as automation: not started. `Deep/` has both against its own semantics, with `max2` and a counting loop proved. - `StrataBoole/Shallow/Layer.lean` is kept until the milestone is reached. +- Two things the hand proof settled. Under the module system, facts about factory entries + are not `rfl`; they need `import all` of the defining files and `simp` unfolding. And + the typing derivations (`HasTypeA`) must be spelled with the annotations exactly as the + lowering writes them, or the rewrite rules do not fire; the tactic should build them + from the term, not from the types. - `StrataBooleTest/generic_datatypes.lean`: first prototype of the carrier. - Risks. Strata's own hand proof of a two-branch `if` is some twenty-five lines with `native_decide` and explicit store facts, so discharging the side conditions From 1a395e176aa548322f577fa258e1e2fb594c8ebb Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Sun, 8 Nov 2026 18:32:40 +0100 Subject: [PATCH 28/64] Pin Strata to the fork's integration/lean-route branch Strata main plus the open PRs the Lean route needs: the datatype denotation, the checked-to-total sequence pass, the public denote lemmas and the datatypes to Lean draft. Moves back to strata-org/Strata when they merge. Core.verify now lives in Strata.Languages.Core.IncrementalSolve, so Verify.lean imports it. Co-Authored-By: Claude Fable 5.1 --- StrataBoole/Verify.lean | 2 ++ lake-manifest.json | 8 ++++---- lakefile.toml | 11 ++++++----- 3 files changed, 12 insertions(+), 9 deletions(-) diff --git a/StrataBoole/Verify.lean b/StrataBoole/Verify.lean index e6e857c..ff1bfeb 100644 --- a/StrataBoole/Verify.lean +++ b/StrataBoole/Verify.lean @@ -9,6 +9,8 @@ public import StrataBoole.Boole public import Strata.Languages.Core.Program public import Strata.Languages.Core.Statement public import Strata.Languages.Core.Verifier +-- `Core.verify` lives here since Strata walks obligations incrementally for every front end. +public import Strata.Languages.Core.IncrementalSolve public import Strata.DL.Lambda.LExpr import Strata.DL.Lambda.LExprWF public import Strata.DL.Imperative.Stmt diff --git a/lake-manifest.json b/lake-manifest.json index b60740e..74d8566 100644 --- a/lake-manifest.json +++ b/lake-manifest.json @@ -11,14 +11,14 @@ "inputRev": "db545bebe", "inherited": false, "configFile": "lakefile.lean"}, - {"url": "https://github.com/strata-org/Strata", + {"url": "https://github.com/kondylidou/Strata", "type": "git", "subDir": null, "scope": "", - "rev": "9f989914b7a152bb14bf19386cedfff7155d57d2", + "rev": "f8be6585bb98db5a4b4033f36db5130a2679c9ad", "name": "Strata", "manifestFile": "lake-manifest.json", - "inputRev": "9f989914b", + "inputRev": "f8be6585b", "inherited": false, "configFile": "lakefile.toml"}, {"url": "https://github.com/leanprover-community/mathlib4.git", @@ -65,7 +65,7 @@ "type": "git", "subDir": null, "scope": "", - "rev": "5b0260404f759be77aba5db82e4f702aaa3d237d", + "rev": "6ca7dbdf5738571a0f6e7cd7d6bc917206797549", "name": "StrataDDM", "manifestFile": "lake-manifest.json", "inputRev": "main", diff --git a/lakefile.toml b/lakefile.toml index 9ecca37..c793c60 100644 --- a/lakefile.toml +++ b/lakefile.toml @@ -7,11 +7,12 @@ weakLeanArgs = ["--tstack=32768"] [[require]] name = "Strata" -git = "https://github.com/strata-org/Strata" -# A fixed commit, not `main`: with a branch name any `lake update` silently -# moves Strata under us, and the break surfaces later as an unrelated CI -# failure. Bump this deliberately, with the migration it needs. -rev = "9f989914b" +# On this branch Strata is the `integration/lean-route` branch of the fork: Strata main +# plus the open PRs the Lean route needs (datatype denotation, checked-to-total sequence +# pass, public denote lemmas, datatypes to Lean). It moves back to strata-org/Strata when +# they merge. A fixed commit, not a branch name, so `lake update` cannot move it. +git = "https://github.com/kondylidou/Strata" +rev = "f8be6585b" [[require]] name = "smt" From 726ee8dcb326eb066880f8f18a702d0199dbfedb Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Tue, 10 Nov 2026 12:58:51 +0100 Subject: [PATCH 29/64] Move the Lean route onto Strata's denotational semantics Re-pin to the integration head, redo the max2 proof with Strata's lifting lemmas, keep only the Boolean connectives and integer equality in HoareLift, adapt the translator to Core's grouped sequence productions and the Set type, move the test pins that upstream's obligation order and SSA numbering changed, and update the Hoare-logic document. --- StrataBoole/HoareLift.lean | 498 ++++-------------- StrataBoole/Verify.lean | 32 +- .../CoreTests/DefineFunRecTests.lean | 16 +- .../FeatureRequests/mutual_recursion.lean | 10 +- .../FeatureRequests/seq_slicing.lean | 16 +- StrataBooleTest/cast_nested.lean | 16 +- StrataBooleTest/global_readonly_call.lean | 16 +- StrataBooleTest/hoare_max2.lean | 289 +++++----- StrataBooleTest/nat_counterexample.lean | 16 +- .../nat_counterexample_extended.lean | 24 +- StrataBooleTest/nat_detection.lean | 24 +- StrataBooleTest/nat_native.lean | 16 +- StrataBooleTest/stack_array_based.lean | 26 +- docs/HoareLogic.md | 95 ++-- lake-manifest.json | 6 +- lakefile.toml | 2 +- 16 files changed, 399 insertions(+), 703 deletions(-) diff --git a/StrataBoole/HoareLift.lean b/StrataBoole/HoareLift.lean index 282a9c9..0a7ba74 100644 --- a/StrataBoole/HoareLift.lean +++ b/StrataBoole/HoareLift.lean @@ -8,22 +8,23 @@ module public import Strata.Languages.Core.Logic.Hoare public import Strata.Languages.Core.Logic.ContractToHoareTripleProps public import Strata.Languages.Core.Logic.HoareCall -public import Strata.Languages.Core.Factory -import all Strata.DL.Lambda.LExprEval -import all Strata.DL.Lambda.LExprEvalProps -import all Strata.DL.Util.FuncAttr -import all Strata.DL.Lambda.FactoryProps -import all Strata.DL.Lambda.Factory -import all Strata.DL.Lambda.IntBoolFactory +public import Strata.Languages.Core.IntEvalProps +public import Strata.Languages.Core.InstWellFormedSemanticsEval import all Strata.Languages.Core.Factory +import all Strata.DL.Lambda.IntBoolFactory +import all Strata.DL.Lambda.Factory +import all Strata.DL.Lambda.FactoryProps import all Strata.DL.Lambda.Denote.LExprDenote +import all Strata.DL.Lambda.Denote.LExprSemanticsConsistent +import all Strata.DL.Lambda.LExprDenoteEval /-! # Lifting lemmas for the Hoare-logic route -Facts about Core's evaluator on the operators a program uses, stated so that a -goal left by Core's Hoare rules (`Expression.eval ρ.store e = some v`) becomes a -proposition over Lean values. Step 2 of `docs/HoareLogic.md`. Each operator gets -one block like the `Int.Ge` one below. +Strata evaluates Core expressions denotationally and provides, in +`Strata.Languages.Core.IntEvalProps`, the evaluation of the integer operators, literals, +variables, equality and conditionals. This module adds what the Boole programs need on +top of it: the Boolean connectives `Bool.And` and `Bool.Or`, which Core builds as +short-circuit operators. Step 2 of `docs/HoareLogic.md`. -/ public section @@ -32,397 +33,98 @@ open Lambda Core namespace HoareLift -abbrev E := Core.Expression.Expr - -/-! ## Literals and variables -/ - -theorem isValue_intConst (a : Int) : LExpr.isValue Core.Factory (LExpr.intConst () a : E) = true := - Lambda.isValue_const_true _ _ _ - -theorem eval_const (n : Nat) (env : Lambda.Env CoreLParams) (m : Unit) (κ : LConst) : - LExpr.eval n Core.Factory env (.const m κ) = (.const m κ, .value true) := by - cases n <;> simp [LExpr.eval, Lambda.isValue_const_true] - -/-- Core's expression metadata is `Unit`, so every metadata is `()`. -/ -theorem unit_metadata (e : E) : LExpr.metadata e = () := rfl - -theorem eval_intConst (n : Nat) (env : Lambda.Env CoreLParams) (a : Int) : - LExpr.eval n Core.Factory env (.intConst () a) = (.intConst () a, .value true) := - eval_const n env () _ - -theorem eval_boolConst (n : Nat) (env : Lambda.Env CoreLParams) (b : Bool) : - LExpr.eval n Core.Factory env (.boolConst () b) = (.boolConst () b, .value true) := - eval_const n env () _ - -theorem callOfLFunc_fvar_partial_none (x : Core.Expression.Ident) (ty : Option LMonoTy) : - Core.Factory.callOfLFunc (LExpr.fvar () x ty : E) (allowPartialApp := true) = none := by - simp [Factory.callOfLFunc, getLFuncCall, getLFuncCall.go] - -theorem isValue_fvar_false' (x : Core.Expression.Ident) (ty : Option LMonoTy) : - LExpr.isValue Core.Factory (LExpr.fvar () x ty : E) = false := by - rw [LExpr.isValue.eq_def] - split <;> (try (rename_i h; simp at h)) - split - · rename_i h; rw [callOfLFunc_fvar_partial_none] at h; cases h - · rfl - -/-- A variable bound to a value evaluates to it in one step. -/ -theorem eval_fvar_value (env : Lambda.Env CoreLParams) (x : Core.Expression.Ident) - (ty : Option LMonoTy) (v : E) (hx : env x = some v) (hv : LExpr.isValue Core.Factory v = true) : - LExpr.eval 1 Core.Factory env (.fvar () x ty) = (v, .value true) := by - show LExpr.eval (Nat.succ 0) Core.Factory env _ = _ - rw [LExpr.eval.eq_2 (TBase := CoreLParams), isValue_fvar_false'] - simp only [Bool.false_eq_true, ↓reduceIte] - rw [Lambda.callOfLFunc_fvar_none] - simp only [LExpr.evalCore, hx, hv, ↓reduceIte] - -/-! The empty attribute array answers every attribute query negatively. -/ - -theorem attr_findInlineIfConstr_empty : - Strata.DL.Util.FuncAttr.findInlineIfConstr (#[] : Array Strata.DL.Util.FuncAttr) = none := by - simp [Strata.DL.Util.FuncAttr.findInlineIfConstr] -theorem attr_findEvalIfConstr_empty : - Strata.DL.Util.FuncAttr.findEvalIfConstr (#[] : Array Strata.DL.Util.FuncAttr) = none := by - simp [Strata.DL.Util.FuncAttr.findEvalIfConstr] -theorem attr_findEvalIfValue_empty : - Strata.DL.Util.FuncAttr.findEvalIfValue (#[] : Array Strata.DL.Util.FuncAttr) = none := by - simp [Strata.DL.Util.FuncAttr.findEvalIfValue] -theorem attr_hasInlineIfAllValues_empty : - Strata.DL.Util.FuncAttr.hasInlineIfAllValues (#[] : Array Strata.DL.Util.FuncAttr) = false := by - simp [Strata.DL.Util.FuncAttr.hasInlineIfAllValues] -theorem attr_contains_inline_empty : - (#[] : Array Strata.DL.Util.FuncAttr).contains .inline = false := by simp - -/-! ## `Int.Ge` -/ - -/-- `Int.Ge a b`, as the lowering of `a >= b` writes it. -/ -def intGe (a b : E) : E := - .app () (.app () (.op () ⟨"Int.Ge", ()⟩ (some (.arrow .int (.arrow .int .bool)))) a) b - -set_option maxRecDepth 4000 in -theorem intGeFunc_mem : (Lambda.intGeFunc : WFLFunc CoreLParams) ∈ Core.WFFactoryArray := by - rw [Array.mem_def] - unfold Core.WFFactoryArray - simp only [Array.toList_appendList, List.mem_append, List.mem_cons, List.not_mem_nil, - or_false, true_or, or_true] - -theorem factory_get_intGe : - Core.Factory.get? "Int.Ge" = some (Lambda.intGeFunc : WFLFunc CoreLParams).func := by - have hmem : (Lambda.intGeFunc : WFLFunc CoreLParams).func ∈ Core.WFFactoryArray.map (·.func) := - Array.mem_map.mpr ⟨_, intGeFunc_mem, rfl⟩ +/-! ## The connectives in `Core.Factory` -/ + +theorem coreFactory_boolAnd : + (Core.Factory)["Bool.And"]? = some (Lambda.boolAndFunc (T := CoreLParams)).func := by + have hmem : (Lambda.boolAndFunc (T := CoreLParams)).func ∈ Core.WFFactoryArray.map (·.func) := by + refine Array.mem_map.mpr ⟨Lambda.boolAndFunc (T := CoreLParams), ?_, rfl⟩ + rw [Array.mem_def] + unfold Core.WFFactoryArray + simp only [Array.toList_appendList] + repeat (first | exact List.Mem.head _ | apply List.Mem.tail) + have hCore : Core.Factory = Lambda.Factory.ofArray (Core.WFFactoryArray.map (·.func)) := rfl + rw [hCore] exact Lambda.Factory.get?_ofArray_of_mem hmem Core.WFFactoryArray_func_name_nodup -theorem callOfLFunc_intGe (a b : E) (aPA : Bool) : - Core.Factory.callOfLFunc (intGe a b) (allowPartialApp := aPA) - = some (.op () ⟨"Int.Ge", ()⟩ (some (.arrow .int (.arrow .int .bool))), [a, b], - (Lambda.intGeFunc : WFLFunc CoreLParams).func) := by - have hget : Core.Factory[("Int.Ge" : String)]? = - some (Lambda.intGeFunc : WFLFunc CoreLParams).func := factory_get_intGe - simp [Factory.callOfLFunc, getLFuncCall, getLFuncCall.go, intGe, hget] - cases aPA <;> simp [Lambda.intGeFunc, Lambda.binaryOp] - -theorem isValue_intGe_false (a b : E) : LExpr.isValue Core.Factory (intGe a b) = false := by - rw [LExpr.isValue.eq_def] - split <;> (try (rename_i h; simp [intGe] at h)) - split - · rename_i h - rw [callOfLFunc_intGe] at h - simp only [Option.some.injEq, Prod.mk.injEq] at h - obtain ⟨-, rfl, rfl⟩ := h - simp [Lambda.intGeFunc, Lambda.binaryOp] - · rfl - -theorem intGeFunc_attr : (Lambda.intGeFunc : WFLFunc CoreLParams).func.attr = #[] := by - simp [Lambda.intGeFunc, Lambda.binaryOp] -theorem intGeFunc_body : (Lambda.intGeFunc : WFLFunc CoreLParams).func.body = none := by - simp [Lambda.intGeFunc, Lambda.binaryOp] - -theorem shortCircuitCall_intGe (args : List E) : - LExpr.shortCircuitCall? (Lambda.intGeFunc : WFLFunc CoreLParams).func args = none := by - unfold LExpr.shortCircuitCall? - rw [intGeFunc_attr] - rfl - -/-- `Int.Ge` on two arguments that evaluate to integer literals in one step. -/ -theorem eval_intGe_args (env : Lambda.Env CoreLParams) (a' b' : E) (a b : Int) - (ha : LExpr.eval 1 Core.Factory env a' = (.intConst () a, .value true)) - (hb : LExpr.eval 1 Core.Factory env b' = (.intConst () b, .value true)) : - LExpr.eval 2 Core.Factory env (intGe a' b') = (.boolConst () (decide (a ≥ b)), .value true) := by - show LExpr.eval (Nat.succ 1) Core.Factory env _ = _ - rw [LExpr.eval.eq_2 (TBase := CoreLParams), isValue_intGe_false] - simp only [Bool.false_eq_true, ↓reduceIte] - rw [callOfLFunc_intGe] - dsimp only - rw [shortCircuitCall_intGe] - simp only [List.map_cons, List.map_nil, ha, hb, intGeFunc_body, intGeFunc_attr, - Option.isSome_none, Bool.false_and, Bool.false_or, Bool.false_eq_true, ↓reduceDIte, - attr_findInlineIfConstr_empty, attr_findEvalIfConstr_empty, attr_findEvalIfValue_empty, - attr_hasInlineIfAllValues_empty, attr_contains_inline_empty, - List.all_cons, List.all_nil, Lambda.isValue_const_true, Bool.and_true, Bool.true_and, - Bool.true_or, Bool.or_false, ↓reduceIte, unit_metadata, - Lambda.intGeFunc, Lambda.binaryOp, LambdaLeanType.cevalTy, LambdaLeanType.mkConst, - LExpr.denoteInt, LExpr.intConst, LExpr.boolConst, - eval_const, LExpr.combineEvalResValueFlag_eq_pair, - LExpr.EvalResult.isValueTrue, LExpr.EvalResult.combineValueFlag, Bool.and_self] - -/-- The lifting lemma the `if` rule needs: `x >= y` in a store binding `x` and `y` to - integer literals evaluates to the Boolean literal `a ≥ b`. -/ -theorem evalFully_intGe_store (env : Lambda.Env CoreLParams) (x y : Core.Expression.Ident) - (tx ty : Option LMonoTy) (a b : Int) - (hx : env x = some (.intConst () a)) (hy : env y = some (.intConst () b)) : - LExpr.evalFully Core.Factory env (intGe (.fvar () x tx) (.fvar () y ty)) - = some (.boolConst () (decide (a ≥ b))) := - Lambda.evalFully_of_value_true Core.Factory env _ 2 _ - (eval_intGe_args env _ _ a b - (eval_fvar_value env x tx _ hx (isValue_intConst a)) - (eval_fvar_value env y ty _ hy (isValue_intConst b))) - -/-! ## `Int.Ge` under any consistent model - -The denotation half of the lifting: in every `Lambda.Interp Core.Factory`, the operator -applied to two integer literals denotes the Boolean the evaluator computes, because the -model agrees with the operator's concrete evaluation. -/ - -theorem intGe_mem_factory : "Int.Ge" ∈ Core.Factory := - Lambda.Factory.getElem?_some_implies_mem factory_get_intGe - -theorem factory_getElem_intGe : - Core.Factory["Int.Ge"]'intGe_mem_factory = (Lambda.intGeFunc : WFLFunc CoreLParams).func := - Lambda.Factory.getElem?_some_getElem factory_get_intGe - -/-- `denote_intConst` with the type spelled as the lowering annotates it. -/ -theorem denote_intConst' (tcInterp : TyConstrInterp) (opInterp : OpInterp tcInterp) - (fv : FreeVarVal CoreLParams tcInterp) (vt : TyVarVal) {m : Unit} {i : Int} - (h : LExpr.HasTypeA [] (LExpr.intConst m i : E) LMonoTy.int) : - LExpr.denote tcInterp opInterp fv vt .nil (LExpr.intConst m i) LMonoTy.int h = i := - denote_intConst tcInterp opInterp fv vt .nil h - -theorem hasTypeA_intGe_consts (c a : Int) : - LExpr.HasTypeA [] (intGe (.intConst () c) (.intConst () a)) .bool := - .app (.app .op .const) .const - -theorem denote_intGe_consts (I : Lambda.Interp Core.Factory) - (fv : FreeVarVal CoreLParams I.tcInterp) (vt : TyVarVal) (c a : Int) - (h : LExpr.HasTypeA [] (intGe (.intConst () c) (.intConst () a)) .bool) : - LExpr.denote I.tcInterp I.opInterp fv vt .nil (intGe (.intConst () c) (.intConst () a)) .bool h - = decide (c ≥ a) := by - have hic := I.interpConsistent - unfold Lambda.Factory.InterpConsistent at hic - have hcons := hic.2 "Int.Ge" intGe_mem_factory - rw [factory_getElem_intGe] at hcons - cases hce : (Lambda.intGeFunc : WFLFunc CoreLParams).func.concreteEval with - | none => simp [Lambda.intGeFunc, Lambda.binaryOp] at hce - | some ceval => - have happ : ceval () [.intConst () c, .intConst () a] = some (.boolConst () (decide (c ≥ a))) := by - simp [Lambda.intGeFunc, Lambda.binaryOp] at hce - subst hce - simp [LambdaLeanType.cevalTy, LambdaLeanType.mkConst, LExpr.denoteInt, LExpr.boolConst] - have hspec := hcons ceval hce vt fv () Subst.empty [.intConst () c, .intConst () a] - (.boolConst () (decide (c ≥ a))) happ - have hs := hspec (.cons .const (.cons .const .nil)) .const - have hc : LExpr.HasTypeA [] (LExpr.intConst () c : E) (.tcons "int" []) := .const - have ha : LExpr.HasTypeA [] (LExpr.intConst () a : E) (.tcons "int" []) := .const - have hop : LExpr.HasTypeA [] - (LExpr.op () ⟨"Int.Ge", ()⟩ (some (.arrow .int (.arrow .int .bool))) : E) - (.arrow .int (.arrow .int .bool)) := .op - have hfn : LExpr.HasTypeA [] - (LExpr.app () (LExpr.op () ⟨"Int.Ge", ()⟩ (some (.arrow .int (.arrow .int .bool)))) - (LExpr.intConst () c) : E) (.arrow .int .bool) := .app hop hc - revert h - unfold intGe - intro h - rw [denote_app (h_fn := hfn) (h_arg := ha), denote_app (h_fn := hop) (h_arg := hc), - denote_op] - first - | exact hs.symm - | (simp only [denote_intConst'] ; exact hs.symm) - -/-! ## `Bool.And`, `Bool.Or` and `==` on literals, under any consistent model -/ - -set_option maxRecDepth 4000 in -theorem boolAndFunc_mem : (Lambda.boolAndFunc : WFLFunc CoreLParams) ∈ Core.WFFactoryArray := by - rw [Array.mem_def] - unfold Core.WFFactoryArray - simp only [Array.toList_appendList, List.mem_append, List.mem_cons, List.not_mem_nil, - or_false, true_or, or_true] - -set_option maxRecDepth 4000 in -theorem boolOrFunc_mem : (Lambda.boolOrFunc : WFLFunc CoreLParams) ∈ Core.WFFactoryArray := by - rw [Array.mem_def] - unfold Core.WFFactoryArray - simp only [Array.toList_appendList, List.mem_append, List.mem_cons, List.not_mem_nil, - or_false, true_or, or_true] - -theorem factory_get_of_mem (wf : WFLFunc CoreLParams) (h : wf ∈ Core.WFFactoryArray) : - Core.Factory.get? wf.func.name.name = some wf.func := - Lambda.Factory.get?_ofArray_of_mem (Array.mem_map.mpr ⟨_, h, rfl⟩) - Core.WFFactoryArray_func_name_nodup - -theorem factory_get_boolAnd : - Core.Factory.get? "Bool.And" = some (Lambda.boolAndFunc : WFLFunc CoreLParams).func := - factory_get_of_mem _ boolAndFunc_mem -theorem factory_get_boolOr : - Core.Factory.get? "Bool.Or" = some (Lambda.boolOrFunc : WFLFunc CoreLParams).func := - factory_get_of_mem _ boolOrFunc_mem - -/-- The denotation of a short-circuit Boolean operator on two Boolean literals: the - model agrees with the operator's concrete evaluation, which decides the result from - the first literal or returns the second. Shared by `Bool.And` and `Bool.Or`. -/ -theorem denote_shortCircuit_consts (I : Lambda.Interp Core.Factory) - (fv : FreeVarVal CoreLParams I.tcInterp) (vt : TyVarVal) - (name : String) (absorb decided : Bool) - (hget : Core.Factory.get? name - = some (Lambda.shortCircuitOp (T := CoreLParams) ⟨name, ()⟩ absorb decided).func) - (p q : Bool) - (h : LExpr.HasTypeA [] - (.app () (.app () (.op () ⟨name, ()⟩ (some (.arrow .bool (.arrow .bool .bool)))) - (.boolConst () p)) (.boolConst () q) : E) .bool) : - LExpr.denote I.tcInterp I.opInterp fv vt .nil - (.app () (.app () (.op () ⟨name, ()⟩ (some (.arrow .bool (.arrow .bool .bool)))) - (.boolConst () p)) (.boolConst () q)) .bool h - = (if p == absorb then decided else q) := by - have hmem : name ∈ Core.Factory := Lambda.Factory.getElem?_some_implies_mem hget - have hic := I.interpConsistent - unfold Lambda.Factory.InterpConsistent at hic - have hcons := hic.2 name hmem - rw [Lambda.Factory.getElem?_some_getElem hget] at hcons - cases hceq : (Lambda.shortCircuitOp (T := CoreLParams) ⟨name, ()⟩ absorb decided).func.concreteEval with - | none => simp [Lambda.shortCircuitOp] at hceq - | some ceval => - have happ : ceval () [.boolConst () p, .boolConst () q] - = some (.boolConst () (if p == absorb then decided else q)) := by - simp [Lambda.shortCircuitOp] at hceq - subst hceq - cases p <;> cases absorb <;> - simp [LambdaLeanType.cevalTy, LambdaLeanType.mkConst, LExpr.denoteBool, LExpr.boolConst] - have hspec := hcons ceval hceq vt fv () Subst.empty [.boolConst () p, .boolConst () q] - (.boolConst () (if p == absorb then decided else q)) happ - have hs := hspec (.cons .const (.cons .const .nil)) .const - have hp : LExpr.HasTypeA [] (LExpr.boolConst () p : E) (.tcons "bool" []) := .const - have hq : LExpr.HasTypeA [] (LExpr.boolConst () q : E) (.tcons "bool" []) := .const - have hop : LExpr.HasTypeA [] - (LExpr.op () ⟨name, ()⟩ (some (.arrow .bool (.arrow .bool .bool))) : E) - (.arrow .bool (.arrow .bool .bool)) := .op - have hfn : LExpr.HasTypeA [] - (LExpr.app () (LExpr.op () ⟨name, ()⟩ (some (.arrow .bool (.arrow .bool .bool)))) - (LExpr.boolConst () p) : E) (.arrow .bool .bool) := .app hop hp - rw [denote_app (h_fn := hfn) (h_arg := hq), denote_app (h_fn := hop) (h_arg := hp), - denote_op] - exact hs.symm - -theorem denote_boolAnd_consts (I : Lambda.Interp Core.Factory) - (fv : FreeVarVal CoreLParams I.tcInterp) (vt : TyVarVal) (p q : Bool) - (h : LExpr.HasTypeA [] - (.app () (.app () (.op () ⟨"Bool.And", ()⟩ (some (.arrow .bool (.arrow .bool .bool)))) - (.boolConst () p)) (.boolConst () q) : E) .bool) : - LExpr.denote I.tcInterp I.opInterp fv vt .nil - (.app () (.app () (.op () ⟨"Bool.And", ()⟩ (some (.arrow .bool (.arrow .bool .bool)))) - (.boolConst () p)) (.boolConst () q)) .bool h = (p && q) := by - rw [denote_shortCircuit_consts I fv vt "Bool.And" false false factory_get_boolAnd p q h] - cases p <;> (try simp) <;> (try rfl) - -theorem denote_boolOr_consts (I : Lambda.Interp Core.Factory) - (fv : FreeVarVal CoreLParams I.tcInterp) (vt : TyVarVal) (p q : Bool) - (h : LExpr.HasTypeA [] - (.app () (.app () (.op () ⟨"Bool.Or", ()⟩ (some (.arrow .bool (.arrow .bool .bool)))) - (.boolConst () p)) (.boolConst () q) : E) .bool) : - LExpr.denote I.tcInterp I.opInterp fv vt .nil - (.app () (.app () (.op () ⟨"Bool.Or", ()⟩ (some (.arrow .bool (.arrow .bool .bool)))) - (.boolConst () p)) (.boolConst () q)) .bool h = (p || q) := by - rw [denote_shortCircuit_consts I fv vt "Bool.Or" true true factory_get_boolOr p q h] - cases p <;> (try simp) <;> (try rfl) - -/-- `Bool.And` on any two Boolean expressions: the operator denotes `&&`. The literal case - carries the model fact; the general case follows because the denotation of a literal - is, definitionally, its value. -/ -theorem denote_boolAnd (I : Lambda.Interp Core.Factory) - (fv : FreeVarVal CoreLParams I.tcInterp) (vt : TyVarVal) (e1 e2 : E) - (h1 : LExpr.HasTypeA [] e1 .bool) (h2 : LExpr.HasTypeA [] e2 .bool) - (h : LExpr.HasTypeA [] - (.app () (.app () (.op () ⟨"Bool.And", ()⟩ (some (.arrow .bool (.arrow .bool .bool)))) e1) e2) - .bool) : - LExpr.denote I.tcInterp I.opInterp fv vt .nil - (.app () (.app () (.op () ⟨"Bool.And", ()⟩ (some (.arrow .bool (.arrow .bool .bool)))) e1) e2) - .bool h - = (LExpr.denote I.tcInterp I.opInterp fv vt .nil e1 .bool h1 && - LExpr.denote I.tcInterp I.opInterp fv vt .nil e2 .bool h2) := by - have hop : LExpr.HasTypeA [] - (LExpr.op () ⟨"Bool.And", ()⟩ (some (.arrow .bool (.arrow .bool .bool))) : E) - (.arrow .bool (.arrow .bool .bool)) := .op - have hfn : LExpr.HasTypeA [] - (LExpr.app () (LExpr.op () ⟨"Bool.And", ()⟩ (some (.arrow .bool (.arrow .bool .bool)))) e1 : E) - (.arrow .bool .bool) := .app hop h1 - have hp : LExpr.HasTypeA [] - (LExpr.boolConst () (LExpr.denote I.tcInterp I.opInterp fv vt .nil e1 .bool h1) : E) - (.tcons "bool" []) := .const - have hq : LExpr.HasTypeA [] - (LExpr.boolConst () (LExpr.denote I.tcInterp I.opInterp fv vt .nil e2 .bool h2) : E) - (.tcons "bool" []) := .const - have hfnL : LExpr.HasTypeA [] - (LExpr.app () (LExpr.op () ⟨"Bool.And", ()⟩ (some (.arrow .bool (.arrow .bool .bool)))) - (LExpr.boolConst () (LExpr.denote I.tcInterp I.opInterp fv vt .nil e1 .bool h1)) : E) - (.arrow .bool .bool) := .app hop hp - have hlit := denote_boolAnd_consts I fv vt - (LExpr.denote I.tcInterp I.opInterp fv vt .nil e1 .bool h1) - (LExpr.denote I.tcInterp I.opInterp fv vt .nil e2 .bool h2) (.app hfnL hq) - rw [denote_app (h_fn := hfnL) (h_arg := hq), denote_app (h_fn := hop) (h_arg := hp), - denote_op] at hlit - rw [denote_app (h_fn := hfn) (h_arg := h2), denote_app (h_fn := hop) (h_arg := h1), denote_op] - exact hlit - -theorem denote_boolOr (I : Lambda.Interp Core.Factory) - (fv : FreeVarVal CoreLParams I.tcInterp) (vt : TyVarVal) (e1 e2 : E) - (h1 : LExpr.HasTypeA [] e1 .bool) (h2 : LExpr.HasTypeA [] e2 .bool) - (h : LExpr.HasTypeA [] - (.app () (.app () (.op () ⟨"Bool.Or", ()⟩ (some (.arrow .bool (.arrow .bool .bool)))) e1) e2) - .bool) : - LExpr.denote I.tcInterp I.opInterp fv vt .nil - (.app () (.app () (.op () ⟨"Bool.Or", ()⟩ (some (.arrow .bool (.arrow .bool .bool)))) e1) e2) - .bool h - = (LExpr.denote I.tcInterp I.opInterp fv vt .nil e1 .bool h1 || - LExpr.denote I.tcInterp I.opInterp fv vt .nil e2 .bool h2) := by - have hop : LExpr.HasTypeA [] - (LExpr.op () ⟨"Bool.Or", ()⟩ (some (.arrow .bool (.arrow .bool .bool))) : E) - (.arrow .bool (.arrow .bool .bool)) := .op - have hfn : LExpr.HasTypeA [] - (LExpr.app () (LExpr.op () ⟨"Bool.Or", ()⟩ (some (.arrow .bool (.arrow .bool .bool)))) e1 : E) - (.arrow .bool .bool) := .app hop h1 - have hp : LExpr.HasTypeA [] - (LExpr.boolConst () (LExpr.denote I.tcInterp I.opInterp fv vt .nil e1 .bool h1) : E) - (.tcons "bool" []) := .const - have hq : LExpr.HasTypeA [] - (LExpr.boolConst () (LExpr.denote I.tcInterp I.opInterp fv vt .nil e2 .bool h2) : E) - (.tcons "bool" []) := .const - have hfnL : LExpr.HasTypeA [] - (LExpr.app () (LExpr.op () ⟨"Bool.Or", ()⟩ (some (.arrow .bool (.arrow .bool .bool)))) - (LExpr.boolConst () (LExpr.denote I.tcInterp I.opInterp fv vt .nil e1 .bool h1)) : E) - (.arrow .bool .bool) := .app hop hp - have hlit := denote_boolOr_consts I fv vt - (LExpr.denote I.tcInterp I.opInterp fv vt .nil e1 .bool h1) - (LExpr.denote I.tcInterp I.opInterp fv vt .nil e2 .bool h2) (.app hfnL hq) - rw [denote_app (h_fn := hfnL) (h_arg := hq), denote_app (h_fn := hop) (h_arg := hp), - denote_op] at hlit - rw [denote_app (h_fn := hfn) (h_arg := h2), denote_app (h_fn := hop) (h_arg := h1), denote_op] - exact hlit +theorem coreFactory_boolOr : + (Core.Factory)["Bool.Or"]? = some (Lambda.boolOrFunc (T := CoreLParams)).func := by + have hmem : (Lambda.boolOrFunc (T := CoreLParams)).func ∈ Core.WFFactoryArray.map (·.func) := by + refine Array.mem_map.mpr ⟨Lambda.boolOrFunc (T := CoreLParams), ?_, rfl⟩ + rw [Array.mem_def] + unfold Core.WFFactoryArray + simp only [Array.toList_appendList] + repeat (first | exact List.Mem.head _ | apply List.Mem.tail) + have hCore : Core.Factory = Lambda.Factory.ofArray (Core.WFFactoryArray.map (·.func)) := rfl + rw [hCore] + exact Lambda.Factory.get?_ofArray_of_mem hmem Core.WFFactoryArray_func_name_nodup -/-- `==` on two integer literals denotes their equality. -/ -theorem denote_eq_ints (I : Lambda.Interp Core.Factory) - (fv : FreeVarVal CoreLParams I.tcInterp) (vt : TyVarVal) (c a : Int) - (h : LExpr.HasTypeA [] (.eq () (LExpr.intConst () c) (LExpr.intConst () a) : E) .bool) : - LExpr.denote I.tcInterp I.opInterp fv vt .nil - (.eq () (LExpr.intConst () c) (LExpr.intConst () a)) .bool h = decide (c = a) := by - have hc : LExpr.HasTypeA [] (LExpr.intConst () c : E) LMonoTy.int := .const - have ha : LExpr.HasTypeA [] (LExpr.intConst () a : E) LMonoTy.int := .const - by_cases hca : c = a - · subst hca - rw [denote_eq_true _ hc ha h rfl] - show (true : Bool) = decide (c = c) - simp - · rw [denote_eq_false _ hc ha h (by rw [denote_intConst', denote_intConst']; exact hca)] - show (false : Bool) = decide (c = a) - simp [hca] +/-! ## Their interpretation in every consistent model + +A short-circuit operator's concrete evaluation on two Boolean literals is its truth +table, so every model that is consistent with the factory interprets it that way. -/ + +theorem boolAnd_opInterp_of_lookup {factory : Lambda.Factory CoreLParams} + (model : Lambda.Interp factory) + (hlookup : factory["Bool.And"]? = some (Lambda.boolAndFunc (T := CoreLParams)).func) + (p q : Bool) : + (model.opInterp "Bool.And" (Lambda.LSort.mkArrow .bool [.bool, .bool]) p q : Bool) + = (p && q) := by + have heval : (Lambda.boolAndFunc (T := CoreLParams)).func.concreteEval.bind + (fun ce => ce () [.boolConst () p, .boolConst () q]) = some (.boolConst () (p && q)) := by + cases p <;> rfl + exact (Core.opInterp_of_concreteEval model hlookup rfl heval (fun _ => .int) (fun _ s => + @default _ (@Lambda.SortDenote.instInhabited model.tcInterp model.allInhabited s)) + (.cons .const (.cons .const .nil)) .const).symm + +theorem boolOr_opInterp_of_lookup {factory : Lambda.Factory CoreLParams} + (model : Lambda.Interp factory) + (hlookup : factory["Bool.Or"]? = some (Lambda.boolOrFunc (T := CoreLParams)).func) + (p q : Bool) : + (model.opInterp "Bool.Or" (Lambda.LSort.mkArrow .bool [.bool, .bool]) p q : Bool) + = (p || q) := by + have heval : (Lambda.boolOrFunc (T := CoreLParams)).func.concreteEval.bind + (fun ce => ce () [.boolConst () p, .boolConst () q]) = some (.boolConst () (p || q)) := by + cases p <;> rfl + exact (Core.opInterp_of_concreteEval model hlookup rfl heval (fun _ => .int) (fun _ s => + @default _ (@Lambda.SortDenote.instInhabited model.tcInterp model.allInhabited s)) + (.cons .const (.cons .const .nil)) .const).symm + +/-! ## Their evaluation -/ + +/-- `a && b` evaluates to the conjunction of the Booleans its operands evaluate to. -/ +theorem eval_boolAnd {f : Core.Expression.Factory} {m m' : Core.ExpressionMetadata} + (hlookup : f.factory["Bool.And"]? = some (Lambda.boolAndFunc (T := CoreLParams)).func) + {σ : Core.CoreStore} {x y : Core.Expression.Expr} {p q : Bool} + (hx : Core.Expression.eval f σ x = some (SemValue.ofBool f.model.tcInterp p)) + (hy : Core.Expression.eval f σ y = some (SemValue.ofBool f.model.tcInterp q)) : + Core.Expression.eval f σ (.app m (.app m' Core.boolAndOp x) y) = + some (SemValue.ofBool f.model.tcInterp (p && q)) := + Core.eval_app2_op "Bool.And" (c := .bool) rfl rfl rfl hx hy + (boolAnd_opInterp_of_lookup f.model hlookup p q) + +/-- `a || b` evaluates to the disjunction of the Booleans its operands evaluate to. -/ +theorem eval_boolOr {f : Core.Expression.Factory} {m m' : Core.ExpressionMetadata} + (hlookup : f.factory["Bool.Or"]? = some (Lambda.boolOrFunc (T := CoreLParams)).func) + {σ : Core.CoreStore} {x y : Core.Expression.Expr} {p q : Bool} + (hx : Core.Expression.eval f σ x = some (SemValue.ofBool f.model.tcInterp p)) + (hy : Core.Expression.eval f σ y = some (SemValue.ofBool f.model.tcInterp q)) : + Core.Expression.eval f σ (.app m (.app m' Core.boolOrOp x) y) = + some (SemValue.ofBool f.model.tcInterp (p || q)) := + Core.eval_app2_op "Bool.Or" (c := .bool) rfl rfl rfl hx hy + (boolOr_opInterp_of_lookup f.model hlookup p q) + +/-- `x == y` on two integer-valued variables evaluates to the Boolean of their equality. -/ +theorem eval_eq_ints (f : Core.Expression.Factory) {m : Core.ExpressionMetadata} + {σ : Core.CoreStore} {x y : Core.Expression.Expr} {a b : Int} + (hx : Core.Expression.eval f σ x = some (SemValue.ofInt f.model.tcInterp a)) + (hy : Core.Expression.eval f σ y = some (SemValue.ofInt f.model.tcInterp b)) : + Core.Expression.eval f σ (.eq m x y) = some (SemValue.ofBool f.model.tcInterp (decide (a = b))) := by + by_cases hab : a = b + · subst hab + simpa using Core.eval_eq_true f hx hy + · simpa [hab] using Core.eval_eq_false f hx hy rfl (fun h => hab (SemValue.ofInt_injective h)) end HoareLift - end -- public section diff --git a/StrataBoole/Verify.lean b/StrataBoole/Verify.lean index ff1bfeb..d0fff26 100644 --- a/StrataBoole/Verify.lean +++ b/StrataBoole/Verify.lean @@ -240,6 +240,7 @@ private def typeRange : Boole.Type → SourceRange | .W1 m | .W8 m | .W16 m | .W32 m | .W64 m | .W128 m => m | .Map m _ _ => m | .Sequence m _ => m + | .Set m _ => m | .nat m => m private def toCoreMonoType (t : Boole.Type) : TranslateM Lambda.LMonoTy := do @@ -488,20 +489,29 @@ private def toCoreExpr (e : Boole.Expr) : TranslateM Core.Expression.Expr := do | .bvsmod m ty a b => toCoreBvBin m ty "SMod" (← toCoreExpr a) (← toCoreExpr b) | .old _ _ a => return oldifyExpr (← get).currentInoutNames (← toCoreExpr a) - -- Sequence operations (Core Grammar, inherited by Boole) + -- Sequence operations (Core Grammar, inherited by Boole). Core groups each checked + -- operation with its total twin under one production whose first argument names the + -- operator; the twin has no bounds precondition and is unconstrained out of range. | .seq_length _ _ s => return mkCoreApp Core.seqLengthOp [← toCoreExpr s] - | .seq_select _ _ s i => return mkCoreApp Core.seqSelectOp [← toCoreExpr s, ← toCoreExpr i] - | .seq_take _ _ s n => return mkCoreApp Core.seqTakeOp [← toCoreExpr s, ← toCoreExpr n] - | .seq_drop _ _ s n => return mkCoreApp Core.seqDropOp [← toCoreExpr s, ← toCoreExpr n] + | .seqSelectOp _ _ f s i => + let op := match f with + | .seq_select _ => Core.seqSelectOp + | .seq_select_unsafe _ => Core.seqSelectUnsafeOp + return mkCoreApp op [← toCoreExpr s, ← toCoreExpr i] + | .seqSliceOp _ _ f s n => + let op := match f with + | .seq_take _ => Core.seqTakeOp + | .seq_take_unsafe _ => Core.seqTakeUnsafeOp + | .seq_drop _ => Core.seqDropOp + | .seq_drop_unsafe _ => Core.seqDropUnsafeOp + return mkCoreApp op [← toCoreExpr s, ← toCoreExpr n] | .seq_append _ _ s1 s2 => return mkCoreApp Core.seqAppendOp [← toCoreExpr s1, ← toCoreExpr s2] | .seq_build _ _ s v => return mkCoreApp Core.seqBuildOp [← toCoreExpr s, ← toCoreExpr v] - | .seq_update _ _ s i v => return mkCoreApp Core.seqUpdateOp [← toCoreExpr s, ← toCoreExpr i, ← toCoreExpr v] - -- Total (unsafe) variants: no bounds precondition, unconstrained out of range. - -- Useful in spec functions over fixed-size arrays whose length is a typing fact. - | .seq_select_unsafe _ _ s i => return mkCoreApp Core.seqSelectUnsafeOp [← toCoreExpr s, ← toCoreExpr i] - | .seq_update_unsafe _ _ s i v => return mkCoreApp Core.seqUpdateUnsafeOp [← toCoreExpr s, ← toCoreExpr i, ← toCoreExpr v] - | .seq_take_unsafe _ _ s n => return mkCoreApp Core.seqTakeUnsafeOp [← toCoreExpr s, ← toCoreExpr n] - | .seq_drop_unsafe _ _ s n => return mkCoreApp Core.seqDropUnsafeOp [← toCoreExpr s, ← toCoreExpr n] + | .seqUpdateOp _ _ f s i v => + let op := match f with + | .seq_update _ => Core.seqUpdateOp + | .seq_update_unsafe _ => Core.seqUpdateUnsafeOp + return mkCoreApp op [← toCoreExpr s, ← toCoreExpr i, ← toCoreExpr v] | .seq_contains _ _ s v => return mkCoreApp Core.seqContainsOp [← toCoreExpr s, ← toCoreExpr v] -- Sequence operations (Boole Verus-style additions — not in Core Grammar) -- Sequence.skip(s, n) = drop first n elements diff --git a/StrataBooleTest/CoreTests/DefineFunRecTests.lean b/StrataBooleTest/CoreTests/DefineFunRecTests.lean index e9e8f11..92236fb 100644 --- a/StrataBooleTest/CoreTests/DefineFunRecTests.lean +++ b/StrataBooleTest/CoreTests/DefineFunRecTests.lean @@ -104,14 +104,6 @@ procedure test_sum_counterexample (a : nat, b : nat) spec { --------------------------------------------------------------------- /-- info: -Obligation: pos.toInt_body_calls_pos..xO_h_0 -Property: assert -Result: ✅ pass - -Obligation: pos.toInt_body_calls_pos..xI_h_1 -Property: assert -Result: ✅ pass - Obligation: pos.toInt_terminates_0 Property: assert Result: ❓ unknown @@ -120,6 +112,14 @@ Obligation: pos.toInt_terminates_1 Property: assert Result: ❓ unknown +Obligation: pos.toInt_body_calls_pos..xO_h_0 +Property: assert +Result: ✅ pass + +Obligation: pos.toInt_body_calls_pos..xI_h_1 +Property: assert +Result: ✅ pass + Obligation: pos.fromInt_terminates_0 Property: assert Result: ✅ pass diff --git a/StrataBooleTest/FeatureRequests/mutual_recursion.lean b/StrataBooleTest/FeatureRequests/mutual_recursion.lean index 5e73895..d045722 100644 --- a/StrataBooleTest/FeatureRequests/mutual_recursion.lean +++ b/StrataBooleTest/FeatureRequests/mutual_recursion.lean @@ -53,19 +53,19 @@ spec { #end /-- info: -Obligation: even_body_calls_MyNat..pred_0 +Obligation: even_terminates_0 Property: assert Result: ✅ pass -Obligation: odd_body_calls_MyNat..pred_0 +Obligation: odd_terminates_0 Property: assert Result: ✅ pass -Obligation: even_terminates_0 +Obligation: even_body_calls_MyNat..pred_0 Property: assert Result: ✅ pass -Obligation: odd_terminates_0 +Obligation: odd_body_calls_MyNat..pred_0 Property: assert Result: ✅ pass @@ -106,7 +106,7 @@ Result: ✅ pass-/ -- Open gap: the denotation of SMT queries has no datatypes yet, so `gen_smt_vcs` -- refuses the selector well-formedness VCs of `MyNat` (strata-org/Strata#1480). /-- -error: gen_smt_vcs: verification condition 'even_body_calls_MyNat..pred_0' uses a datatype, which the denotation of SMT queries does not cover yet, so no Lean goal can be created for it; the SMT path still checks it +error: gen_smt_vcs: verification condition 'even_terminates_0' uses a datatype, which the denotation of SMT queries does not cover yet, so no Lean goal can be created for it; the SMT path still checks it -/ #guard_msgs in example : Strata.smtVCsCorrectBoole mutualRecursionSeed := by diff --git a/StrataBooleTest/FeatureRequests/seq_slicing.lean b/StrataBooleTest/FeatureRequests/seq_slicing.lean index 3f525a4..a49c415 100644 --- a/StrataBooleTest/FeatureRequests/seq_slicing.lean +++ b/StrataBooleTest/FeatureRequests/seq_slicing.lean @@ -143,14 +143,6 @@ Obligation: seq_empty_bv64_seed_ensures_8_1950 Property: assert Result: ✅ pass -Obligation: reconstruct_body_calls_Sequence.select_0 -Property: out-of-bounds access check -Result: ✅ pass - -Obligation: reconstruct_body_calls_Sequence.drop_1 -Property: out-of-bounds access check -Result: ✅ pass - Obligation: reconstruct_terminates_0 Property: assert Result: ✅ pass @@ -158,6 +150,14 @@ Result: ✅ pass Obligation: reconstruct_terminates_1 Property: assert Result: ✅ pass + +Obligation: reconstruct_body_calls_Sequence.select_0 +Property: out-of-bounds access check +Result: ✅ pass + +Obligation: reconstruct_body_calls_Sequence.drop_1 +Property: out-of-bounds access check +Result: ✅ pass -/ #guard_msgs in #eval Strata.Boole.verify "cvc5" seqSlicingSeed (options := .quiet) diff --git a/StrataBooleTest/cast_nested.lean b/StrataBooleTest/cast_nested.lean index 99c2e38..901b27a 100644 --- a/StrataBooleTest/cast_nested.lean +++ b/StrataBooleTest/cast_nested.lean @@ -176,14 +176,6 @@ Obligation: cast_in_exists_ensures_11_1592 Property: assert Result: ✅ pass -Obligation: bytes_to_nat_body_calls_Sequence.select_0 -Property: out-of-bounds access check -Result: ✅ pass - -Obligation: bytes_to_nat_body_calls_Sequence.drop_1 -Property: out-of-bounds access check -Result: ✅ pass - Obligation: bytes_to_nat_terminates_0 Property: assert Result: ✅ pass @@ -192,6 +184,14 @@ Obligation: bytes_to_nat_terminates_1 Property: assert Result: ✅ pass +Obligation: bytes_to_nat_body_calls_Sequence.select_0 +Property: out-of-bounds access check +Result: ✅ pass + +Obligation: bytes_to_nat_body_calls_Sequence.drop_1 +Property: out-of-bounds access check +Result: ✅ pass + Obligation: test_rec_empty_ensures_15_2126 Property: assert Result: ✅ pass diff --git a/StrataBooleTest/global_readonly_call.lean b/StrataBooleTest/global_readonly_call.lean index 2277439..dc45ee9 100644 --- a/StrataBooleTest/global_readonly_call.lean +++ b/StrataBooleTest/global_readonly_call.lean @@ -129,19 +129,19 @@ true Label: callElimAssert_inc_requires_0_2575_6 Property: assert Assumptions: -main_caller_requires_2_2709: z@3 == 10 -main_caller_requires_3_2729: g@3 == 0 +main_caller_requires_2_2709: z@2 == 10 +main_caller_requires_3_2729: g@2 == 0 Obligation: -int.gt(z@3, 0) +int.gt(z@2, 0) Label: main_caller_ensures_4_2748 Property: assert Assumptions: -main_caller_requires_2_2709: z@3 == 10 -main_caller_requires_3_2729: g@3 == 0 -callElimAssume_inc_ensures_1_2593_7: g@5 == int.add(int.add(g@3, 5), z@5) +main_caller_requires_2_2709: z@2 == 10 +main_caller_requires_3_2729: g@2 == 0 +callElimAssume_inc_ensures_1_2593_7: g@3 == int.add(int.add(g@2, 5), z@3) Obligation: -g@5 == 15 +g@3 == 15 --- info: @@ -157,7 +157,7 @@ Obligation: main_caller_ensures_4_2748 Property: assert Result: ❓ unknown Model: -(g@5, 5) (g@3, 0) (z@3, 10) (z@5, 0)-/ +(g@3, 5) (g@2, 0) (z@2, 10) (z@3, 0)-/ #guard_msgs in #eval Strata.Boole.verify "cvc5" callerPgm diff --git a/StrataBooleTest/hoare_max2.lean b/StrataBooleTest/hoare_max2.lean index 1c0cc2b..07da890 100644 --- a/StrataBooleTest/hoare_max2.lean +++ b/StrataBooleTest/hoare_max2.lean @@ -5,12 +5,16 @@ -/ import StrataBoole.HoareLift import StrataBoole.MetaVerifier +import Strata.Languages.Core.ProgramProps /-! # `max2` against Core's Hoare logic, by hand -The first procedure proved on the Lean route of `docs/HoareLogic.md`. Everything the -tactic of step 1 will automate is written out once here; the lifting lemmas it uses -are in `StrataBoole.HoareLift`. +The first procedure proved on the Lean route of `docs/HoareLogic.md`: a Boole block, +lowered to Core inside Lean, whose contract is proved by applying Core's Hoare rules. +Everything the tactic of step 1 will automate is written out once here. Expressions are +evaluated denotationally, so the values of variables are semantic values and the +evaluation lemmas of `Strata.Languages.Core.IntEvalProps` and `StrataBoole.HoareLift` +turn each rule's goal into a fact about integers. -/ open Strata Lambda Core HoareLift @@ -42,15 +46,24 @@ def max2Proc : Core.Procedure := (max2Core.findProcByString? "max2").get! theorem max2_findProc : max2Core.findProcByString? "max2" = some max2Proc := by native_decide +abbrev E := Core.Expression.Expr def intTy : Option LMonoTy := some (.tcons "int" []) def xV : Core.Expression.Ident := ⟨"x", ()⟩ def yV : Core.Expression.Ident := ⟨"y", ()⟩ def rV : Core.Expression.Ident := ⟨"r", ()⟩ -/-- Metadata of the statements, read off the program so the shapes below are exact. -/ +/-- `a >= b`, `a && b`, `a || b` as the lowering writes them. -/ +abbrev geE (a b : E) : E := .app () (.app () Core.intGeOp a) b +abbrev andE (a b : E) : E := .app () (.app () Core.boolAndOp a) b +abbrev orE (a b : E) : E := .app () (.app () Core.boolOrOp a) b + +/-- The condition of the `if`. -/ +abbrev cond : E := geE (.fvar () xV intTy) (.fvar () yV intTy) + +/-- Metadata and labels of the statements and clauses, read off the program so the shapes + below are exact. -/ def max2Body : Core.Statements := match max2Proc.body with | .structured ss => ss | _ => [] - def md4 : Imperative.MetaData Core.Expression := match max2Body with | [.block _ _ md] => md | _ => #[] def md3 : Imperative.MetaData Core.Expression := @@ -62,180 +75,154 @@ def md2 : Imperative.MetaData Core.Expression := theorem max2_body_eq : max2Proc.body = .structured [.block "max2" - [.ite (.det (intGe (.fvar () xV intTy) (.fvar () yV intTy))) + [.ite (.det cond) [.cmd (.cmd (.set rV (.det (.fvar () xV intTy)) md1))] [.cmd (.cmd (.set rV (.det (.fvar () yV intTy)) md2))] md3] md4] := by native_decide -/-! ## The contract as a triple -/ - -/-- Gate parameters: no reserved prefixes, every operator counts as declared. -/ -def params : Core.Logic.InitEnvWFParams := ⟨[], fun _ => true⟩ - -theorem max2_checksTyped : Core.Logic.Hoare.Procedure.contractChecksTyped max2Proc := by - native_decide - -theorem max2_inputs : max2Proc.header.inputs.toList = [(xV, .tcons "int" []), (yV, .tcons "int" [])] := by - native_decide - -/-- `Bool.And a b` and `Bool.Or a b` as the lowering writes `a && b` and `a || b`. -/ -abbrev andE (a b : E) : E := - .app () (.app () (.op () ⟨"Bool.And", ()⟩ (some (.arrow .bool (.arrow .bool .bool)))) a) b -abbrev orE (a b : E) : E := - .app () (.app () (.op () ⟨"Bool.Or", ()⟩ (some (.arrow .bool (.arrow .bool .bool)))) a) b - -/-- The clause labels carry source offsets, so they are read off the program too. -/ def lbl0 : Core.CoreLabel := match max2Proc.spec.postconditions.toList with | (l, _) :: _ => l | _ => "" def lbl1 : Core.CoreLabel := match max2Proc.spec.postconditions.toList with | _ :: (l, _) :: _ => l | _ => "" - def mdP0 : Imperative.MetaData Core.Expression := match max2Proc.spec.postconditions.toList with | (_, c) :: _ => c.md | _ => #[] def mdP1 : Imperative.MetaData Core.Expression := match max2Proc.spec.postconditions.toList with | _ :: (_, c) :: _ => c.md | _ => #[] theorem max2_posts : max2Proc.spec.postconditions.toList = - [(lbl0, - { expr := andE (intGe (.fvar () rV intTy) (.fvar () xV intTy)) - (intGe (.fvar () rV intTy) (.fvar () yV intTy)), - attr := .Default, md := mdP0 }), - (lbl1, - { expr := orE (.eq () (.fvar () rV intTy) (.fvar () xV intTy)) - (.eq () (.fvar () rV intTy) (.fvar () yV intTy)), - attr := .Default, md := mdP1 })] := by + [(lbl0, { expr := andE (geE (.fvar () rV intTy) (.fvar () xV intTy)) + (geE (.fvar () rV intTy) (.fvar () yV intTy)), + attr := .Default, md := mdP0 }), + (lbl1, { expr := orE (.eq () (.fvar () rV intTy) (.fvar () xV intTy)) + (.eq () (.fvar () rV intTy) (.fvar () yV intTy)), + attr := .Default, md := mdP1 })] := by + native_decide + +theorem max2_inputs : max2Proc.header.inputs.toList = + [(xV, .tcons "int" []), (yV, .tcons "int" [])] := by native_decide -/-- A clause holds in every world once its captured form is a closed expression that - denotes `true` under every valuation. -/ -theorem check_of_captured (model : Lambda.Interp Core.Factory) - (ρ : Imperative.Env Core.Expression) (label : Core.CoreLabel) (check : Core.Procedure.Check) - (e : E) (hfac : ρ.factory = Core.Factory) - (hcap : Core.Logic.capturedExpr - { factory := ρ.factory, store := ρ.store, label := label, - expr := check.expr, metadata := check.md } = e) - (ht : LExpr.HasTypeA [] e .bool) - (hd : ∀ (fv : FreeVarVal CoreLParams model.tcInterp) (vt : TyVarVal), - LExpr.denote model.tcInterp model.opInterp fv vt .nil e .bool ht = true) : - Core.Logic.Hoare.Procedure.checkAsPredicate model ρ label check := by - intro world - refine Or.inl ⟨hfac, ?_⟩ - rw [hcap] - exact ⟨ht, hd _ _⟩ - -/-- The two `ensures` clauses, read in every world of `model`, once the store binds the - three variables to integer literals satisfying them. -/ -theorem max2_post (model : Lambda.Interp Core.Factory) (ρ : Imperative.Env Core.Expression) - (a b c : Int) (hfac : ρ.factory = Core.Factory) - (hx : ρ.store xV = some (.intConst () a)) (hy : ρ.store yV = some (.intConst () b)) - (hr : ρ.store rV = some (.intConst () c)) +theorem max2_checksTyped : Core.Logic.Hoare.Procedure.contractChecksTyped max2Proc := by + native_decide + +/-- No function precedes `max2`, so its visible factory is `Core.Factory`. -/ +theorem max2_factory : max2Core.factoryBeforeProcedure "max2" = Core.Factory := + Core.Program.factoryBeforeProcedure_eq_core_of_noFunctions (by native_decide) + +/-- Gate parameters: no reserved prefixes, every operator counts as declared. -/ +def params : Core.Logic.InitEnvWFParams := ⟨[], fun _ => true⟩ + +/-! ## The values of the inputs -/ + +/-- An integer value of the environment's factory. -/ +abbrev intV (f : Core.Expression.Factory) (n : Int) : Core.Expression.Val := + SemValue.ofInt f.model.tcInterp n + +/-- Inside either branch the condition has evaluated, which binds `x` and `y` to values of + the factory; with their declared type `int` they are integers. -/ +theorem inputs_of_cond (ρ : Imperative.Env Core.Expression) {b : Bool} + (hpre : Core.Logic.Hoare.Procedure.contractPre Core.Factory max2Proc ρ) + (hcond : Core.Expression.eval ρ.factory ρ.store cond = + some (SemValue.ofBool ρ.factory.model.tcInterp b)) : + ρ.factory.factory = Core.Factory ∧ + ∃ a c : Int, ρ.store xV = some (intV ρ.factory a) ∧ ρ.store yV = some (intV ρ.factory c) := by + obtain ⟨-, hfac, -, hin⟩ := hpre + refine ⟨hfac, ?_⟩ + obtain ⟨vx, hx, hsx⟩ := hin xV (.tcons "int" []) (by rw [max2_inputs]; simp) + obtain ⟨vy, hy, hsy⟩ := hin yV (.tcons "int" []) (by rw [max2_inputs]; simp) + have hd := Lambda.LExpr.denoteEval_defines hcond + have hvars : ∀ z ∈ [xV, yV], z ∈ Lambda.LExpr.LExpr.getVars cond := by + simp [Lambda.LExpr.LExpr.getVars, Core.intGeOp, Lambda.WFLFunc.opExpr, + Lambda.LFunc.opExpr, Lambda.LFuncDefined.opExpr] + obtain ⟨wx, hwx, htx⟩ := hd xV (hvars xV (by simp)) + obtain ⟨wy, hwy, hty⟩ := hd yV (hvars yV (by simp)) + rw [hx] at hwx; cases hwx + rw [hy] at hwy; cases hwy + obtain ⟨a, ha⟩ := Lambda.SemValue.exists_ofInt hsx + obtain ⟨c, hc⟩ := Lambda.SemValue.exists_ofInt hsy + rw [ha, htx] at hx + rw [hc, hty] at hy + exact ⟨a, c, hx, hy⟩ + +/-- The condition's Boolean, once the inputs are known. -/ +theorem cond_eval (ρ : Imperative.Env Core.Expression) (a c : Int) + (hfac : ρ.factory.factory = Core.Factory) + (hx : ρ.store xV = some (intV ρ.factory a)) (hy : ρ.store yV = some (intV ρ.factory c)) : + Core.Expression.eval ρ.factory ρ.store cond = + some (SemValue.ofBool ρ.factory.model.tcInterp (decide (a ≥ c))) := + Core.eval_intGe (by rw [hfac]; exact Core.coreFactory_intGe) + (Core.eval_fvar_int (ty := intTy) _ hx) (Core.eval_fvar_int (ty := intTy) _ hy) + +/-! ## The postconditions -/ + +/-- The two `ensures` clauses hold in every world once the store binds `x`, `y` and `r` to + integers satisfying them. -/ +theorem max2_post (ρ : Imperative.Env Core.Expression) (a b c : Int) + (hfac : ρ.factory.factory = Core.Factory) + (hx : ρ.store xV = some (intV ρ.factory a)) (hy : ρ.store yV = some (intV ρ.factory b)) + (hr : ρ.store rV = some (intV ρ.factory c)) (h1 : c ≥ a) (h2 : c ≥ b) (h3 : c = a ∨ c = b) : - Core.Logic.Hoare.Procedure.contractPost model max2Proc ρ := by + Core.Logic.Hoare.Procedure.contractPost Core.Factory max2Proc ρ := by intro label check hmem _ rw [max2_posts] at hmem simp only [List.mem_cons, List.not_mem_nil, or_false, Prod.mk.injEq] at hmem - have hc : LExpr.HasTypeA [] (LExpr.intConst () c : E) LMonoTy.int := .const - have ha : LExpr.HasTypeA [] (LExpr.intConst () a : E) LMonoTy.int := .const - have hb : LExpr.HasTypeA [] (LExpr.intConst () b : E) LMonoTy.int := .const - rcases hmem with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩ - · refine check_of_captured model ρ _ _ - (andE (intGe (.intConst () c) (.intConst () a)) (intGe (.intConst () c) (.intConst () b))) - hfac ?_ (.app (.app .op (hasTypeA_intGe_consts c a)) (hasTypeA_intGe_consts c b)) ?_ - · simp [Core.Logic.capturedExpr, LExpr.substFvarsFromEnv, Lambda.Env.mk, hx, hy, hr, intGe] - · intro fv vt - rw [denote_boolAnd _ _ _ _ _ (hasTypeA_intGe_consts c a) (hasTypeA_intGe_consts c b), - denote_intGe_consts, denote_intGe_consts] - show (decide (c ≥ a) && decide (c ≥ b)) = true - simp [h1, h2] - · refine check_of_captured model ρ _ _ - (orE (.eq () (.intConst () c) (.intConst () a)) (.eq () (.intConst () c) (.intConst () b))) - hfac ?_ (.app (.app .op (.eq hc ha)) (.eq hc hb)) ?_ - · simp [Core.Logic.capturedExpr, LExpr.substFvarsFromEnv, Lambda.Env.mk, hx, hy, hr] - · intro fv vt - rw [denote_boolOr _ _ _ _ _ (.eq hc ha) (.eq hc hb), denote_eq_ints, denote_eq_ints] - show (decide (c = a) || decide (c = b)) = true - rcases h3 with rfl | rfl <;> simp - -/-- From `contractPre`: the inputs are integer literals. -/ -theorem max2_pre_ints (model : Lambda.Interp Core.Factory) (ρ : Imperative.Env Core.Expression) - (hpre : Core.Logic.Hoare.Procedure.contractPre model max2Proc ρ) : - ρ.factory = Core.Factory ∧ - ∃ a b : Int, ρ.store xV = some (.intConst () a) ∧ ρ.store yV = some (.intConst () b) := by - obtain ⟨-, hfac, -, hin⟩ := hpre - refine ⟨hfac, ?_⟩ - have hx := hin xV (.tcons "int" []) (by rw [max2_inputs]; simp) - have hy := hin yV (.tcons "int" []) (by rw [max2_inputs]; simp) - obtain ⟨vx, hvx, a, rfl⟩ := hx - obtain ⟨vy, hvy, b, rfl⟩ := hy - exact ⟨a, b, hvx, hvy⟩ - -/-- `Core.Logic.Hoare.set` where the right-hand side is a variable the store binds to an - integer literal: the assigned value is that literal. -/ -theorem set_int_var (π : String → Option Core.Procedure) (x src : Core.Expression.Ident) - (ty : Option LMonoTy) (md : Imperative.MetaData Core.Expression) - (Pre Post : Imperative.Env Core.Expression → Prop) - (hsrc : ∀ ρ₀, Pre ρ₀ → ∃ a : Int, ρ₀.store src = some (.intConst () a)) - (hpost : ∀ (ρ₀ : Imperative.Env Core.Expression) (σ' : Core.CoreStore) (a : Int), Pre ρ₀ → - ρ₀.store src = some (.intConst () a) → - σ' x = some (.intConst () a) → (∀ w, x ≠ w → σ' w = ρ₀.store w) → - Post { ρ₀ with store := σ' }) : - Core.Logic.Hoare.Triple π params Pre [Core.Statement.set x (.fvar () src ty) md] Post := - Core.Logic.Hoare.set π params x _ md Pre Post - (fun ρ₀ σ' v hpre hev hup => by - obtain ⟨a, ha⟩ := hsrc ρ₀ hpre - have hv : v = .intConst () a := (Option.some.injEq _ _).mp - (hev.symm.trans (Lambda.evalFully_fvar_of_value ρ₀.factory ρ₀.store () src ty _ ha - (Lambda.isValue_const_true _ _ _))) - subst hv - cases hup with - | update _hold hnew hoth => exact hpost ρ₀ σ' a hpre ha hnew hoth) + have er := Core.eval_fvar_int (ty := intTy) (m := ()) ρ.factory hx + have ex := Core.eval_fvar_int (ty := intTy) (m := ()) ρ.factory hx + have ey := Core.eval_fvar_int (ty := intTy) (m := ()) ρ.factory hy + have err := Core.eval_fvar_int (ty := intTy) (m := ()) ρ.factory hr + have hge : ρ.factory.factory["Int.Ge"]? = some (Lambda.intGeFunc (T := CoreLParams)).func := by + rw [hfac]; exact Core.coreFactory_intGe + rcases hmem with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩ <;> intro world <;> refine Or.inl ⟨hfac, ?_⟩ <;> + show Core.Expression.eval ρ.factory ρ.store _ = some (Imperative.HasBool.ttVal ρ.factory) + · rw [eval_boolAnd (by rw [hfac]; exact coreFactory_boolAnd) + (Core.eval_intGe hge err ex) (Core.eval_intGe hge err ey)] + simp [Imperative.HasBool.ttVal, h1, h2] + · rw [eval_boolOr (by rw [hfac]; exact coreFactory_boolOr) + (eval_eq_ints _ err ex) (eval_eq_ints _ err ey)] + rcases h3 with rfl | rfl <;> simp [Imperative.HasBool.ttVal] + +/-! ## The triple -/ theorem max2_triple : Core.Logic.Hoare.Procedure.contractTriple max2Core params "max2" := by refine Core.Logic.Hoare.Procedure.contractTriple_of_core_typed max2Core params "max2" max2Proc _ - max2_findProc max2_body_eq max2_checksTyped (fun model => ?_) + max2_findProc max2_body_eq max2_checksTyped ?_ + rw [max2_factory] -- the procedure block, then the labelled block - refine (Core.Logic.Hoare.block max2Core.findProcByString? params ?_ - (Imperative.Logic.Hoare.postWF_of_definedVars_nil _ (by native_decide))) model refine Core.Logic.Hoare.block max2Core.findProcByString? params ?_ (Imperative.Logic.Hoare.postWF_of_definedVars_nil _ (by native_decide)) - -- the if: each branch is one assignment whose value we know + refine Core.Logic.Hoare.block max2Core.findProcByString? params ?_ + (Imperative.Logic.Hoare.postWF_of_definedVars_nil _ (by native_decide)) + -- the if: one assignment per branch refine Core.Logic.Hoare.ite max2Core.findProcByString? params ?_ ?_ (Imperative.Logic.Hoare.postWF_of_definedVars_nil _ (by native_decide)) (Imperative.Logic.Hoare.postWF_of_definedVars_nil _ (by native_decide)) - · -- then: r := x under x >= y - refine set_int_var _ rV xV intTy md1 _ _ ?_ ?_ - · intro ρ₀ ⟨hpre, _⟩ - obtain ⟨_, a, b, hx, _⟩ := max2_pre_ints model ρ₀ hpre - exact ⟨a, hx⟩ - · intro ρ₀ σ' a ⟨hpre, hcond⟩ hxa hnew hoth - obtain ⟨hfac, a', b, hx, hy⟩ := max2_pre_ints model ρ₀ hpre - rw [hx] at hxa; cases hxa - have hge : b ≤ a := by - rw [hfac, show Core.Expression.eval = Lambda.LExpr.evalFully (TBase := CoreLParams) from rfl, - evalFully_intGe_store _ _ _ _ _ a b hx hy] at hcond - have htt : (Imperative.HasBool.tt : E) = .const () (.boolConst true) := rfl - simpa [htt, LExpr.boolConst] using hcond - have hne : rV ≠ xV := by decide - have hne' : rV ≠ yV := by decide - exact max2_post model _ a b a hfac (by simpa [hoth _ hne] using hx) - (by simpa [hoth _ hne'] using hy) hnew (Int.le_refl a) hge (Or.inl rfl) - · -- else: r := y under ¬ (x >= y) - refine set_int_var _ rV yV intTy md2 _ _ ?_ ?_ - · intro ρ₀ ⟨hpre, _⟩ - obtain ⟨_, a, b, _, hy⟩ := max2_pre_ints model ρ₀ hpre - exact ⟨b, hy⟩ - · intro ρ₀ σ' b ⟨hpre, hcond⟩ hyb hnew hoth - obtain ⟨hfac, a, b', hx, hy⟩ := max2_pre_ints model ρ₀ hpre - rw [hy] at hyb; cases hyb - have hlt : ¬ b ≤ a := by - rw [hfac, show Core.Expression.eval = Lambda.LExpr.evalFully (TBase := CoreLParams) from rfl, - evalFully_intGe_store _ _ _ _ _ a b hx hy] at hcond - have hff : (Imperative.HasBool.ff : E) = .const () (.boolConst false) := rfl - simpa [hff, LExpr.boolConst] using hcond - have hne : rV ≠ xV := by decide - have hne' : rV ≠ yV := by decide - exact max2_post model _ a b b hfac (by simpa [hoth _ hne] using hx) - (by simpa [hoth _ hne'] using hy) hnew (by omega) (Int.le_refl b) (Or.inr rfl) + · -- then: r := x, under x >= y + refine Core.Logic.Hoare.set max2Core.findProcByString? params rV _ md1 _ _ ?_ + intro ρ₀ σ' v ⟨hpre, hcond⟩ hev hup + obtain ⟨hfac, a, c, hx, hy⟩ := inputs_of_cond ρ₀ hpre hcond + have hge : a ≥ c := of_decide_eq_true (Lambda.SemValue.ofBool_injective + (Option.some.inj ((cond_eval ρ₀ a c hfac hx hy).symm.trans hcond))) + have hv : v = intV ρ₀.factory a := + Option.some.inj (hev.symm.trans (Core.eval_fvar_int (ty := intTy) _ hx)) + subst hv + cases hup with + | update _ hnew hoth => + exact max2_post { ρ₀ with store := σ' } a c a hfac + ((hoth xV (by decide)).trans hx) ((hoth yV (by decide)).trans hy) hnew + (Int.le_refl a) hge (Or.inl rfl) + · -- else: r := y, under not (x >= y) + refine Core.Logic.Hoare.set max2Core.findProcByString? params rV _ md2 _ _ ?_ + intro ρ₀ σ' v ⟨hpre, hcond⟩ hev hup + obtain ⟨hfac, a, c, hx, hy⟩ := inputs_of_cond ρ₀ hpre hcond + have hlt : ¬ a ≥ c := of_decide_eq_false (Lambda.SemValue.ofBool_injective + (Option.some.inj ((cond_eval ρ₀ a c hfac hx hy).symm.trans hcond))) + have hv : v = intV ρ₀.factory c := + Option.some.inj (hev.symm.trans (Core.eval_fvar_int (ty := intTy) _ hy)) + subst hv + cases hup with + | update _ hnew hoth => + exact max2_post { ρ₀ with store := σ' } a c c hfac + ((hoth xV (by decide)).trans hx) ((hoth yV (by decide)).trans hy) hnew + (by omega) (Int.le_refl c) (Or.inr rfl) end HoareMax2 - diff --git a/StrataBooleTest/nat_counterexample.lean b/StrataBooleTest/nat_counterexample.lean index 068ebf1..2ca9269 100644 --- a/StrataBooleTest/nat_counterexample.lean +++ b/StrataBooleTest/nat_counterexample.lean @@ -34,19 +34,19 @@ spec { ensures nat_toInt(a) < nat_toInt(b); } #end /-- info: -Obligation: pos.toInt_body_calls_pos..xO_h_0 +Obligation: pos.toInt_terminates_0 Property: assert Result: ✅ pass -Obligation: pos.toInt_body_calls_pos..xI_h_1 +Obligation: pos.toInt_terminates_1 Property: assert Result: ✅ pass -Obligation: pos.toInt_terminates_0 +Obligation: pos.toInt_body_calls_pos..xO_h_0 Property: assert Result: ✅ pass -Obligation: pos.toInt_terminates_1 +Obligation: pos.toInt_body_calls_pos..xI_h_1 Property: assert Result: ✅ pass @@ -100,19 +100,19 @@ spec { #end /-- info: -Obligation: pos.toInt_body_calls_pos..xO_h_0 +Obligation: pos.toInt_terminates_0 Property: assert Result: ✅ pass -Obligation: pos.toInt_body_calls_pos..xI_h_1 +Obligation: pos.toInt_terminates_1 Property: assert Result: ✅ pass -Obligation: pos.toInt_terminates_0 +Obligation: pos.toInt_body_calls_pos..xO_h_0 Property: assert Result: ✅ pass -Obligation: pos.toInt_terminates_1 +Obligation: pos.toInt_body_calls_pos..xI_h_1 Property: assert Result: ✅ pass diff --git a/StrataBooleTest/nat_counterexample_extended.lean b/StrataBooleTest/nat_counterexample_extended.lean index 18d3b7f..14249d2 100644 --- a/StrataBooleTest/nat_counterexample_extended.lean +++ b/StrataBooleTest/nat_counterexample_extended.lean @@ -37,19 +37,19 @@ spec { #end /-- info: -Obligation: pos.toInt_body_calls_pos..xO_h_0 +Obligation: pos.toInt_terminates_0 Property: assert Result: ✅ pass -Obligation: pos.toInt_body_calls_pos..xI_h_1 +Obligation: pos.toInt_terminates_1 Property: assert Result: ✅ pass -Obligation: pos.toInt_terminates_0 +Obligation: pos.toInt_body_calls_pos..xO_h_0 Property: assert Result: ✅ pass -Obligation: pos.toInt_terminates_1 +Obligation: pos.toInt_body_calls_pos..xI_h_1 Property: assert Result: ✅ pass @@ -145,19 +145,19 @@ spec { #end /-- info: -Obligation: pos.toInt_body_calls_pos..xO_h_0 +Obligation: pos.toInt_terminates_0 Property: assert Result: ✅ pass -Obligation: pos.toInt_body_calls_pos..xI_h_1 +Obligation: pos.toInt_terminates_1 Property: assert Result: ✅ pass -Obligation: pos.toInt_terminates_0 +Obligation: pos.toInt_body_calls_pos..xO_h_0 Property: assert Result: ✅ pass -Obligation: pos.toInt_terminates_1 +Obligation: pos.toInt_body_calls_pos..xI_h_1 Property: assert Result: ✅ pass @@ -214,19 +214,19 @@ spec { #end /-- info: -Obligation: pos.toInt_body_calls_pos..xO_h_0 +Obligation: pos.toInt_terminates_0 Property: assert Result: ✅ pass -Obligation: pos.toInt_body_calls_pos..xI_h_1 +Obligation: pos.toInt_terminates_1 Property: assert Result: ✅ pass -Obligation: pos.toInt_terminates_0 +Obligation: pos.toInt_body_calls_pos..xO_h_0 Property: assert Result: ✅ pass -Obligation: pos.toInt_terminates_1 +Obligation: pos.toInt_body_calls_pos..xI_h_1 Property: assert Result: ✅ pass diff --git a/StrataBooleTest/nat_detection.lean b/StrataBooleTest/nat_detection.lean index 24a5f12..72660ad 100644 --- a/StrataBooleTest/nat_detection.lean +++ b/StrataBooleTest/nat_detection.lean @@ -51,19 +51,19 @@ spec { ensures r >= 0; } #end /-- info: -Obligation: pos.toInt_body_calls_pos..xO_h_0 +Obligation: pos.toInt_terminates_0 Property: assert Result: ✅ pass -Obligation: pos.toInt_body_calls_pos..xI_h_1 +Obligation: pos.toInt_terminates_1 Property: assert Result: ✅ pass -Obligation: pos.toInt_terminates_0 +Obligation: pos.toInt_body_calls_pos..xO_h_0 Property: assert Result: ✅ pass -Obligation: pos.toInt_terminates_1 +Obligation: pos.toInt_body_calls_pos..xI_h_1 Property: assert Result: ✅ pass @@ -111,19 +111,19 @@ spec { requires 0 <= n; } #end /-- info: -Obligation: pos.toInt_body_calls_pos..xO_h_0 +Obligation: pos.toInt_terminates_0 Property: assert Result: ✅ pass -Obligation: pos.toInt_body_calls_pos..xI_h_1 +Obligation: pos.toInt_terminates_1 Property: assert Result: ✅ pass -Obligation: pos.toInt_terminates_0 +Obligation: pos.toInt_body_calls_pos..xO_h_0 Property: assert Result: ✅ pass -Obligation: pos.toInt_terminates_1 +Obligation: pos.toInt_body_calls_pos..xI_h_1 Property: assert Result: ✅ pass @@ -172,19 +172,19 @@ spec { #end /-- info: -Obligation: pos.toInt_body_calls_pos..xO_h_0 +Obligation: pos.toInt_terminates_0 Property: assert Result: ✅ pass -Obligation: pos.toInt_body_calls_pos..xI_h_1 +Obligation: pos.toInt_terminates_1 Property: assert Result: ✅ pass -Obligation: pos.toInt_terminates_0 +Obligation: pos.toInt_body_calls_pos..xO_h_0 Property: assert Result: ✅ pass -Obligation: pos.toInt_terminates_1 +Obligation: pos.toInt_body_calls_pos..xI_h_1 Property: assert Result: ✅ pass diff --git a/StrataBooleTest/nat_native.lean b/StrataBooleTest/nat_native.lean index e9f12f0..360f5f2 100644 --- a/StrataBooleTest/nat_native.lean +++ b/StrataBooleTest/nat_native.lean @@ -43,19 +43,19 @@ spec { #end /-- info: -Obligation: pos.toInt_body_calls_pos..xO_h_0 +Obligation: pos.toInt_terminates_0 Property: assert Result: ✅ pass -Obligation: pos.toInt_body_calls_pos..xI_h_1 +Obligation: pos.toInt_terminates_1 Property: assert Result: ✅ pass -Obligation: pos.toInt_terminates_0 +Obligation: pos.toInt_body_calls_pos..xO_h_0 Property: assert Result: ✅ pass -Obligation: pos.toInt_terminates_1 +Obligation: pos.toInt_body_calls_pos..xI_h_1 Property: assert Result: ✅ pass @@ -148,19 +148,19 @@ spec { #end /-- info: -Obligation: pos.toInt_body_calls_pos..xO_h_0 +Obligation: pos.toInt_terminates_0 Property: assert Result: ✅ pass -Obligation: pos.toInt_body_calls_pos..xI_h_1 +Obligation: pos.toInt_terminates_1 Property: assert Result: ✅ pass -Obligation: pos.toInt_terminates_0 +Obligation: pos.toInt_body_calls_pos..xO_h_0 Property: assert Result: ✅ pass -Obligation: pos.toInt_terminates_1 +Obligation: pos.toInt_body_calls_pos..xI_h_1 Property: assert Result: ✅ pass diff --git a/StrataBooleTest/stack_array_based.lean b/StrataBooleTest/stack_array_based.lean index 5c8d2c7..4af4ded 100644 --- a/StrataBooleTest/stack_array_based.lean +++ b/StrataBooleTest/stack_array_based.lean @@ -134,51 +134,51 @@ true Label: StackEmpty_ensures_3_1210 Property: assert Assumptions: -: if top@3 == 0 then top@3 == 0 else true -: if if top@3 == 0 then false else true then if top@3 == 0 then false else true else true +: if top@2 == 0 then top@2 == 0 else true +: if if top@2 == 0 then false else true then if top@2 == 0 then false else true else true Obligation: -(if top@3 == 0 then true else false) ==> top@3 == 0 +(if top@2 == 0 then true else false) ==> top@2 == 0 Label: StackEmpty_ensures_4_1238 Property: assert Assumptions: -: if top@3 == 0 then top@3 == 0 else true -: if if top@3 == 0 then false else true then if top@3 == 0 then false else true else true +: if top@2 == 0 then top@2 == 0 else true +: if if top@2 == 0 then false else true then if top@2 == 0 then false else true else true Obligation: -top@3 == 0 ==> (if top@3 == 0 then true else false) +top@2 == 0 ==> (if top@2 == 0 then true else false) Label: Push_ensures_6_1499 Property: assert Assumptions: -Push_requires_5_1448: int.lt(top@4, n@4) +Push_requires_5_1448: int.lt(top@3, n@3) Obligation: true Label: Push_ensures_7_1530 Property: assert Assumptions: -Push_requires_5_1448: int.lt(top@4, n@4) +Push_requires_5_1448: int.lt(top@3, n@3) Obligation: -(S@3[int.add(top@4, 1):=x@1])[int.add(top@4, 1)] == x@1 +(S@3[int.add(top@3, 1):=x@1])[int.add(top@3, 1)] == x@1 Label: Push_ensures_8_1588 Property: assert Assumptions: -Push_requires_5_1448: int.lt(top@4, n@4) +Push_requires_5_1448: int.lt(top@3, n@3) Obligation: -forall __q0 : int :: int.le(1, __q0) && int.le(__q0, top@4) ==> (S@3[int.add(top@4, 1):=x@1])[__q0] == S@3[__q0] +forall __q0 : int :: int.le(1, __q0) && int.le(__q0, top@3) ==> (S@3[int.add(top@3, 1):=x@1])[__q0] == S@3[__q0] Label: Pop_ensures_10_1845 Property: assert Assumptions: -Pop_requires_9_1808: int.gt(top@6, 0) +Pop_requires_9_1808: int.gt(top@4, 0) Obligation: true Label: Pop_ensures_11_1876 Property: assert Assumptions: -Pop_requires_9_1808: int.gt(top@6, 0) +Pop_requires_9_1808: int.gt(top@4, 0) Obligation: true diff --git a/docs/HoareLogic.md b/docs/HoareLogic.md index a6a6247..8bc2b96 100644 --- a/docs/HoareLogic.md +++ b/docs/HoareLogic.md @@ -37,12 +37,20 @@ Core over Core's own operational semantics: with `old` snapshots and typed parameters, and the generic `SpecHoareConnection` (`Strata/DL/Imperative/Logic/`), which relates a triple to Strata's own notion of assertion validity. -- Conditions are interpreted with `LExpr.denote`; statements evaluate expressions with - `Expression.eval` over `Core.Factory`. +- Since November 2026, expressions are evaluated denotationally: `Expression.eval` is + `LExpr.denoteEval` over a modeled factory (the factory, a model of it, and the sorts of + its type variables), and stores hold semantic values. Every model satisfies the factory + axioms, and `Core.factoryInterp` is one such model (maps as functions, sequences as + lists, sets as predicates), so the triple is never vacuous. The functions declared + before a procedure are part of its factory (`Program.factoryBeforeProcedure`), and + `contractTriple` carries the typing of the contract. +- Lifting lemmas for the `int` and `bv` operators, free variables, `==` and `if` + (`IntEvalProps.lean`, `BitVecEvalProps.lean`): the evaluator on values is the Lean + operation in every model. Its tests prove some twenty procedures by applying the rules by hand, with `native_decide` -for facts about the AST. There is no automation and no lifting: a goal reads -`Expression.eval ρ.factory ρ.store e = some v`, not `x ≥ y`. +for facts about the AST. There is no automation: a goal reads +`Expression.eval ρ.factory ρ.store e = some v` until the lemmas are applied. Its authors confirmed (October 2026) that the triple was written as the specification of partial correctness, the invariant a correct program transformation must preserve, and @@ -59,21 +67,21 @@ So the tactic below is ours to build, and the triple is a stable target. the store. This is the shape of `core_vcgen` in the `StrataBoole/Deep/` experiment (fork branch `exp/deep-embedding`), retargeted from its own `Exec` to Strata's `Triple`. 2. **Lifting.** Turn each goal into a proposition over Lean values: a store slot of type - `int` is an `Int` (`inputAsPredicate` gives the literal), `Expression.eval` of an - operator on literals is the Lean operation (one lemma per operator, none in Strata yet), - and a contract clause under `denote` becomes the corresponding proposition. This is - the shape of `core_lift`. The interpreter prototype's `Model.lean` and `Sort.lean`, a - concrete interpretation of Core's types and operators over `LExpr.denote`, carry over - as this layer. Milestone: `max2`, then the counting loop of `demo.lean`, proved by the - tactic, lifting, and `omega`/`grind`; `find_max` once `Map` is in (see Risks). + `int` is an `Int` (`inputAsPredicate` and `SemValue.exists_ofInt`), `Expression.eval` + of an operator on values is the Lean operation (Strata's lemmas for `int` and `bv`, + ours for `Bool.And`, `Bool.Or` and `==` on integers in `StrataBoole/HoareLift.lean`), + and a contract clause becomes the corresponding proposition. Still to write: the + lemmas for `Map` and `Sequence` operators, which follow from the factory axioms every + model satisfies, and for quantifiers. This is the shape of `core_lift`. Milestone: + `max2`, then the counting loop of `demo.lean`, then `find_max`, proved by the tactic, + lifting, and `omega`/`grind`. 3. **Boole entry.** The prototype's `shallow_reflect` (on its fork branch) already produces the type-checked Core program as a Lean term. It is the input of step 1, so a user writes a `#strata program Boole` block and states `contractTriple` on its procedures. 4. **Gaps shared with Strata, fixed in Strata.** Rules for nondeterministic `if` and - `while`; the program's own declarations in the model, that is its functions (with - bodies, recursive ones included), its uninterpreted functions and its axioms, which - `Triple` does not see today; the generic datatype carrier wired into the model - (decision below), which also covers `nat`; `Map` and `Sequence` (see Risks). + `while`; the program's uninterpreted functions and axioms in the model (its functions + with bodies are in since November 2026); the generic datatype carrier wired into the + model (decision below), which also covers `nat`. 5. **Boole semantics.** A Boole interpreter proved to agree with `toCoreProgram`, so that Boole has a meaning stated in its own terms and the lowering to Core is proved correct rather than definitional. This is what makes Boole a language rather than a front end. @@ -119,10 +127,11 @@ So the tactic below is ours to build, and the triple is a stable target. | --- | --- | | assignments, `init`, `assert`, `assume`, `havoc` (as `set x *` through `cmd`), blocks, `exit`, deterministic `if` and `while`, `call` | rules exist | | `if *`, `while *`, loop measures, `cover` | to add | -| `int`, `bool`, `bv n` | denoted; lifting lemmas to add (step 2) | -| `Map`, `Sequence`, `string` operators | not usable yet: no value forms in the evaluator, and the triple quantifies over models that need not satisfy their axioms (see Risks) | +| `int`, `bool`, `bv n` | denoted and lifted | +| `Map`, `Sequence`, `Set`, `string` operators | modelled, every model satisfies their axioms; lifting lemmas to add (step 2) | | datatypes, `nat` | generic carrier (decision above); wiring into the model is step 4 | -| user functions | step 4, Strata's TODO on the model factory | +| user functions with bodies | in the model (`factoryBeforeProcedure`) | +| uninterpreted functions, `axiom` | step 4 | ## Target: the benchmark the solver path already verifies @@ -134,9 +143,10 @@ program this route has to reach. What it uses, and where each item sits: | `for` loop with six invariants, `call` in the body, `exit` | rules exist; the tactic must discharge the loop and call side conditions | 1 | | integer and `bv W8` arithmetic, `as_uint`, comparisons | lifting lemmas per operator | 2 | | quantified `requires` and invariants | lifting of `denote` on quantifiers to Lean `∀` over `Int` | 2 | -| `Sequence (bv W8)` and `Sequence Scalar`, `select`, `length` | a model and value forms in Strata | 4 | +| `Sequence (bv W8)` and `Sequence Scalar`, `select`, `length` | lifting lemmas from the sequence axioms | 2 | | native `nat`, the `nat_*` library | the generic carrier in the model, library functions as program functions | 4 | -| `function` definitions, one `rec function` with `requires` and `decreases`, `function f();` without body | program declarations in the model | 4 | +| `function` definitions, one `rec function` with `requires` and `decreases` | in the model | done | +| `function f();` without body | uninterpreted functions in the model | 4 | | `axiom` declarations, including the unfolding axiom of the recursive function | program axioms as hypotheses on the model | 4 | | a callee whose body is `assume false` | `call_of_contract` with a trivially proved contract | 1 | @@ -149,16 +159,16 @@ Everything in steps 1 to 3 is exercised by the first two and reused unchanged by ## Status -- `max2` is proved against Strata's triple, by hand, in `StrataBooleTest/hoare_max2.lean`: - `contractTriple_of_core_typed`, then `block`, `block`, `ite` and `set`, every side - condition by `native_decide` on the reflected program. The lifting lemmas it uses are - in `StrataBoole/HoareLift.lean`: the evaluator on `Int.Ge` over a store of literals - (one unfolding of `LExpr.eval.eq_2` plus the factory entry's facts), and the denotation - of `Int.Ge`, `Bool.And`, `Bool.Or` and `==` on literals in every model, each from the - model's agreement with the operator's concrete evaluation. The proof is the - specification of the step 1 tactic: it does these steps for any straight-line body with - `if`. Steps 1 and 2 as automation: not started. `Deep/` has both against its own - semantics, with `max2` and a counting loop proved. +- `max2` is proved against Strata's triple, by hand, in `StrataBooleTest/hoare_max2.lean` + on the denotational semantics: `contractTriple_of_core_typed`, then `block`, `block`, + `ite` and `set`, every side condition by `native_decide` on the reflected program, the + inputs recovered from the condition's evaluation (`denoteEval_defines`), the operators + lifted with Strata's `eval_intGe` and `eval_fvar_int` and our `eval_boolAnd`, + `eval_boolOr` and `eval_eq_ints` (`StrataBoole/HoareLift.lean`, each from the model's + agreement with the operator's concrete evaluation). The proof is the specification of + the step 1 tactic: it does these steps for any straight-line body with `if`. Steps 1 + and 2 as automation: not started. `Deep/` has both against its own semantics, with + `max2` and a counting loop proved. - `StrataBoole/Shallow/Layer.lean` is kept until the milestone is reached. - Two things the hand proof settled. Under the module system, facts about factory entries are not `rfl`; they need `import all` of the defining files and `simp` unfolding. And @@ -168,22 +178,12 @@ Everything in steps 1 to 3 is exercised by the first two and reused unchanged by - `StrataBooleTest/generic_datatypes.lean`: first prototype of the carrier. - Risks. Strata's own hand proof of a two-branch `if` is some twenty-five lines with `native_decide` and explicit store facts, so discharging the side conditions - automatically is the bulk of step 1. Step 4 also waits on Strata carrying the - typed-contract invariant as a hypothesis of `contractTriple`. -- `Map` and `Sequence` are outside the Hoare logic today, for two reasons that both - need a Strata change. First, `set` and `init` require `Expression.eval` to return a - value, and `evalFully` returns `none` for a full application of an operator without a - concrete evaluation (`select`, `update`, the sequence and string operators), so - `x := m[0]` has no execution and its triple holds for any postcondition. Second, - `Triple` quantifies over every `Lambda.Interp`, which must agree with function bodies - and concrete evaluations but not with the factory axioms, so nothing about - `m[k := v][k]` is provable in any case. The fix is to give these operators a fixed - interpretation in the model (maps as functions, sequences as lists) together with - value forms for the evaluator, or to interpret `set` and `init` through `denote`. - `Strata/Languages/Core/ProgramEval.lean` already has the evaluation of `select` over - `update`/`mapConst` terms for the concrete interpreter. Until this lands the tactic - refuses such statements, and the milestone is an integer program with a loop - (`demo.lean`'s), not `find_max`. + automatically is the bulk of step 1. +- `Map` and `Sequence` were outside the logic until November 2026: the fuel evaluator had + no value forms for their operators, so `x := m[0]` had no execution, and models did not + have to satisfy the factory axioms (strata-org/Strata#1496). Both are fixed by the + denotational evaluation above. The only remaining work on them is ours: the lifting + lemmas of step 2. ## Open questions @@ -191,9 +191,6 @@ Everything in steps 1 to 3 is exercised by the first two and reused unchanged by check `decreases` separately? - `cover` is a reachability check, not a Hoare fact. How to state it? - Goal names: carry the program's clause names into the goals the tactic leaves. -- Evaluator vacuity (see Risks): evaluation rules for `Map` and `Sequence` operators, or - `set`/`init` through `denote`? The second keeps one interpretation for expressions - everywhere; the first keeps Strata's semantics unchanged. - `native_decide` for AST facts: acceptable in the tactic, or avoid it? ## Sources diff --git a/lake-manifest.json b/lake-manifest.json index 74d8566..c939133 100644 --- a/lake-manifest.json +++ b/lake-manifest.json @@ -15,10 +15,10 @@ "type": "git", "subDir": null, "scope": "", - "rev": "f8be6585bb98db5a4b4033f36db5130a2679c9ad", + "rev": "91bb455326b6ebc8c7fd1edb753b2ea1ff63474c", "name": "Strata", "manifestFile": "lake-manifest.json", - "inputRev": "f8be6585b", + "inputRev": "91bb45532", "inherited": false, "configFile": "lakefile.toml"}, {"url": "https://github.com/leanprover-community/mathlib4.git", @@ -65,7 +65,7 @@ "type": "git", "subDir": null, "scope": "", - "rev": "6ca7dbdf5738571a0f6e7cd7d6bc917206797549", + "rev": "b70e35961b1c8179d278d44fecc8d4101a2ed46a", "name": "StrataDDM", "manifestFile": "lake-manifest.json", "inputRev": "main", diff --git a/lakefile.toml b/lakefile.toml index c793c60..d1c48ec 100644 --- a/lakefile.toml +++ b/lakefile.toml @@ -12,7 +12,7 @@ name = "Strata" # pass, public denote lemmas, datatypes to Lean). It moves back to strata-org/Strata when # they merge. A fixed commit, not a branch name, so `lake update` cannot move it. git = "https://github.com/kondylidou/Strata" -rev = "f8be6585b" +rev = "91bb45532" [[require]] name = "smt" From 58d1bf682343e5a2c95ca22fd40ccf7e22c8bc99 Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Tue, 10 Nov 2026 13:02:30 +0100 Subject: [PATCH 30/64] fix --- docs/HoareLogic.md | 44 +++++++++++++++++++++----------------------- 1 file changed, 21 insertions(+), 23 deletions(-) diff --git a/docs/HoareLogic.md b/docs/HoareLogic.md index 8bc2b96..87dc363 100644 --- a/docs/HoareLogic.md +++ b/docs/HoareLogic.md @@ -29,21 +29,21 @@ flowchart TD `Strata/Languages/Core/Logic/` (on Strata `main` since September 2026) is a Hoare logic for Core over Core's own operational semantics: -- `Core.Logic.Hoare.Triple π params Pre ss Post`, quantified over every model of the - program's uninterpreted symbols (`Lambda.Interp Core.Factory`). +- `Core.Logic.Hoare.Triple π params Pre ss Post factory`, quantified over every model + of `factory` (`Lambda.Interp`). A model satisfies the factory's axioms, and + `Core.factoryInterp` is one (maps as functions, sequences as lists, sets as predicates), + so the triple is never vacuous. - Proved rules for `cmd`, `set`, `init`, `seq`, `block`, `exit_cons`, `ite`, `while_rule` (partial correctness) and `Procedure.call_of_contract`. - `Procedure.contractTriple`, which reads `requires` and `ensures` as the triple to prove, - with `old` snapshots and typed parameters, and the generic `SpecHoareConnection` - (`Strata/DL/Imperative/Logic/`), which relates a triple to Strata's own notion of - assertion validity. -- Since November 2026, expressions are evaluated denotationally: `Expression.eval` is - `LExpr.denoteEval` over a modeled factory (the factory, a model of it, and the sorts of - its type variables), and stores hold semantic values. Every model satisfies the factory - axioms, and `Core.factoryInterp` is one such model (maps as functions, sequences as - lists, sets as predicates), so the triple is never vacuous. The functions declared - before a procedure are part of its factory (`Program.factoryBeforeProcedure`), and - `contractTriple` carries the typing of the contract. + with `old` snapshots, typed parameters and typed clauses, over the factory visible at + the procedure: Core's operators plus the functions declared before it + (`Program.factoryBeforeProcedure`). The generic `SpecHoareConnection` + (`Strata/DL/Imperative/Logic/`) relates a triple to Strata's own notion of assertion + validity. +- Expressions are evaluated denotationally (since November 2026): `Expression.eval` is + `LExpr.denoteEval` over the factory, a model of it and the sorts of its type variables, + and stores hold semantic values. - Lifting lemmas for the `int` and `bv` operators, free variables, `==` and `if` (`IntEvalProps.lean`, `BitVecEvalProps.lean`): the evaluator on values is the Lean operation in every model. @@ -68,11 +68,11 @@ So the tactic below is ours to build, and the triple is a stable target. branch `exp/deep-embedding`), retargeted from its own `Exec` to Strata's `Triple`. 2. **Lifting.** Turn each goal into a proposition over Lean values: a store slot of type `int` is an `Int` (`inputAsPredicate` and `SemValue.exists_ofInt`), `Expression.eval` - of an operator on values is the Lean operation (Strata's lemmas for `int` and `bv`, - ours for `Bool.And`, `Bool.Or` and `==` on integers in `StrataBoole/HoareLift.lean`), - and a contract clause becomes the corresponding proposition. Still to write: the - lemmas for `Map` and `Sequence` operators, which follow from the factory axioms every - model satisfies, and for quantifiers. This is the shape of `core_lift`. Milestone: + of an operator on values is the Lean operation (Strata's lemmas, plus ours for the + Boolean connectives and `==` in `StrataBoole/HoareLift.lean`), and a contract clause + becomes the corresponding proposition. Still to write: the lemmas for `Map` and + `Sequence` operators, which follow from the factory axioms, and for quantifiers. This + is the shape of `core_lift`. Milestone: `max2`, then the counting loop of `demo.lean`, then `find_max`, proved by the tactic, lifting, and `omega`/`grind`. 3. **Boole entry.** The prototype's `shallow_reflect` (on its fork branch) already produces @@ -142,7 +142,7 @@ program this route has to reach. What it uses, and where each item sits: | --- | --- | --- | | `for` loop with six invariants, `call` in the body, `exit` | rules exist; the tactic must discharge the loop and call side conditions | 1 | | integer and `bv W8` arithmetic, `as_uint`, comparisons | lifting lemmas per operator | 2 | -| quantified `requires` and invariants | lifting of `denote` on quantifiers to Lean `∀` over `Int` | 2 | +| quantified `requires` and invariants | lifting of quantifiers to Lean `∀` over `Int` | 2 | | `Sequence (bv W8)` and `Sequence Scalar`, `select`, `length` | lifting lemmas from the sequence axioms | 2 | | native `nat`, the `nat_*` library | the generic carrier in the model, library functions as program functions | 4 | | `function` definitions, one `rec function` with `requires` and `decreases` | in the model | done | @@ -179,11 +179,9 @@ Everything in steps 1 to 3 is exercised by the first two and reused unchanged by - Risks. Strata's own hand proof of a two-branch `if` is some twenty-five lines with `native_decide` and explicit store facts, so discharging the side conditions automatically is the bulk of step 1. -- `Map` and `Sequence` were outside the logic until November 2026: the fuel evaluator had - no value forms for their operators, so `x := m[0]` had no execution, and models did not - have to satisfy the factory axioms (strata-org/Strata#1496). Both are fixed by the - denotational evaluation above. The only remaining work on them is ours: the lifting - lemmas of step 2. +- `Map` and `Sequence` were outside the logic until November 2026 (strata-org/Strata#1496: + their operators had no execution, and models were free to violate the axioms). The + denotational evaluation fixed both; what remains is the lifting lemmas of step 2. ## Open questions From e36a937b3da7c55c88cfa4ac81d82b66e1c2a34f Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Tue, 10 Nov 2026 22:11:54 +0100 Subject: [PATCH 31/64] fix --- docs/HoareLogic.md | 316 ++++++++++++++++++++++++--------------------- 1 file changed, 168 insertions(+), 148 deletions(-) diff --git a/docs/HoareLogic.md b/docs/HoareLogic.md index 87dc363..5458d85 100644 --- a/docs/HoareLogic.md +++ b/docs/HoareLogic.md @@ -3,11 +3,12 @@ ## Goal Verify Boole programs in Lean with proofs that are sound by construction. Today's Lean -path trusts the VC generator, the SMT encoding and a bridge axiom; strata-org/Strata#1488 -showed it could prove `False`, and strata-org/Strata#1490 closed that by refusing every -VC the denotation does not cover. Here the trusted parts are Core's semantics and Lean, and the -goals range over Lean values, so Lean tactics work on them without a solver. Boole programs -reach it through their lowering to Core. +path, `gen_smt_vcs_boole`, trusts the VC generator, the SMT encoding and a bridge axiom; +strata-org/Strata#1488 showed it could prove `False`, and strata-org/Strata#1490 closed +that by refusing every VC the denotation does not cover. This route aims to trust only +Core's semantics and Lean (see Trusted base). Its goals range over Lean values, so Lean +tactics work on them without a solver. Boole programs reach it through their lowering to +Core. ```mermaid flowchart TD @@ -24,172 +25,191 @@ flowchart TD O["Core operational semantics"] -. rules are theorems about it .- H ``` -## What Strata already provides +## What Strata provides -`Strata/Languages/Core/Logic/` (on Strata `main` since September 2026) is a Hoare logic for -Core over Core's own operational semantics: +`Strata/Languages/Core/Logic/` is a Hoare logic for Core over Core's own operational +semantics: -- `Core.Logic.Hoare.Triple π params Pre ss Post factory`, quantified over every model - of `factory` (`Lambda.Interp`). A model satisfies the factory's axioms, and - `Core.factoryInterp` is one (maps as functions, sequences as lists, sets as predicates), - so the triple is never vacuous. -- Proved rules for `cmd`, `set`, `init`, `seq`, `block`, `exit_cons`, `ite`, `while_rule` +- `Triple π params Pre ss Post factory`, quantified over every model of `factory` + (`Lambda.Interp`). A model satisfies the factory's axioms. One is shown to exist for + Core's own factory (`Core.factoryInterp`: maps as functions, sequences as lists, sets as + predicates), none for a program's. +- Proved rules: `cmd`, `set`, `init`, `seq`, `block`, `exit_cons`, `ite`, `while_rule` (partial correctness) and `Procedure.call_of_contract`. -- `Procedure.contractTriple`, which reads `requires` and `ensures` as the triple to prove, - with `old` snapshots, typed parameters and typed clauses, over the factory visible at - the procedure: Core's operators plus the functions declared before it - (`Program.factoryBeforeProcedure`). The generic `SpecHoareConnection` - (`Strata/DL/Imperative/Logic/`) relates a triple to Strata's own notion of assertion - validity. -- Expressions are evaluated denotationally (since November 2026): `Expression.eval` is - `LExpr.denoteEval` over the factory, a model of it and the sorts of its type variables, - and stores hold semantic values. -- Lifting lemmas for the `int` and `bv` operators, free variables, `==` and `if` - (`IntEvalProps.lean`, `BitVecEvalProps.lean`): the evaluator on values is the Lean - operation in every model. - -Its tests prove some twenty procedures by applying the rules by hand, with `native_decide` -for facts about the AST. There is no automation: a goal reads -`Expression.eval ρ.factory ρ.store e = some v` until the lemmas are applied. - -Its authors confirmed (October 2026) that the triple was written as the specification of -partial correctness, the invariant a correct program transformation must preserve, and -that they have no plans to automate it. Generating verification conditions against it is -open to others, and they see no blocker once the generator's correctness is established. -So the tactic below is ours to build, and the triple is a stable target. +- `Procedure.contractTriple`: `requires` and `ensures` as the triple to prove, with `old` + snapshots and typed parameters and clauses. Its factory is Core's operators plus the + functions declared before the procedure, with or without body + (`Program.factoryBeforeProcedure`). Datatype declarations add nothing to it, and the + program's axioms are not in the precondition. +- Strata's notion of correctness, `ProcedureAssertsValidOnTraces.denote`: every assertion + on every run is valid and the postconditions hold, from entry environments satisfying + the axioms declared before the procedure (`AxiomsBeforeProcedureDecl`). + `Strata/Transform/SpecHoareConnection.lean` takes a triple to assertion validity on + every run, given termination. +- Denotational evaluation (since November 2026): `Expression.eval` is `LExpr.denoteEval` + over the factory and a model of it, and stores hold semantic values. Lifting lemmas + exist for `+`, `-`, `*` and the comparisons on `int`, three `bv16` operators, free + variables, `==` and `if` (`IntEvalProps.lean`, `BitVecEvalProps.lean`), with a generic + one for any binary operator that has a concrete evaluation (`eval_app2_op`). + +Its tests prove some twenty procedures by hand, with `native_decide` for facts about the +AST; none uses axioms, datatypes, maps or sequences. There is no automation and its +authors plan none: the triple is their specification of partial correctness, and +generating verification conditions against it is open to others. So the tactic is ours to +build, on a stable target. ## Plan -1. **VC generation tactic over `Core.Logic.Hoare`.** From `Procedure.contractTriple p params - name`, apply the rules backwards statement by statement and discharge their side - conditions (`InitEnvWF`, `PostWF`, `exitsCoveredByBlocks`) by evaluation on the - concrete AST. The result is one goal per `assert`, loop invariant and `ensures`, over - the store. This is the shape of `core_vcgen` in the `StrataBoole/Deep/` experiment (fork - branch `exp/deep-embedding`), retargeted from its own `Exec` to Strata's `Triple`. +1. **Tactic.** State the contract triple with `AxiomsBeforeProcedureDecl` added to its + precondition, so the axioms are available as Strata's notion of correctness assumes + them. A theorem to write takes a proved triple to the part of that notion about runs + that finish; the part about runs that do not also needs termination. Apply the rules + backwards and discharge their side conditions: `exitsCoveredByBlocks`, and `PostWF` for + a block that declares nothing, by evaluation on the concrete AST; `PostWF` for a block + with declarations from `denoteEval_congr`, since a postcondition does not read the + variables the block drops; and for a call `bodyFrame` and `bodyOutputsTyped`, which are + facts about every run of the callee's body. Derive from `cmd` the rules Strata does not + name: `assume`, `assert`, `havoc`, declaration without initialiser. The result is one + goal per `assert`, loop invariant and `ensures`, over the store. This is `core_vcgen` + of the `StrataBoole/Deep/` experiment (fork branch `exp/deep-embedding`), retargeted to + Strata's `Triple`. 2. **Lifting.** Turn each goal into a proposition over Lean values: a store slot of type - `int` is an `Int` (`inputAsPredicate` and `SemValue.exists_ofInt`), `Expression.eval` - of an operator on values is the Lean operation (Strata's lemmas, plus ours for the - Boolean connectives and `==` in `StrataBoole/HoareLift.lean`), and a contract clause - becomes the corresponding proposition. Still to write: the lemmas for `Map` and - `Sequence` operators, which follow from the factory axioms, and for quantifiers. This - is the shape of `core_lift`. Milestone: - `max2`, then the counting loop of `demo.lean`, then `find_max`, proved by the tactic, - lifting, and `omega`/`grind`. -3. **Boole entry.** The prototype's `shallow_reflect` (on its fork branch) already produces - the type-checked Core program as a Lean term. It is the input of step 1, so a user - writes a `#strata program Boole` block and states `contractTriple` on its procedures. -4. **Gaps shared with Strata, fixed in Strata.** Rules for nondeterministic `if` and - `while`; the program's uninterpreted functions and axioms in the model (its functions - with bodies are in since November 2026); the generic datatype carrier wired into the - model (decision below), which also covers `nat`. + `int` is an `Int`, and evaluating an operator on values is the Lean operation. Done: + Strata's lemmas, plus `Bool.And`, `Bool.Or` and `==` on integers in + `StrataBoole/HoareLift.lean`. To write: the other Boolean connectives, `div` and `mod`, + the `bv` operators and conversions, `Map` and `Sequence` operators (from the factory + axioms), quantifiers, and user functions (a function equals its body in every model). + This is `core_lift` of the same experiment. +3. **Boole entry.** `Strata.Boole.typeCheck` gives the type-checked Core program of a + `#strata program Boole` block as a Lean term, and the triple is stated on its + procedures, as in `hoare_max2.lean`. The prototype's `shallow_reflect` (fork branch) + wraps this as a command. +4. **The model, in Strata.** Not needed to prove a triple, needed to trust one. + - Datatypes: constructors, testers and destructors enter the visible factory + (`Lambda.genBlockFactory` generates them), and the model's datatype laws, today + disjointness and injectivity, gain inversion and induction. + - A model exists for a program's factory with its axioms, built on the carrier + (Decisions). This rules out a vacuous triple, and proves the `nat` bridge axioms of + the intended `nat` instead of assuming them. + - `contractTriple` and `call_of_contract` carry the axioms, so a callee's proof may + use them. + - Function preconditions and termination of recursive functions, which the solver path + checks, stated beside the triple. + - Rules for nondeterministic `if` and `while`. 5. **Boole semantics.** A Boole interpreter proved to agree with `toCoreProgram`, so that - Boole has a meaning stated in its own terms and the lowering to Core is proved correct - rather than definitional. This is what makes Boole a language rather than a front end. - It comes after steps 1 to 3 because the agreement theorem needs Core's semantics on the - other side. Its prerequisites, `toCoreExpr` total and the `nat` library inside - `typeCheck`, are merged (strata-org/Strata-Boole#25, #26). Running programs is not - what it is for: Strata already has an executable evaluator for Core - (`Strata/Languages/Core/StatementEval.lean`). Open design choice: Velvet's - nondeterministic state monad, with its VC generator, is a candidate for the - interpreter now that Strata and Velvet share a Lean version. + Boole has a meaning in its own terms and the lowering is proved, not trusted. It + follows steps 1 to 3 because the agreement theorem needs Core's semantics on the other + side. It is not for running programs; Strata's `StatementEval.lean` does that. Its + prerequisites are merged (strata-org/Strata-Boole#25, #26). Candidate: Velvet's + nondeterministic state monad with its VC generator. + +Milestones: `max2`, the counting loop of `demo.lean`, a loop over a sequence, `find_max`, +then the benchmark below. ## Decisions -- Build on `Core.Logic.Hoare`, not on a semantics of our own: neither `Deep/`'s `Exec`, - which nothing connects to Core's semantics, nor an interpreter with an adequacy proof - that would redo what Strata's rules already prove. -- Core first, then Boole. Boole is the language users write and the one this work is - about; Core is where the proved semantics lives today. Starting from Boole directly - would leave nothing to prove adequacy against, so the Boole semantics is step 5, not - step 1. +- Build on `Core.Logic.Hoare`, not on a semantics of our own. `Deep/`'s `Exec` is not + connected to Core's semantics, and an interpreter with an adequacy proof would redo what + Strata's rules already prove. +- Core first, then Boole: Core is where the proved semantics lives, so a Boole semantics + has something to agree with. - Goals over Lean values come from lifting, not from a monadic encoding, so `Std.Do`/`mvcgen` (`StrataBoole/Shallow/Layer.lean`) is off the path. -- Failure is never vacuous: a construct the tactic cannot handle leaves the goal open - instead of closing it. -- Datatypes get one generic model, not one Lean inductive per program: a single inductive - of constructor applications with a well-sortedness predicate (`DT.Carrier` in - `Strata/DL/SMT/DenoteDatatypes.lean`, the SMT denotation under review in Strata). Its laws - are proved once, a program's datatypes are declarations the model reads, and `nat` is - its `pos`/`nat` with `toInt` by structural recursion. The same carrier interprets - datatype sorts in the model `Triple` quantifies over, which discharges the laws the - Lambda denotation leaves as assumptions. The per-program inductives of - strata-org/Strata#1480 serve the SMT-IR path; readable goals (`pos.xO h` for - `mk "xO" [h]`) are notation and simp lemmas added later. -- This is a deep embedding with shallow goals: the program stays data, the Lean term is - the proof about it, and what the user sees are goals over Lean values. It started as a - shallow embedding in the Velvet sense; say so when the difference matters. The - `Shallow` names left in the tree (`StrataBoole/Shallow/`, `shallow_find_max`) are that - prototype's. - -## Coverage of the rules - -| Core | `Core.Logic.Hoare` | +- Failure is never vacuous: a construct the tactic cannot handle leaves its goal open. +- Datatypes: keep Strata's approach of stating their laws as conditions on every model, + and supply the model from one generic carrier, a single inductive of constructor + applications with a well-sortedness predicate (`DT.Carrier`, strata-org/Strata#1493, + written for the SMT denotation). `nat` is its `pos`/`nat` with `toInt` by structural + recursion. The per-program inductives of strata-org/Strata#1480 serve the SMT path only; + readable goals are notation added later. +- This is a deep embedding with shallow goals: the program stays data, and the user sees + goals over Lean values. The `Shallow` names in the tree are the earlier prototype's. + +## Coverage + +| Core | State | | --- | --- | -| assignments, `init`, `assert`, `assume`, `havoc` (as `set x *` through `cmd`), blocks, `exit`, deterministic `if` and `while`, `call` | rules exist | +| assignments, `init` with a value, blocks, `exit`, deterministic `if` and `while`, `call` | rules exist | +| `assert`, `assume`, `havoc`, declaration without initialiser | through `cmd`; rules to derive (step 1) | | `if *`, `while *`, loop measures, `cover` | to add | -| `int`, `bool`, `bv n` | denoted and lifted | -| `Map`, `Sequence`, `Set`, `string` operators | modelled, every model satisfies their axioms; lifting lemmas to add (step 2) | -| datatypes, `nat` | generic carrier (decision above); wiring into the model is step 4 | -| user functions with bodies | in the model (`factoryBeforeProcedure`) | -| uninterpreted functions, `axiom` | step 4 | - -## Target: the benchmark the solver path already verifies - -`StrataBooleTest/dalek_sum_of_slice.lean` (36 obligations, cvc5 and lean-smt) is the -program this route has to reach. What it uses, and where each item sits: - -| In the program | Needs | Step | -| --- | --- | --- | -| `for` loop with six invariants, `call` in the body, `exit` | rules exist; the tactic must discharge the loop and call side conditions | 1 | -| integer and `bv W8` arithmetic, `as_uint`, comparisons | lifting lemmas per operator | 2 | -| quantified `requires` and invariants | lifting of quantifiers to Lean `∀` over `Int` | 2 | -| `Sequence (bv W8)` and `Sequence Scalar`, `select`, `length` | lifting lemmas from the sequence axioms | 2 | -| native `nat`, the `nat_*` library | the generic carrier in the model, library functions as program functions | 4 | -| `function` definitions, one `rec function` with `requires` and `decreases` | in the model | done | -| `function f();` without body | uninterpreted functions in the model | 4 | -| `axiom` declarations, including the unfolding axiom of the recursive function | program axioms as hypotheses on the model | 4 | -| a callee whose body is `assume false` | `call_of_contract` with a trivially proved contract | 1 | - -The lifted goals must stay solver-friendly: lean-smt closes goals over `Int`, `Bool` and -`BitVec`, so sequences should lift to a length and an index function rather than to -`List`, and `nat` to `Nat`. Decide this with step 4; it does not affect steps 1 to 3. - -Order: `max2`, the counting loop, then this program as soon as step 4 lands in Strata. -Everything in steps 1 to 3 is exercised by the first two and reused unchanged by the third. +| `int`, `bool`, `bv n` | lifted: `+`, `-`, `*` and comparisons on `int`, `&&`, `\|\|`, three `bv16` operators; the rest to add (step 2) | +| `Map`, `Sequence`, `Set`, `string` | constrained in every model; lifting to add (step 2) | +| functions, with or without body | in the model | +| `axiom` | through `AxiomsBeforeProcedureDecl` (step 1); assumed until step 4 | +| datatypes, `nat` | not in the model: constructors are unconstrained symbols (step 4) | + +## Target: `dalek_sum_of_slice` + +`StrataBooleTest/dalek_sum_of_slice.lean` (branch `demo/dalek-sum-of-slice`; 36 +obligations on the solver path, cvc5 and lean-smt) is the program this route has to reach. +On the current Strata it type checks, both procedures pass `contractChecksTyped`, every +operator of their specifications is in the visible factory, and caller and callee see the +same factory, as `call_of_contract` requires. + +It uses a `for` loop with six invariants and a `call` in its body, `exit`, `assume` and +two declarations without initialiser (step 1); integer `+`, `-`, `*`, `div`, `mod`, `<=` +and `<`, `&&` and `==>`, `<=` on `bv W8` and `as_uint`, `Sequence` `select`, `select!` and +`length`, quantified clauses, and thirteen functions, one recursive and two without body +(step 2); and 19 axioms, 12 from the `nat` library and 7 of its own. `nat` is used only +through its library functions and those axioms, so the proof is expected to need no +datatype reasoning. It does not wait on step 4; until then it assumes the 19 axioms, as +the solver path does. + +The callee is trusted: its body is `assume false`. Core's semantics runs the callee's body +at a call, so that assumption enters the caller's trace, and every obligation of the +caller after the first call holds vacuously. On this route a trusted procedure needs a +body that can run and meets its contract, such as assigning an arbitrary value and +assuming the `ensures`. That is a change to the benchmark and to how trusted functions +are translated, not to Strata. + +Lifted goals must stay within what lean-smt closes (`Int`, `Bool`, `BitVec`): sequences +lift to a length and an index function, which is what the axioms give in an arbitrary +model, and `nat` appears through `nat.toInt`. + +## Trusted base + +What a proved triple rests on, beyond Lean's kernel, Core's semantics and the contract as +written: + +| Trusted today | Removed by | +| --- | --- | +| the Boole to Core lowering | step 5 | +| the program's axioms, and that a model of the program with them exists | step 4 | +| function preconditions and termination, which the triple does not state | step 4 | +| the Lean compiler, through `native_decide` on facts about the AST | kernel-checked facts in the tactic | + +The solver path trusts the lowering and the axioms too, and in addition Strata's +transformation pipeline, the SMT encoding and the solver. The tactic needs no adequacy +theorem: it builds a proof from rules that are theorems about the semantics, and the +kernel checks that proof for each program. ## Status -- `max2` is proved against Strata's triple, by hand, in `StrataBooleTest/hoare_max2.lean` - on the denotational semantics: `contractTriple_of_core_typed`, then `block`, `block`, - `ite` and `set`, every side condition by `native_decide` on the reflected program, the - inputs recovered from the condition's evaluation (`denoteEval_defines`), the operators - lifted with Strata's `eval_intGe` and `eval_fvar_int` and our `eval_boolAnd`, - `eval_boolOr` and `eval_eq_ints` (`StrataBoole/HoareLift.lean`, each from the model's - agreement with the operator's concrete evaluation). The proof is the specification of - the step 1 tactic: it does these steps for any straight-line body with `if`. Steps 1 - and 2 as automation: not started. `Deep/` has both against its own semantics, with - `max2` and a counting loop proved. -- `StrataBoole/Shallow/Layer.lean` is kept until the milestone is reached. -- Two things the hand proof settled. Under the module system, facts about factory entries - are not `rfl`; they need `import all` of the defining files and `simp` unfolding. And - the typing derivations (`HasTypeA`) must be spelled with the annotations exactly as the - lowering writes them, or the rewrite rules do not fire; the tactic should build them - from the term, not from the types. -- `StrataBooleTest/generic_datatypes.lean`: first prototype of the carrier. -- Risks. Strata's own hand proof of a two-branch `if` is some twenty-five lines with - `native_decide` and explicit store facts, so discharging the side conditions - automatically is the bulk of step 1. -- `Map` and `Sequence` were outside the logic until November 2026 (strata-org/Strata#1496: - their operators had no execution, and models were free to violate the axioms). The - denotational evaluation fixed both; what remains is the lifting lemmas of step 2. +- `max2` is proved against Strata's triple by hand (`StrataBooleTest/hoare_max2.lean`): + `contractTriple_of_core_typed`, then `block`, `block`, `ite` and `set`, side conditions + by `native_decide`, operators lifted with Strata's lemmas and + `StrataBoole/HoareLift.lean`. It is the specification of the tactic for straight-line + bodies with `if`. The tactic is not started; `Deep/` has one against its own semantics, + with `max2` and a counting loop. +- What the hand proof settled: under the module system, facts about factory entries need + `import all` and `simp`, not `rfl`. Typing derivations no longer have to be written: + Strata's lemmas take the evaluation of the subterms. +- Risk: discharging the side conditions is the bulk of step 1. Strata's hand proof of a + two-branch `if` is some 25 lines, its call test some 1400 lines for three procedures. +- `StrataBooleTest/generic_datatypes.lean` is a first prototype of the carrier. + `StrataBoole/Shallow/Layer.lean` is kept until the first milestone. ## Open questions -- Loop measures: `while_rule` is partial correctness. Add a total-correctness rule, or - check `decreases` separately? +- Termination: `while_rule` is partial correctness, while Strata's notion of correctness + also covers runs that never finish. Add a total-correctness rule, or check `decreases` + separately? - `cover` is a reachability check, not a Hoare fact. How to state it? - Goal names: carry the program's clause names into the goals the tactic leaves. -- `native_decide` for AST facts: acceptable in the tactic, or avoid it? +- Datatypes and program models in the Hoare logic (step 4): no upstream test uses either, + so agree the shape with Strata before building. +- Trusted procedures: `Triple` runs a callee's body, while Strata also has a + contract-based call semantics (`EvalCmdExtContractE`). Should a triple over it exist? ## Sources From 225c548ec1972cc68cd25091195884fca093562d Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Wed, 11 Nov 2026 10:21:46 +0100 Subject: [PATCH 32/64] Pin Strata to the integration head with the Hoare rules for the base commands --- lake-manifest.json | 4 ++-- lakefile.toml | 7 ++++--- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/lake-manifest.json b/lake-manifest.json index c939133..56a41e2 100644 --- a/lake-manifest.json +++ b/lake-manifest.json @@ -15,10 +15,10 @@ "type": "git", "subDir": null, "scope": "", - "rev": "91bb455326b6ebc8c7fd1edb753b2ea1ff63474c", + "rev": "dcdb7f08446275cf4933615464988f262ca5881b", "name": "Strata", "manifestFile": "lake-manifest.json", - "inputRev": "91bb45532", + "inputRev": "dcdb7f084", "inherited": false, "configFile": "lakefile.toml"}, {"url": "https://github.com/leanprover-community/mathlib4.git", diff --git a/lakefile.toml b/lakefile.toml index d1c48ec..61541ea 100644 --- a/lakefile.toml +++ b/lakefile.toml @@ -9,10 +9,11 @@ weakLeanArgs = ["--tstack=32768"] name = "Strata" # On this branch Strata is the `integration/lean-route` branch of the fork: Strata main # plus the open PRs the Lean route needs (datatype denotation, checked-to-total sequence -# pass, public denote lemmas, datatypes to Lean). It moves back to strata-org/Strata when -# they merge. A fixed commit, not a branch name, so `lake update` cannot move it. +# pass, public denote lemmas, datatypes to Lean, Hoare rules for the base commands). It +# moves back to strata-org/Strata when they merge. A fixed commit, not a branch name, so +# `lake update` cannot move it. git = "https://github.com/kondylidou/Strata" -rev = "91bb45532" +rev = "dcdb7f084" [[require]] name = "smt" From 69b78e00bd842b780c95b1139c331d5f33341e34 Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Wed, 11 Nov 2026 10:22:40 +0100 Subject: [PATCH 33/64] Pin Strata with the Hoare rules for the base commands; track the Strata changes in the doc --- docs/HoareLogic.md | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/docs/HoareLogic.md b/docs/HoareLogic.md index 5458d85..898499e 100644 --- a/docs/HoareLogic.md +++ b/docs/HoareLogic.md @@ -68,8 +68,8 @@ build, on a stable target. a block that declares nothing, by evaluation on the concrete AST; `PostWF` for a block with declarations from `denoteEval_congr`, since a postcondition does not read the variables the block drops; and for a call `bodyFrame` and `bodyOutputsTyped`, which are - facts about every run of the callee's body. Derive from `cmd` the rules Strata does not - name: `assume`, `assert`, `havoc`, declaration without initialiser. The result is one + facts about every run of the callee's body. The rules for `assume`, `assert`, `havoc` + and a declaration without initialiser are in strata-org/Strata#1498. The result is one goal per `assert`, loop invariant and `ensures`, over the store. This is `core_vcgen` of the `StrataBoole/Deep/` experiment (fork branch `exp/deep-embedding`), retargeted to Strata's `Triple`. @@ -130,7 +130,7 @@ then the benchmark below. | Core | State | | --- | --- | | assignments, `init` with a value, blocks, `exit`, deterministic `if` and `while`, `call` | rules exist | -| `assert`, `assume`, `havoc`, declaration without initialiser | through `cmd`; rules to derive (step 1) | +| `assert`, `assume`, `havoc`, declaration without initialiser | rules in strata-org/Strata#1498 | | `if *`, `while *`, loop measures, `cover` | to add | | `int`, `bool`, `bv n` | lifted: `+`, `-`, `*` and comparisons on `int`, `&&`, `\|\|`, three `bv16` operators; the rest to add (step 2) | | `Map`, `Sequence`, `Set`, `string` | constrained in every model; lifting to add (step 2) | @@ -199,6 +199,22 @@ kernel checks that proof for each program. - `StrataBooleTest/generic_datatypes.lean` is a first prototype of the carrier. `StrataBoole/Shallow/Layer.lean` is kept until the first milestone. +## Strata changes for this route + +This branch pins the `integration/lean-route` branch of the fork: Strata main plus the open +pull requests below. The pin returns to strata-org/Strata when they merge. + +| Change | State | Used by | +| --- | --- | --- | +| strata-org/Strata#1498: rules `init_nondet`, `havoc`, `assume`, `assert`, and the forms of the last two that read a condition by evaluation | open | step 1 | +| strata-org/Strata#1492: public unfolding lemmas for quantifiers and binders | approved, not merged | quantifier lifting in step 2 | +| strata-org/Strata#1493: datatypes in the SMT denotation, with the generic carrier | open | the SMT path now, the model of step 4 later | +| strata-org/Strata#1496: `Map` and `Sequence` statements had no execution, and models did not have to satisfy their axioms | closed, fixed upstream by the denotational evaluation | step 2 | +| strata-org/Strata#1490: the SMT path refuses the VCs its denotation does not cover | merged | Goal | + +The integration branch also carries strata-org/Strata#1483, which concerns the solver path +only. Nothing of step 4 has a pull request yet; its shape is the last two open questions. + ## Open questions - Termination: `while_rule` is partial correctness, while Strata's notion of correctness From ce9e4c9de5c685e69f534c2b1d7cd74de0ad969c Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Wed, 11 Nov 2026 10:34:38 +0100 Subject: [PATCH 34/64] sum --- docs/HoareLogic.md | 44 +++++++++++++++++++------------------------- 1 file changed, 19 insertions(+), 25 deletions(-) diff --git a/docs/HoareLogic.md b/docs/HoareLogic.md index 898499e..7e3c0c5 100644 --- a/docs/HoareLogic.md +++ b/docs/HoareLogic.md @@ -140,31 +140,25 @@ then the benchmark below. ## Target: `dalek_sum_of_slice` -`StrataBooleTest/dalek_sum_of_slice.lean` (branch `demo/dalek-sum-of-slice`; 36 -obligations on the solver path, cvc5 and lean-smt) is the program this route has to reach. -On the current Strata it type checks, both procedures pass `contractChecksTyped`, every -operator of their specifications is in the visible factory, and caller and callee see the -same factory, as `call_of_contract` requires. - -It uses a `for` loop with six invariants and a `call` in its body, `exit`, `assume` and -two declarations without initialiser (step 1); integer `+`, `-`, `*`, `div`, `mod`, `<=` -and `<`, `&&` and `==>`, `<=` on `bv W8` and `as_uint`, `Sequence` `select`, `select!` and -`length`, quantified clauses, and thirteen functions, one recursive and two without body -(step 2); and 19 axioms, 12 from the `nat` library and 7 of its own. `nat` is used only -through its library functions and those axioms, so the proof is expected to need no -datatype reasoning. It does not wait on step 4; until then it assumes the 19 axioms, as -the solver path does. - -The callee is trusted: its body is `assume false`. Core's semantics runs the callee's body -at a call, so that assumption enters the caller's trace, and every obligation of the -caller after the first call holds vacuously. On this route a trusted procedure needs a -body that can run and meets its contract, such as assigning an arbitrary value and -assuming the `ensures`. That is a change to the benchmark and to how trusted functions -are translated, not to Strata. - -Lifted goals must stay within what lean-smt closes (`Int`, `Bool`, `BitVec`): sequences -lift to a length and an index function, which is what the axioms give in an arbitrary -model, and `nat` appears through `nat.toInt`. +`StrataBooleTest/dalek_sum_of_slice.lean` (branch `demo/dalek-sum-of-slice`, 36 +obligations on the solver path) is the program this route has to reach. On the current +Strata it type checks, both contracts pass `contractChecksTyped`, and caller and callee +see the same factory, as `call_of_contract` requires. + +| It uses | Step | +| --- | --- | +| a `for` loop with six invariants and a `call`, `exit`, `assume`, two declarations without initialiser | 1 | +| integer arithmetic with `div` and `mod`, `&&`, `==>`, `<=` and `as_uint` on `bv W8`, `Sequence` `select`, `select!` and `length`, quantifiers, thirteen functions | 2 | +| 19 axioms, 12 of them the `nat` library's | assumed until 4 | + +- `nat` is used only through its library and those axioms, so the proof should need no + datatype reasoning and does not wait on step 4. +- The callee is trusted, with body `assume false`. A call runs the callee's body, so + every obligation of the caller after the first call holds vacuously. The benchmark + needs a body that can run, such as assigning an arbitrary value and assuming the + `ensures`: a change to the benchmark and its translation, not to Strata. +- Lifted goals stay within what lean-smt closes (`Int`, `Bool`, `BitVec`): sequences as + a length and an index function, `nat` through `nat.toInt`. ## Trusted base From 73e2e99bb8296b2b480f1c8f2f1f315b8677a2cf Mon Sep 17 00:00:00 2001 From: Stephanie Ma Date: Wed, 11 Nov 2026 16:57:23 -0800 Subject: [PATCH 35/64] Hoare-logic route: tactic, lifting and boole_prove under HoareLogic/ - hoare_contract, hoare_vcs, hoare_lift prove Procedure.contractTriple for integer programs from Boole source; max2 and demo.lean's loop pass - Deep embedding, shallow_reflect and #core_reflect in StrataBoole/HoareLogic - Route code and tests grouped under StrataBoole/HoareLogic and StrataBooleTest/HoareLogic; translator and interpreter prototypes removed - docs/HoareLogic.md: Status updated Co-Authored-By: Claude Opus 5.5 --- StrataBoole.lean | 35 +- StrataBoole/HoareLogic/Deep/Delab.lean | 590 +++++++++++ StrataBoole/HoareLogic/Deep/Exec.lean | 254 +++++ StrataBoole/HoareLogic/Deep/Lang.lean | 238 +++++ StrataBoole/HoareLogic/Deep/Spec.lean | 257 +++++ StrataBoole/HoareLogic/Deep/Tactic.lean | 279 ++++++ StrataBoole/HoareLogic/Deep/Triple.lean | 90 ++ StrataBoole/HoareLogic/Hoare/Contract.lean | 347 +++++++ StrataBoole/HoareLogic/Hoare/Lift/Denote.lean | 880 ++++++++++++++++ StrataBoole/HoareLogic/Hoare/Lift/Eval.lean | 916 +++++++++++++++++ StrataBoole/HoareLogic/Hoare/Proj.lean | 349 +++++++ StrataBoole/HoareLogic/Hoare/Rules.lean | 374 +++++++ StrataBoole/HoareLogic/Hoare/Tactic.lean | 940 ++++++++++++++++++ StrataBoole/HoareLogic/Hoare/WP.lean | 482 +++++++++ StrataBoole/{ => HoareLogic}/HoareLift.lean | 0 StrataBoole/HoareLogic/Lift/Names.lean | 154 +++ StrataBoole/HoareLogic/Pipeline.lean | 80 ++ .../Reflect/Boole.lean} | 26 +- StrataBoole/HoareLogic/Reflect/Core.lean | 243 +++++ .../Reflect/ToExpr.lean} | 4 +- .../Reflect/TypeCheck.lean} | 17 +- .../{ => HoareLogic}/Shallow/Layer.lean | 0 StrataBoole/Shallow/Emit.lean | 173 ---- StrataBoole/Shallow/Interpreter/Interp.lean | 355 ------- StrataBoole/Shallow/Interpreter/Model.lean | 209 ---- StrataBoole/Shallow/Interpreter/Sort.lean | 74 -- StrataBoole/Shallow/Translate.lean | 519 ---------- StrataBooleTest.lean | 20 +- StrataBooleTest/HoareLogic/boole_globals.lean | 75 ++ StrataBooleTest/HoareLogic/deep_count_up.lean | 72 ++ StrataBooleTest/HoareLogic/deep_max2.lean | 116 +++ StrataBooleTest/HoareLogic/deep_nondet.lean | 77 ++ StrataBooleTest/HoareLogic/deep_quant.lean | 117 +++ StrataBooleTest/HoareLogic/demo_pipeline.lean | 291 ++++++ .../{ => HoareLogic}/generic_datatypes.lean | 0 .../HoareLogic/hoare_find_max_core.lean | 69 ++ .../HoareLogic/hoare_frame_core.lean | 138 +++ .../HoareLogic/hoare_havoc_gap.lean | 46 + .../HoareLogic/hoare_locals_core.lean | 89 ++ .../{ => HoareLogic}/hoare_max2.lean | 4 +- .../HoareLogic/hoare_nondet_core.lean | 91 ++ .../HoareLogic/hoare_ops_core.lean | 121 +++ .../HoareLogic/hoare_quant_core.lean | 141 +++ .../{ => HoareLogic}/shallow_find_max.lean | 2 +- .../HoareLogic/shallow_reflect.lean | 234 +++++ StrataBooleTest/shallow_translate.lean | 142 --- docs/HoareLogic.md | 30 +- 47 files changed, 8248 insertions(+), 1512 deletions(-) create mode 100644 StrataBoole/HoareLogic/Deep/Delab.lean create mode 100644 StrataBoole/HoareLogic/Deep/Exec.lean create mode 100644 StrataBoole/HoareLogic/Deep/Lang.lean create mode 100644 StrataBoole/HoareLogic/Deep/Spec.lean create mode 100644 StrataBoole/HoareLogic/Deep/Tactic.lean create mode 100644 StrataBoole/HoareLogic/Deep/Triple.lean create mode 100644 StrataBoole/HoareLogic/Hoare/Contract.lean create mode 100644 StrataBoole/HoareLogic/Hoare/Lift/Denote.lean create mode 100644 StrataBoole/HoareLogic/Hoare/Lift/Eval.lean create mode 100644 StrataBoole/HoareLogic/Hoare/Proj.lean create mode 100644 StrataBoole/HoareLogic/Hoare/Rules.lean create mode 100644 StrataBoole/HoareLogic/Hoare/Tactic.lean create mode 100644 StrataBoole/HoareLogic/Hoare/WP.lean rename StrataBoole/{ => HoareLogic}/HoareLift.lean (100%) create mode 100644 StrataBoole/HoareLogic/Lift/Names.lean create mode 100644 StrataBoole/HoareLogic/Pipeline.lean rename StrataBoole/{Shallow/Interpreter/Command.lean => HoareLogic/Reflect/Boole.lean} (51%) create mode 100644 StrataBoole/HoareLogic/Reflect/Core.lean rename StrataBoole/{Shallow/Interpreter/Reflect.lean => HoareLogic/Reflect/ToExpr.lean} (99%) rename StrataBoole/{Shallow/Pipeline.lean => HoareLogic/Reflect/TypeCheck.lean} (62%) rename StrataBoole/{ => HoareLogic}/Shallow/Layer.lean (100%) delete mode 100644 StrataBoole/Shallow/Emit.lean delete mode 100644 StrataBoole/Shallow/Interpreter/Interp.lean delete mode 100644 StrataBoole/Shallow/Interpreter/Model.lean delete mode 100644 StrataBoole/Shallow/Interpreter/Sort.lean delete mode 100644 StrataBoole/Shallow/Translate.lean create mode 100644 StrataBooleTest/HoareLogic/boole_globals.lean create mode 100644 StrataBooleTest/HoareLogic/deep_count_up.lean create mode 100644 StrataBooleTest/HoareLogic/deep_max2.lean create mode 100644 StrataBooleTest/HoareLogic/deep_nondet.lean create mode 100644 StrataBooleTest/HoareLogic/deep_quant.lean create mode 100644 StrataBooleTest/HoareLogic/demo_pipeline.lean rename StrataBooleTest/{ => HoareLogic}/generic_datatypes.lean (100%) create mode 100644 StrataBooleTest/HoareLogic/hoare_find_max_core.lean create mode 100644 StrataBooleTest/HoareLogic/hoare_frame_core.lean create mode 100644 StrataBooleTest/HoareLogic/hoare_havoc_gap.lean create mode 100644 StrataBooleTest/HoareLogic/hoare_locals_core.lean rename StrataBooleTest/{ => HoareLogic}/hoare_max2.lean (99%) create mode 100644 StrataBooleTest/HoareLogic/hoare_nondet_core.lean create mode 100644 StrataBooleTest/HoareLogic/hoare_ops_core.lean create mode 100644 StrataBooleTest/HoareLogic/hoare_quant_core.lean rename StrataBooleTest/{ => HoareLogic}/shallow_find_max.lean (98%) create mode 100644 StrataBooleTest/HoareLogic/shallow_reflect.lean delete mode 100644 StrataBooleTest/shallow_translate.lean diff --git a/StrataBoole.lean b/StrataBoole.lean index 3386c4f..2037080 100644 --- a/StrataBoole.lean +++ b/StrataBoole.lean @@ -7,7 +7,7 @@ module public import StrataBoole.Boole public import StrataBoole.Verify -public import StrataBoole.HoareLift +public import StrataBoole.HoareLogic.HoareLift /-! ## Strata Boole Public Interface @@ -30,12 +30,43 @@ dialect of Strata. `Strata.BooleNat.prepend`. The implementation is `natCorePreamble` in `StrataBoole/Verify.lean`; nothing imports this module. `lake build StrataBoole.Nat`. -### `import StrataBoole.Shallow.Layer` +### `import StrataBoole.HoareLogic.Shallow.Layer` A shallow-embedding prototype on `Std.Do`: the `ND` monad with `havoc`, `assume`, `assert` and `whileInv`, each with its `@[spec]` rule for `mvcgen`. The Hoare-logic route in `docs/HoareLogic.md` does not build on it. +### `import StrataBoole.HoareLogic.Pipeline` + +`boole_prove pgm proc` proves in Lean the contract of the procedure `proc` of the Boole program +`pgm`: it binds the program's Core AST (`shallow_reflect`), then states and proves +`proc_contract : Core.Logic.Hoare.Procedure.contractTriple pgm_ast params "proc"` and +`proc_correct : Strata.Deep.Procedure.Correct proc_ast`, closing each verification condition +with `omega`, then `grind`. `boole_prove pgm proc strata` or `… deep` proves one of the two, and +`… with tac` closes the conditions with `tac`. + +### `import StrataBoole.HoareLogic.Hoare.Tactic` + +The Hoare-logic route of `docs/HoareLogic.md`, on Strata's `Core.Logic.Hoare`: +weakest-precondition rules proved from Strata's (`Hoare/Rules.lean`, `Proj.lean`, `WP.lean`, +`Contract.lean`), lifting lemmas for the evaluator and the denotation (`Hoare/Lift/`), and the +tactics `hoare_contract`, `hoare_vcs` and `hoare_lift`, which turn `Procedure.contractTriple` +into verification conditions over `Int` and `Bool`, named after the program's clauses. + +### `import StrataBoole.HoareLogic.Deep.Tactic` + +A deep embedding of Core's structured statements with a big-step semantics of its own +(`Deep/Exec.lean`), rules proved about it, and the tactics `core_vcgen` and `core_lift`. It leaves +the same conditions as the Hoare-logic route and serves as a cross-check; nothing connects it to +Core's semantics. + +### `import StrataBoole.HoareLogic.Reflect.Boole` + +`shallow_reflect p` binds the type-checked Core program of the Boole program `p` to +`

_ast : Core.Program` and each of its procedures to `_ast : Core.Procedure`, as terms +the kernel can reduce. `#core_reflect` (`StrataBoole.HoareLogic.Reflect.Core`) does the same +for a program written in Core syntax. + ### `import StrataBoole.MetaVerifier` The `gen_smt_vcs_boole` tactic and `Strata.smtVCsCorrectBoole` are available diff --git a/StrataBoole/HoareLogic/Deep/Delab.lean b/StrataBoole/HoareLogic/Deep/Delab.lean new file mode 100644 index 0000000..96f60c4 --- /dev/null +++ b/StrataBoole/HoareLogic/Deep/Delab.lean @@ -0,0 +1,590 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import Lean +import Strata.Languages.Core.Procedure +import StrataBoole.HoareLogic.Deep.Lang + +/-! # Deep embedding of Core: reading Core ASTs in goals + +Delaborators that print the Core AST inside goals in Core's own notation: + +* an expression `Lambda.LExpr …` as `⟪m >= x || m == y⟫`; +* a statement, or a list of statements, as `⟦m := x; assert [l]: m >= y⟧`; +* a procedure as its Core declaration, `⟦procedure max2(x : int, …) spec { … } { … }⟧`; +* `Holds σ e` as `σ ⊨ e`. + +Built-in operators print infix (`+`, `<=`, `==`, `&&`, `==>`, …). Any other operator, +or a function, prints as a call `f(a, b)`. The type annotations the translator puts on +variables and operators are not shown. + +The notation is for reading only: no elaborator turns `⟪…⟫` back into a term. A part +of the AST that is not a literal, such as a Lean variable standing for an expression, +prints as `⦃e⦄` inside the Core notation. `set_option pp.core false` turns all of this +off and shows the raw constructors. + +This file is not a `module`, so its delaborators need no `meta` phase annotations. +-/ + +register_option pp.core : Bool := { + defValue := true + descr := "(pretty printer) display Core expressions, statements and procedures in Core notation" +} + +namespace Strata.Deep.Delab + +open Lean PrettyPrinter Delaborator SubExpr + +/-! ## Display syntax -/ + +declare_syntax_cat core_expr (behavior := both) +declare_syntax_cat core_type +declare_syntax_cat core_label +declare_syntax_cat core_guard +declare_syntax_cat core_loop_spec (behavior := both) +declare_syntax_cat core_call_arg (behavior := both) +declare_syntax_cat core_stmt (behavior := both) +declare_syntax_cat core_block +declare_syntax_cat core_param (behavior := both) +declare_syntax_cat core_clause (behavior := both) +declare_syntax_cat core_proc (behavior := both) + +syntax:max ident : core_expr +syntax:max num : core_expr +syntax:max str : core_expr +syntax:max "(" core_expr ")" : core_expr +syntax:max "⦃" term "⦄" : core_expr +syntax:max core_expr:max "(" core_expr,* ")" : core_expr +syntax:75 "!" core_expr:75 : core_expr +syntax:75 "-" core_expr:75 : core_expr +syntax:70 core_expr:70 " * " core_expr:71 : core_expr +syntax:70 core_expr:70 " / " core_expr:71 : core_expr +syntax:70 core_expr:70 " % " core_expr:71 : core_expr +syntax:65 core_expr:65 " + " core_expr:66 : core_expr +syntax:65 core_expr:65 " - " core_expr:66 : core_expr +syntax:50 core_expr:51 " == " core_expr:51 : core_expr +syntax:50 core_expr:51 " < " core_expr:51 : core_expr +syntax:50 core_expr:51 " <= " core_expr:51 : core_expr +syntax:50 core_expr:51 " > " core_expr:51 : core_expr +syntax:50 core_expr:51 " >= " core_expr:51 : core_expr +syntax:35 core_expr:35 " && " core_expr:36 : core_expr +syntax:30 core_expr:30 " || " core_expr:31 : core_expr +syntax:25 core_expr:26 " ==> " core_expr:25 : core_expr +syntax:20 core_expr:21 " <==> " core_expr:21 : core_expr +syntax:10 "if " core_expr " then " core_expr " else " core_expr:10 : core_expr +syntax:10 &"forall" ident " : " core_type " :: " core_expr:10 : core_expr +syntax:10 &"exists" ident " : " core_type " :: " core_expr:10 : core_expr +syntax:10 &"fun" ident " : " core_type " => " core_expr:10 : core_expr + +syntax:max ident : core_type +syntax:max "(" core_type ")" : core_type +syntax:max "⦃" term "⦄" : core_type +syntax:60 ident (ppSpace core_type:max)+ : core_type +syntax:25 core_type:26 " -> " core_type:25 : core_type + +syntax "[" ident "]" ":" ppHardSpace : core_label + +syntax "(" core_expr ")" : core_guard +syntax "*" : core_guard + +syntax ppAllowUngrouped &"decreases" ppHardSpace core_expr : core_loop_spec +syntax ppAllowUngrouped &"invariant" ppHardSpace (core_label)? core_expr : core_loop_spec + +syntax core_expr : core_call_arg +syntax &"out" ppSpace ident : core_call_arg +syntax &"inout" ppSpace ident : core_call_arg + +-- Layout: `ppRealGroup` is an all-or-nothing group, and `ppSpace` a line break that is +-- taken only when its group does not fit; `ppLine` is a hard line break. (`ppGroup` +-- also indents, which would shift every nested block.) `ppAllowUngrouped` keeps the +-- category formatter from indenting each statement once more. +syntax ppAllowUngrouped ppRealGroup(ident " := " core_expr) : core_stmt +syntax ppAllowUngrouped &"havoc" ppHardSpace ident : core_stmt +syntax ppAllowUngrouped ppRealGroup(&"var" ppHardSpace ident " : " core_type (" := " core_expr)?) : + core_stmt +syntax ppAllowUngrouped ppRealGroup(&"assert" ppHardSpace (core_label)? core_expr) : core_stmt +syntax ppAllowUngrouped ppRealGroup(&"assume" ppHardSpace (core_label)? core_expr) : core_stmt +syntax ppAllowUngrouped ppRealGroup(&"cover" ppHardSpace (core_label)? core_expr) : core_stmt +syntax ppAllowUngrouped "if" ppHardSpace core_guard ppHardSpace core_block + (ppHardSpace "else" ppHardSpace core_block)? : core_stmt +syntax ppAllowUngrouped ppRealGroup("while" ppHardSpace core_guard + ppIndent((ppLine core_loop_spec)*) ppLine core_block) : core_stmt +syntax ppAllowUngrouped (ident ":" ppHardSpace)? core_block : core_stmt +syntax ppAllowUngrouped &"exit" ppHardSpace ident : core_stmt +syntax ppAllowUngrouped ppRealGroup(&"call" ppHardSpace ident "(" core_call_arg,* ")") : core_stmt +syntax ppAllowUngrouped "⦃" term "⦄" : core_stmt + +syntax ppAllowUngrouped ppRealGroup("{" ppIndent(ppSpace sepBy(core_stmt, ";", ";" ppSpace)) + ppSpace "}") : core_block +syntax ppAllowUngrouped "⦃" term "⦄" : core_block + +syntax ident " : " core_type : core_param +syntax &"out" ppHardSpace ident " : " core_type : core_param +syntax &"inout" ppHardSpace ident " : " core_type : core_param + +syntax ppAllowUngrouped (&"free" ppHardSpace)? &"requires" ppHardSpace (core_label)? core_expr : + core_clause +syntax ppAllowUngrouped (&"free" ppHardSpace)? &"ensures" ppHardSpace (core_label)? core_expr : + core_clause + +syntax ppAllowUngrouped &"procedure" ppHardSpace ident "(" core_param,* ")" + ppIndent(ppLine &"spec" ppHardSpace "{" ppIndent((ppLine core_clause ";")*) ppLine "}" + ppLine "{" ppIndent(ppLine sepBy(core_stmt, ";", ";" ppLine)) ppLine "}") : core_proc + +/-- A Core expression, displayed. -/ +syntax:max "⟪" core_expr "⟫" : term +/-- A list of Core statements, displayed. -/ +syntax:max "⟦" sepBy(core_stmt, ";", "; ") "⟧" : term +/-- A Core procedure, displayed. -/ +syntax:max "⟦" core_proc "⟧" : term + +/-- `σ ⊨ e`: the Core formula `e` holds in `σ`. -/ +notation:50 σ:51 " ⊨ " e:51 => Strata.Deep.Holds σ e + +section +open Lean.PrettyPrinter.Parenthesizer + +/-- Visit a node of a display category without letting the precedences inside it decide +the parentheses around it. The notation always brackets such a node (`⟪…⟫`, `⟦…⟧`), and +the delaborators below parenthesize inside it themselves. -/ +def opaqueCategory (cat : Lean.Name) : CategoryParenthesizer := fun prec => do + let st ← get + parenthesizeCategoryCore cat prec + modify fun st' => { st' with + contPrec := st.contPrec, contCat := st.contCat, minPrec := st.minPrec, + trailPrec := st.trailPrec, trailCat := st.trailCat, visitedToken := st.visitedToken } + +@[category_parenthesizer core_expr] def core_expr.parenthesizer := opaqueCategory `core_expr +@[category_parenthesizer core_stmt] def core_stmt.parenthesizer := opaqueCategory `core_stmt +@[category_parenthesizer core_proc] def core_proc.parenthesizer := opaqueCategory `core_proc + +end + +/-! ## Reading literals out of terms -/ + +def getPPCore (o : Options) : Bool := o.get `pp.core true + +def strLit? (e : Lean.Expr) : Option String := + match e.consumeMData with + | .lit (.strVal s) => some s + | _ => none + +/-- The name of an identifier literal `⟨s, ()⟩`. -/ +def identName? (e : Lean.Expr) : Option String := do + let e := e.consumeMData + guard (e.isAppOfArity ``Lambda.Identifier.mk 3) + strLit? (e.getArg! 1) + +/-- A Core variable or label, as an identifier. -/ +def nameIdent (s : String) : Ident := mkIdent (.mkSimple s) + +/-- A Core operator name such as `Int.DivT`, as a dotted identifier. -/ +def opIdent (s : String) : Ident := mkIdent s.toName + +/-- Attach the current subterm to `stx`, so that hovering over it shows the AST. -/ +def annot {k} (stx : TSyntax k) : DelabM (TSyntax k) := do + let pos ← getPos + let stx' := annotatePos pos ⟨stx.raw⟩ + addTermInfo pos stx' (← getExpr) + return ⟨stx'.raw⟩ + +/-- The elements of the list literal at the current position, each displayed by `k`; +`none` if the list is not a literal. -/ +partial def listLit? {α} (k : DelabM α) : DelabM (Option (Array α)) := do + let e := (← getExpr).consumeMData + if e.isAppOfArity ``List.nil 1 then + return some #[] + else if e.isAppOfArity ``List.cons 3 then + let x ← withNaryArg 1 k + let some xs ← withNaryArg 2 (listLit? k) | return none + return some (#[x] ++ xs) + else + return none + +/-! ## Types -/ + +partial def coreType : DelabM (TSyntax `core_type) := do + let e := (← getExpr).consumeMData + let embed : DelabM (TSyntax `core_type) := do `(core_type| ⦃$(← withOptionAtCurrPos `pp.core false delab)⦄) + if e.isAppOfArity ``Lambda.LMonoTy.tcons 2 then + let some n := strLit? (e.getArg! 0) | embed + let some args ← withNaryArg 1 (listLit? coreType) | embed + if n == "arrow" ∧ args.size == 2 then + -- `->` associates to the right, so only an arrow on the left needs parentheses. + let isArrow (t : Lean.Expr) : Bool := + t.consumeMData.isAppOfArity ``Lambda.LMonoTy.tcons 2 ∧ + strLit? (t.consumeMData.getArg! 0) == some "arrow" + let domE := ((e.getArg! 1).consumeMData.getArg! 1).consumeMData + let dom ← if isArrow domE then `(core_type| ($(args[0]!))) else pure args[0]! + annot (← `(core_type| $dom -> $(args[1]!))) + else if args.isEmpty then + annot (← `(core_type| $(nameIdent n):ident)) + else + let args ← args.mapM fun a => `(core_type| ($a)) + annot (← `(core_type| $(nameIdent n):ident $args*)) + else if e.isAppOfArity ``Lambda.LMonoTy.ftvar 1 then + let some n := strLit? (e.getArg! 0) | embed + annot (← `(core_type| $(nameIdent n):ident)) + else if e.isAppOfArity ``Lambda.LMonoTy.bitvec 1 then + let some n ← Meta.getNatValue? (e.getArg! 0) | embed + annot (← `(core_type| $(nameIdent s!"bv{n}"):ident)) + else + embed + +/-! ## Expressions -/ + +/-- The precedence of an atom. -/ +def atomPrec : Nat := 1024 + +/-- A displayed expression and the precedence it was printed at. -/ +structure Shown where + stx : TSyntax `core_expr + prec : Nat + +/-- Parenthesize `s` where an operand of precedence at least `p` is expected. -/ +def Shown.at (s : Shown) (p : Nat) : DelabM (TSyntax `core_expr) := + if s.prec < p then `(core_expr| ($(s.stx))) else pure s.stx + +/-- Precedences of the infix built-ins: the operator's, then its two operands'. -/ +def infixPrec? : String → Option (Nat × Nat × Nat) + | "Int.Mul" | "Int.Div" | "Int.Mod" => some (70, 70, 71) + | "Int.Add" | "Int.Sub" => some (65, 65, 66) + | "Int.Lt" | "Int.Le" | "Int.Gt" | "Int.Ge" => some (50, 51, 51) + | "Bool.And" => some (35, 35, 36) + | "Bool.Or" => some (30, 30, 31) + | "Bool.Implies" => some (25, 26, 25) + | "Bool.Equiv" => some (20, 21, 21) + | _ => none + +def infixStx (o : String) (a b : TSyntax `core_expr) : DelabM (TSyntax `core_expr) := + match o with + | "Int.Mul" => `(core_expr| $a * $b) + | "Int.Div" => `(core_expr| $a / $b) + | "Int.Mod" => `(core_expr| $a % $b) + | "Int.Add" => `(core_expr| $a + $b) + | "Int.Sub" => `(core_expr| $a - $b) + | "Int.Lt" => `(core_expr| $a < $b) + | "Int.Le" => `(core_expr| $a <= $b) + | "Int.Gt" => `(core_expr| $a > $b) + | "Int.Ge" => `(core_expr| $a >= $b) + | "Bool.And" => `(core_expr| $a && $b) + | "Bool.Or" => `(core_expr| $a || $b) + | "Bool.Implies" => `(core_expr| $a ==> $b) + | _ => `(core_expr| $a <==> $b) + +/-- The value of an integer literal, in any of the forms `toExpr` and the elaborator +produce. -/ +def intLit? (e : Lean.Expr) : MetaM (Option Int) := do + if let some i ← Meta.getIntValue? e then return some i + let e := e.consumeMData + if e.isAppOfArity ``Int.ofNat 1 then + return (← Meta.getNatValue? (e.getArg! 0)).map Int.ofNat + if e.isAppOfArity ``Int.negSucc 1 then + return (← Meta.getNatValue? (e.getArg! 0)).map Int.negSucc + return none + +/-- The Core expression at the current position. `bound` names the enclosing binders, +innermost first, for de Bruijn indices. -/ +partial def coreExpr (bound : List String) : DelabM Shown := do + let e := (← getExpr).consumeMData + let atom (stx : TSyntax `core_expr) : DelabM Shown := do return ⟨← annot stx, atomPrec⟩ + let embed : DelabM Shown := do + return ⟨← `(core_expr| ⦃$(← withOptionAtCurrPos `pp.core false delab)⦄), atomPrec⟩ + -- a literal whose value is not a numeral or `true`/`false`: show the value itself + let embedLit : DelabM Shown := do + return ⟨← `(core_expr| ⦃$(← withNaryArg 2 (withNaryArg 0 delab))⦄), atomPrec⟩ + let some c := e.getAppFn.constName? | embed + match c, e.getAppNumArgs with + | ``Lambda.LExpr.fvar, 4 => + let some x := identName? (e.getArg! 2) | embed + if x.startsWith "old " then + let arg ← `(core_expr| $(nameIdent (x.drop 4).toString):ident) + atom (← `(core_expr| $(nameIdent "old"):ident($arg))) + else atom (← `(core_expr| $(nameIdent x):ident)) + | ``Lambda.LExpr.bvar, 3 => + let some i ← Meta.getNatValue? (e.getArg! 2) | embed + let some x := bound[i]? | embed + atom (← `(core_expr| $(nameIdent x):ident)) + | ``Lambda.LExpr.op, 4 => + let some o := identName? (e.getArg! 2) | embed + atom (← `(core_expr| $(opIdent o):ident)) + | ``Lambda.LExpr.const, 3 => + let k := (e.getArg! 2).consumeMData + if k.isAppOfArity ``Lambda.LConst.intConst 1 then + let some i ← intLit? (k.getArg! 0) | embedLit + let n := Syntax.mkNumLit (toString i.natAbs) + if i < 0 then return ⟨← annot (← `(core_expr| -$n:num)), 75⟩ + else atom (← `(core_expr| $n:num)) + else if k.isAppOfArity ``Lambda.LConst.boolConst 1 then + match (k.getArg! 0).consumeMData with + | .const ``Bool.true _ => atom (← `(core_expr| true)) + | .const ``Bool.false _ => atom (← `(core_expr| false)) + | _ => embedLit + else if k.isAppOfArity ``Lambda.LConst.strConst 1 then + let some s := strLit? (k.getArg! 0) | embed + atom (← `(core_expr| $(Syntax.mkStrLit s):str)) + else embed + | ``Lambda.LExpr.eq, 4 => + let a ← withNaryArg 2 (coreExpr bound) + let b ← withNaryArg 3 (coreExpr bound) + return ⟨← annot (← `(core_expr| $(← a.at 51) == $(← b.at 51))), 50⟩ + | ``Lambda.LExpr.ite, 5 => + let i ← withNaryArg 2 (coreExpr bound) + let t ← withNaryArg 3 (coreExpr bound) + let f ← withNaryArg 4 (coreExpr bound) + return ⟨← annot (← `(core_expr| if $(i.stx) then $(t.stx) else $(← f.at 10))), 10⟩ + | ``Lambda.LExpr.abs, 5 => + let x := (strLit? (e.getArg! 2)).getD "x" + let ty ← withNaryArg 3 optType + let body ← withNaryArg 4 (coreExpr (x :: bound)) + return ⟨← annot (← `(core_expr| fun $(nameIdent x) : $ty => $(body.stx))), 10⟩ + | ``Lambda.LExpr.quant, 7 => + let x := (strLit? (e.getArg! 3)).getD "x" + let ty ← withNaryArg 4 optType + let body ← withNaryArg 6 (coreExpr (x :: bound)) + let all := (e.getArg! 2).consumeMData.isConstOf ``Lambda.QuantifierKind.all + let stx ← if all then `(core_expr| forall $(nameIdent x) : $ty :: $(body.stx)) + else `(core_expr| exists $(nameIdent x) : $ty :: $(body.stx)) + return ⟨← annot stx, 10⟩ + | ``Lambda.LExpr.app, 4 => + let (o, head, args) ← spine bound + match o, args with + | some o, #[a, b] => + if let some (p, pa, pb) := infixPrec? o then + return ⟨← annot (← infixStx o (← a.at pa) (← b.at pb)), p⟩ + call head args + | some "Bool.Not", #[a] => return ⟨← annot (← `(core_expr| !$(← a.at 75))), 75⟩ + | some "Int.Neg", #[a] => return ⟨← annot (← `(core_expr| -$(← a.at 75))), 75⟩ + | _, _ => call head args + | _, _ => embed +where + /-- `app (… (app f a₁) …) aₙ`: the operator name if `f` is one, `f`, and the `aᵢ`. -/ + spine (bound : List String) : DelabM (Option String × Shown × Array Shown) := do + let e := (← getExpr).consumeMData + if e.isAppOfArity ``Lambda.LExpr.app 4 then + let (o, head, args) ← withNaryArg 2 (spine bound) + return (o, head, args.push (← withNaryArg 3 (coreExpr bound))) + else + let o := if e.isAppOfArity ``Lambda.LExpr.op 4 then identName? (e.getArg! 2) else none + return (o, ← coreExpr bound, #[]) + call (head : Shown) (args : Array Shown) : DelabM Shown := do + let args := args.map (·.stx) + return ⟨← annot (← `(core_expr| $(← head.at atomPrec)($args,*))), atomPrec⟩ + /-- An optional type annotation; a missing one prints as `_`. -/ + optType : DelabM (TSyntax `core_type) := do + let e := (← getExpr).consumeMData + if e.isAppOfArity ``Option.some 2 then withNaryArg 1 coreType + else `(core_type| $(mkIdent `_):ident) + +/-! ## Statements -/ + +def label? (l : String) : DelabM (Option (TSyntax `core_label)) := + if l.isEmpty then pure none else some <$> `(core_label| [$(nameIdent l)]: ) + +def guardStx : DelabM (TSyntax `core_guard) := do + let e := (← getExpr).consumeMData + if e.isAppOfArity ``Imperative.ExprOrNondet.det 2 then + let c ← withNaryArg 1 (coreExpr []) + `(core_guard| ($(c.stx))) + else `(core_guard| *) + +mutual +partial def coreStmt : DelabM (TSyntax `core_stmt) := do + let e := (← getExpr).consumeMData + let embed : DelabM (TSyntax `core_stmt) := do `(core_stmt| ⦃$(← withOptionAtCurrPos `pp.core false delab)⦄) + if e.isAppOfArity ``Imperative.Stmt.cmd 3 then + withNaryArg 2 coreCommand + else if e.isAppOfArity ``Imperative.Stmt.block 5 then + let b ← withNaryArg 3 coreBlock + let l := (strLit? (e.getArg! 2)).getD "" + if l.isEmpty then + annot (← `(core_stmt| $b:core_block)) + else + let lbl := nameIdent l + annot (← `(core_stmt| $lbl:ident : $b:core_block)) + else if e.isAppOfArity ``Imperative.Stmt.ite 6 then + let c ← withNaryArg 2 guardStx + let t ← withNaryArg 3 coreBlock + if (e.getArg! 4).consumeMData.isAppOfArity ``List.nil 1 then + annot (← `(core_stmt| if $c $t)) + else + let f ← withNaryArg 4 coreBlock + annot (← `(core_stmt| if $c $t else $f)) + else if e.isAppOfArity ``Imperative.Stmt.loop 7 then + let g ← withNaryArg 2 guardStx + let m := (e.getArg! 3).consumeMData + let measure ← if m.isAppOfArity ``Option.some 2 then + withNaryArg 3 (withNaryArg 1 do + let d ← coreExpr [] + some <$> `(core_loop_spec| decreases $(d.stx))) + else pure none + let some invs ← withNaryArg 4 (listLit? invariant) | embed + let body ← withNaryArg 5 coreBlock + let specs := measure.toArray ++ invs + annot (← `(core_stmt| while $g $specs* $body:core_block)) + else if e.isAppOfArity ``Imperative.Stmt.exit 4 then + let some l := strLit? (e.getArg! 2) | embed + annot (← `(core_stmt| exit $(nameIdent l))) + else embed +where + invariant : DelabM (TSyntax `core_loop_spec) := do + let e := (← getExpr).consumeMData + if e.isAppOfArity ``Prod.mk 4 then + let l ← label? ((strLit? (e.getArg! 2)).getD "") + let i := (← withNaryArg 3 (coreExpr [])).stx + `(core_loop_spec| invariant $[$l]? $i:core_expr) + else + let t ← delab + `(core_loop_spec| invariant ⦃$t⦄) + +partial def coreCommand : DelabM (TSyntax `core_stmt) := do + let e := (← getExpr).consumeMData + let embed : DelabM (TSyntax `core_stmt) := do `(core_stmt| ⦃$(← withOptionAtCurrPos `pp.core false delab)⦄) + if e.isAppOfArity ``Imperative.CmdExt.cmd 2 then + withNaryArg 1 coreCmd + else if e.isAppOfArity ``Imperative.CmdExt.call 4 then + let some p := strLit? (e.getArg! 1) | embed + let some args ← withNaryArg 2 (listLit? callArg) | embed + annot (← `(core_stmt| call $(nameIdent p)($args,*))) + else embed +where + callArg : DelabM (TSyntax `core_call_arg) := do + let e := (← getExpr).consumeMData + if e.isAppOfArity ``Imperative.CallArg.inArg 2 then + let a ← withNaryArg 1 (coreExpr []) + `(core_call_arg| $(a.stx):core_expr) + else if let some x := (if e.getAppNumArgs == 2 then identName? (e.getArg! 1) else none) then + if e.isAppOf ``Imperative.CallArg.outArg then `(core_call_arg| out $(nameIdent x)) + else `(core_call_arg| inout $(nameIdent x)) + else `(core_call_arg| ⦃$(← withOptionAtCurrPos `pp.core false delab)⦄) + +partial def coreCmd : DelabM (TSyntax `core_stmt) := do + let e := (← getExpr).consumeMData + let embed : DelabM (TSyntax `core_stmt) := do `(core_stmt| ⦃$(← withOptionAtCurrPos `pp.core false delab)⦄) + let det? (i : Nat) : DelabM (Option (TSyntax `core_expr)) := do + let d := (e.getArg! i).consumeMData + if d.isAppOfArity ``Imperative.ExprOrNondet.det 2 then + some <$> withNaryArg i (withNaryArg 1 do return (← coreExpr []).stx) + else pure none + if e.isAppOfArity ``Imperative.Cmd.set 4 then + let some x := identName? (e.getArg! 1) | embed + match ← det? 2 with + | some v => annot (← `(core_stmt| $(nameIdent x):ident := $v)) + | none => annot (← `(core_stmt| havoc $(nameIdent x))) + else if e.isAppOfArity ``Imperative.Cmd.init 5 then + let some x := identName? (e.getArg! 1) | embed + let ty ← withNaryArg 2 do + let t := (← getExpr).consumeMData + if t.isAppOfArity ``Lambda.LTy.forAll 2 then withNaryArg 1 coreType + else `(core_type| ⦃$(← withOptionAtCurrPos `pp.core false delab)⦄) + let v ← det? 3 + annot (← `(core_stmt| var $(nameIdent x) : $ty $[:= $v]?)) + else if e.getAppNumArgs == 4 ∧ (e.isAppOf ``Imperative.Cmd.assert ∨ + e.isAppOf ``Imperative.Cmd.assume ∨ e.isAppOf ``Imperative.Cmd.cover) then + let l ← label? ((strLit? (e.getArg! 1)).getD "") + let b ← withNaryArg 2 (coreExpr []) + if e.isAppOf ``Imperative.Cmd.assert then annot (← `(core_stmt| assert $[$l]? $(b.stx):core_expr)) + else if e.isAppOf ``Imperative.Cmd.assume then annot (← `(core_stmt| assume $[$l]? $(b.stx):core_expr)) + else annot (← `(core_stmt| cover $[$l]? $(b.stx):core_expr)) + else embed + +partial def coreBlock : DelabM (TSyntax `core_block) := do + match ← listLit? coreStmt with + | some ss => `(core_block| { $ss;* }) + | none => `(core_block| ⦃$(← withOptionAtCurrPos `pp.core false delab)⦄) +end + +/-! ## Procedures -/ + +/-- A parameter `(x, ty)` of a signature. -/ +def param : DelabM (Option (String × TSyntax `core_type)) := do + let e := (← getExpr).consumeMData + unless e.isAppOfArity ``Prod.mk 4 do return none + let some x := identName? (e.getArg! 2) | return none + return some (x, ← withNaryArg 3 coreType) + +/-- A specification clause `(label, check)`, as a `requires` or `ensures` clause. -/ +def clause (isPost : Bool) : DelabM (Option (TSyntax `core_clause)) := do + let e := (← getExpr).consumeMData + unless e.isAppOfArity ``Prod.mk 4 do return none + let chk := (e.getArg! 3).consumeMData + unless chk.isAppOfArity ``Imperative.Check.mk 4 do return none + let l ← label? ((strLit? (e.getArg! 2)).getD "") + let b ← withNaryArg 3 (withNaryArg 1 (coreExpr [])) + let free := (chk.getArg! 2).consumeMData.isConstOf ``Imperative.CheckAttr.Free + match isPost, free with + | true, true => some <$> `(core_clause| free ensures $[$l]? $(b.stx):core_expr) + | true, false => some <$> `(core_clause| ensures $[$l]? $(b.stx):core_expr) + | false, true => some <$> `(core_clause| free requires $[$l]? $(b.stx):core_expr) + | false, false => some <$> `(core_clause| requires $[$l]? $(b.stx):core_expr) + +def coreProc : DelabM (TSyntax `core_proc) := do + let e := (← getExpr).consumeMData + guard (e.isAppOfArity ``Imperative.Procedure.mk 8) + let hdr := (e.getArg! 5).consumeMData + guard (hdr.isAppOfArity ``Core.Procedure.Header.mk 5) + let some name := identName? (hdr.getArg! 0) | failure + let some ins ← withNaryArg 5 (withNaryArg 2 (listLit? param)) | failure + let some outs ← withNaryArg 5 (withNaryArg 3 (listLit? param)) | failure + let some ins := ins.mapM id | failure + let some outs := outs.mapM id | failure + let outNames := outs.map (·.1) + let inNames := ins.map (·.1) + let mut params := #[] + for (x, ty) in ins do + params := params.push <| ← if outNames.contains x then `(core_param| inout $(nameIdent x) : $ty) + else `(core_param| $(nameIdent x):ident : $ty) + for (x, ty) in outs do + unless inNames.contains x do params := params.push (← `(core_param| out $(nameIdent x) : $ty)) + let spec := (e.getArg! 6).consumeMData + guard (spec.isAppOfArity ``Imperative.Spec.mk 3) + let some pres ← withNaryArg 6 (withNaryArg 1 (listLit? (clause false))) | failure + let some posts ← withNaryArg 6 (withNaryArg 2 (listLit? (clause true))) | failure + let some clauses := (pres ++ posts).mapM id | failure + let body := (e.getArg! 7).consumeMData + guard (body.isAppOfArity ``Imperative.Body.structured 3) + let some ss ← withNaryArg 7 (withNaryArg 2 (listLit? coreStmt)) | failure + `(core_proc| procedure $(nameIdent name)($params,*) spec { $[$clauses;]* } { $ss;* }) + +/-! ## Delaborators -/ + +@[delab app.Lambda.LExpr.app, delab app.Lambda.LExpr.fvar, delab app.Lambda.LExpr.bvar, + delab app.Lambda.LExpr.op, delab app.Lambda.LExpr.const, delab app.Lambda.LExpr.eq, + delab app.Lambda.LExpr.ite, delab app.Lambda.LExpr.abs, delab app.Lambda.LExpr.quant] +def delabExpr : Delab := whenPPOption getPPCore do + let e ← getExpr + let arity := match e.getAppFn.constName? with + | some ``Lambda.LExpr.app | some ``Lambda.LExpr.fvar | some ``Lambda.LExpr.op + | some ``Lambda.LExpr.eq => 4 + | some ``Lambda.LExpr.ite | some ``Lambda.LExpr.abs => 5 + | some ``Lambda.LExpr.quant => 7 + | _ => 3 + guard (e.getAppNumArgs == arity) + `(⟪$((← coreExpr []).stx)⟫) + +@[delab app.Imperative.Stmt.cmd, delab app.Imperative.Stmt.block, delab app.Imperative.Stmt.ite, + delab app.Imperative.Stmt.loop, delab app.Imperative.Stmt.exit] +def delabStmt : Delab := whenPPOption getPPCore do + let e ← getExpr + guard (e.getAppNumArgs ≥ 3) + let s ← coreStmt + `(⟦$s:core_stmt⟧) + +/-- A list literal of statements prints as one block. -/ +@[delab app.List.cons] +def delabStmts : Delab := whenPPOption getPPCore do + let e ← getExpr + guard (e.getAppNumArgs == 3) + let elem ← Meta.whnfR (e.getArg! 0) + guard (elem.isAppOf ``Imperative.Stmt) + let some ss ← listLit? coreStmt | failure + `(⟦$ss;*⟧) + +@[delab app.Imperative.Procedure.mk] +def delabProc : Delab := whenPPOption getPPCore do + let p ← coreProc + `(⟦$p:core_proc⟧) + +end Strata.Deep.Delab diff --git a/StrataBoole/HoareLogic/Deep/Exec.lean b/StrataBoole/HoareLogic/Deep/Exec.lean new file mode 100644 index 0000000..02c73f4 --- /dev/null +++ b/StrataBoole/HoareLogic/Deep/Exec.lean @@ -0,0 +1,254 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +module + +public import StrataBoole.HoareLogic.Deep.Lang + +/-! # Deep embedding of Core: big-step semantics + +`Exec ss σ o` says that running the statement list `ss` from `σ` can end with outcome +`o`. It is the ground truth of the deep embedding: the triple (`Deep/Triple.lean`) is +defined from it, and every proof rule (`Deep/Spec.lean`) is a theorem about it. + +* **Failure is an outcome.** A run ends in `.failure` when a check fails: an `assert`, + a loop invariant, or a `decreases` obligation. It also fails when it meets an + expression or a statement outside the fragment. A triple rules out failure, so it + covers every assertion in the program. +* **`assume` discards runs.** `assume e` has no outcome when `e` is false. +* **Loops are checked the way Core checks them.** Each time control reaches the loop + head, every invariant must hold and the measure must be a non-negative integer. + After each iteration of the body, the measure must have decreased. +* **Only terminating runs are described**, so the triple is partial correctness. The + `decreases` checks are still enforced on every iteration a run makes. +* **Nondeterministic control is every choice.** `if (*)` runs either branch and `while (*)` + any number of iterations, with the same head checks as a guarded loop; `cover` is a skip. +-/ + +@[expose] public section + +namespace Strata.Deep + +open Imperative + +/-! ## Outcomes -/ + +/-- How a run ends: normally in a state, or with a failed check. -/ +inductive Outcome where + | normal (σ : State) + | failure + +/-- `Q` holds of a normal outcome. A failure satisfies no postcondition. -/ +def Outcome.Sat (Q : State → Prop) : Outcome → Prop + | .normal σ => Q σ + | .failure => False + +/-! ## The fragment -/ + +/-- The statement forms the semantics covers. Every other form (calls, `cover`, `exit`, +nondeterministic guards, type declarations) fails, so a triple about a program that +uses one cannot be proved. -/ +def Supported : Core.Statement → Prop + | .cmd (.cmd (.init _ _ _ _)) => True + | .cmd (.cmd (.set _ _ _)) => True + | .cmd (.cmd (.assert _ _ _)) => True + | .cmd (.cmd (.assume _ _ _)) => True + | .cmd (.cmd (.cover _ _ _)) => True + | .ite _ _ _ _ => True + | .block _ _ _ => True + | .loop _ _ _ _ _ => True + | _ => False + +mutual +/-- The variables a statement may assign: the targets of `var`, `:=` and `havoc`, +including those in nested blocks. -/ +def Stmt.mods : Core.Statement → List String + | .cmd (.cmd (.init x _ _ _)) => [x.name] + | .cmd (.cmd (.set x _ _)) => [x.name] + | .ite _ t f _ => Block.mods t ++ Block.mods f + | .block _ b _ => Block.mods b + | .loop _ _ _ b _ => Block.mods b + | _ => [] + +/-- The variables a statement list may assign. -/ +def Block.mods : List Core.Statement → List String + | [] => [] + | s :: ss => Stmt.mods s ++ Block.mods ss +end + +/-- `σ` with each variable of `xs` replaced by its value in `τ`. A loop's head states are +of this form, with `xs` the variables its body may assign. -/ +def State.havoc (σ : State) (xs : List String) (τ : State) : State := + fun y => if y ∈ xs then τ y else σ y + +/-! ## Loop checks -/ + +/-- `P`, carrying the label `l` of the program clause it comes from. The label is only a name +for the reader of a verification condition: `Labeled l P` unfolds to `P`. -/ +def Labeled (_l : String) (P : Prop) : Prop := P + +/-- Every invariant holds, each under its label. -/ +def InvsHold : List (String × Expr) → State → Prop + | [], _ => True + | (l, e) :: invs, σ => Labeled l (Holds σ e) ∧ InvsHold invs σ + +/-- The measure, if there is one, is a non-negative integer. -/ +def MeasureNonneg : Option Expr → State → Prop + | none, _ => True + | some e, σ => + match evalInt σ e with + | some k => 0 ≤ k + | none => False + +/-- The measure, if there is one, is smaller in `σ'` (after an iteration) than in `σ` +(before it). -/ +def MeasureDecreased : Option Expr → State → State → Prop + | none, _, _ => True + | some e, σ, σ' => + match evalInt σ e, evalInt σ' e with + | some k, some k' => k' < k + | _, _ => False + +/-- What Core checks whenever control reaches a loop head (`loop_entry` in the CFG Core +lowers loops to): the invariants, then the lower bound of the measure. -/ +def LoopHead (invs : List (String × Expr)) (m : Option Expr) (σ : State) : Prop := + InvsHold invs σ ∧ MeasureNonneg m σ + +/-! ## Execution -/ + +/-- `Exec ss σ o`: running `ss` from `σ` can end with outcome `o`. Each compound +statement has one constructor for a normal run of its body, followed by the rest of the +list, and one for a body that fails. -/ +inductive Exec : List Core.Statement → State → Outcome → Prop where + | nil : Exec [] σ (.normal σ) + -- `x := e` + | set (he : eval σ e = some v) (k : Exec ss (σ.update x.name v) o) : + Exec (.cmd (.cmd (.set x (.det e) md)) :: ss) σ o + | set_fail (he : eval σ e = none) : + Exec (.cmd (.cmd (.set x (.det e) md)) :: ss) σ .failure + -- `havoc x` + | havoc (k : Exec ss (σ.update x.name v) o) : + Exec (.cmd (.cmd (.set x .nondet md)) :: ss) σ o + -- `var x : T := e` + | init (he : eval σ e = some v) (k : Exec ss (σ.update x.name v) o) : + Exec (.cmd (.cmd (.init x ty (.det e) md)) :: ss) σ o + | init_fail (he : eval σ e = none) : + Exec (.cmd (.cmd (.init x ty (.det e) md)) :: ss) σ .failure + -- `var x : T` + | init_havoc (k : Exec ss (σ.update x.name v) o) : + Exec (.cmd (.cmd (.init x ty .nondet md)) :: ss) σ o + -- `assert e` + | assert (he : Holds σ e) (k : Exec ss σ o) : + Exec (.cmd (.cmd (.assert l e md)) :: ss) σ o + | assert_fail (he : ¬ Holds σ e) : + Exec (.cmd (.cmd (.assert l e md)) :: ss) σ .failure + -- `assume e` + | assume (he : MayHold σ e) (k : Exec ss σ o) : + Exec (.cmd (.cmd (.assume l e md)) :: ss) σ o + -- `cover e`: a skip + | cover (k : Exec ss σ o) : + Exec (.cmd (.cmd (.cover l e md)) :: ss) σ o + -- `if (c) { t } else { f }` + | ite_true (hc : evalBool σ c = some true) (ht : Exec t σ (.normal σ')) (k : Exec ss σ' o) : + Exec (.ite (.det c) t f md :: ss) σ o + | ite_true_fail (hc : evalBool σ c = some true) (ht : Exec t σ .failure) : + Exec (.ite (.det c) t f md :: ss) σ .failure + | ite_false (hc : evalBool σ c = some false) (hf : Exec f σ (.normal σ')) (k : Exec ss σ' o) : + Exec (.ite (.det c) t f md :: ss) σ o + | ite_false_fail (hc : evalBool σ c = some false) (hf : Exec f σ .failure) : + Exec (.ite (.det c) t f md :: ss) σ .failure + | ite_fail (hc : evalBool σ c = none) : + Exec (.ite (.det c) t f md :: ss) σ .failure + -- `if (*) { t } else { f }`: either branch + | ite_nondet_true (ht : Exec t σ (.normal σ')) (k : Exec ss σ' o) : + Exec (.ite .nondet t f md :: ss) σ o + | ite_nondet_true_fail (ht : Exec t σ .failure) : + Exec (.ite .nondet t f md :: ss) σ .failure + | ite_nondet_false (hf : Exec f σ (.normal σ')) (k : Exec ss σ' o) : + Exec (.ite .nondet t f md :: ss) σ o + | ite_nondet_false_fail (hf : Exec f σ .failure) : + Exec (.ite .nondet t f md :: ss) σ .failure + -- `{ b }`; variables declared in `b` stay visible after it + | block (hb : Exec b σ (.normal σ')) (k : Exec ss σ' o) : + Exec (.block l b md :: ss) σ o + | block_fail (hb : Exec b σ .failure) : + Exec (.block l b md :: ss) σ .failure + -- `while (g) decreases m invariant invs { b }` + | loop_head_fail (hh : ¬ LoopHead invs m σ) : + Exec (.loop (.det g) m invs b md :: ss) σ .failure + | loop_guard_fail (hh : LoopHead invs m σ) (hg : evalBool σ g = none) : + Exec (.loop (.det g) m invs b md :: ss) σ .failure + | loop_exit (hh : LoopHead invs m σ) (hg : evalBool σ g = some false) + (k : Exec ss σ o) : + Exec (.loop (.det g) m invs b md :: ss) σ o + | loop_body_fail (hh : LoopHead invs m σ) (hg : evalBool σ g = some true) + (hb : Exec b σ .failure) : + Exec (.loop (.det g) m invs b md :: ss) σ .failure + | loop_measure_fail (hh : LoopHead invs m σ) (hg : evalBool σ g = some true) + (hb : Exec b σ (.normal σ')) (hd : ¬ MeasureDecreased m σ σ') : + Exec (.loop (.det g) m invs b md :: ss) σ .failure + | loop_iter (hh : LoopHead invs m σ) (hg : evalBool σ g = some true) + (hb : Exec b σ (.normal σ')) (hd : MeasureDecreased m σ σ') + (k : Exec (.loop (.det g) m invs b md :: ss) σ' o) : + Exec (.loop (.det g) m invs b md :: ss) σ o + -- `while (*) decreases m invariant invs { b }`: any number of iterations + | loopN_head_fail (hh : ¬ LoopHead invs m σ) : + Exec (.loop .nondet m invs b md :: ss) σ .failure + | loopN_exit (hh : LoopHead invs m σ) (k : Exec ss σ o) : + Exec (.loop .nondet m invs b md :: ss) σ o + | loopN_body_fail (hh : LoopHead invs m σ) (hb : Exec b σ .failure) : + Exec (.loop .nondet m invs b md :: ss) σ .failure + | loopN_measure_fail (hh : LoopHead invs m σ) (hb : Exec b σ (.normal σ')) + (hd : ¬ MeasureDecreased m σ σ') : + Exec (.loop .nondet m invs b md :: ss) σ .failure + | loopN_iter (hh : LoopHead invs m σ) (hb : Exec b σ (.normal σ')) + (hd : MeasureDecreased m σ σ') (k : Exec (.loop .nondet m invs b md :: ss) σ' o) : + Exec (.loop .nondet m invs b md :: ss) σ o + -- everything outside the fragment + | unsupported (hs : ¬ Supported s) : Exec (s :: ss) σ .failure + +/-- The weakest liberal precondition read off `Exec`: no run of `ss` from `σ` fails, +and every run that ends normally ends in `Q`. -/ +def semWP (ss : List Core.Statement) (Q : State → Prop) (σ : State) : Prop := + ∀ o, Exec ss σ o → o.Sat Q + +/-! ## Framing -/ + +/-- A run changes only the variables the statements may assign. -/ +theorem Exec.frame {ss : List Core.Statement} {σ : State} {o : Outcome} (h : Exec ss σ o) : + ∀ σ', o = .normal σ' → ∀ y, y ∉ Block.mods ss → σ' y = σ y := by + induction h with + | nil => intro _ h _ _; cases h; rfl + | set _ _ ih | havoc _ ih | init _ _ ih | init_havoc _ ih => + intro σ' h y hy + simp only [Block.mods, Stmt.mods, List.cons_append, List.nil_append, List.mem_cons, + not_or] at hy + rw [ih σ' h y hy.2] + simp [State.update, hy.1] + | assert _ _ ih | assume _ _ ih | cover _ ih => + intro σ' h y hy + exact ih σ' h y (by simpa [Block.mods, Stmt.mods] using hy) + | ite_true _ _ _ iht ihk | ite_false _ _ _ iht ihk | block _ _ iht ihk + | ite_nondet_true _ _ iht ihk | ite_nondet_false _ _ iht ihk => + intro σ' h y hy + simp only [Block.mods, Stmt.mods, List.mem_append, not_or] at hy + rw [ihk σ' h y (by simp_all), iht _ rfl y (by simp_all)] + | loop_exit _ _ _ ih | loopN_exit _ _ ih => + intro σ' h y hy + exact ih σ' h y (by simp_all [Block.mods, Stmt.mods]) + | loop_iter _ _ _ _ _ ihb ihk | loopN_iter _ _ _ _ ihb ihk => + intro σ' h y hy + rw [ihk σ' h y hy, ihb _ rfl y (by simp_all [Block.mods, Stmt.mods])] + | _ => intro _ h; cases h + +/-- A state that agrees with `σ` outside `xs` is `σ` havocked at `xs`. -/ +theorem State.havoc_self {σ σ' : State} {xs : List String} + (h : ∀ y, y ∉ xs → σ' y = σ y) : σ.havoc xs σ' = σ' := by + funext y + by_cases hy : y ∈ xs <;> simp [State.havoc, hy, h] + +end Strata.Deep + +end diff --git a/StrataBoole/HoareLogic/Deep/Lang.lean b/StrataBoole/HoareLogic/Deep/Lang.lean new file mode 100644 index 0000000..a6f7cf8 --- /dev/null +++ b/StrataBoole/HoareLogic/Deep/Lang.lean @@ -0,0 +1,238 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +module + +public import Strata.Languages.Core.Statement + +/-! # Deep embedding of Core: values, states, expressions + +A deep embedding of Strata Core in the style of the `lean-vcgen-tutorial`: Core +programs stay ASTs (`Core.Statement`), and their meaning is a relation (`Exec`, in +`Deep/Exec.lean`). This file fixes the value model and gives the expression fragment its +meaning. + +**Values are tagged, projections are total.** `Val` has an `int` and a `bool` +constructor. Every read goes through `Val.toInt` / `Val.toBool`, which are total, so an +operator never fails on a mistyped operand. Core programs are type checked before +verification, so a well-typed program never reaches the defaults. Equality is the one +operator whose meaning depends on a type: `==` compares integers as integers and +booleans as booleans, at the type the translator annotated its operands with. A +well-typed state therefore never has to be assumed: no verification condition mentions +a value's tag. + +**Expressions outside the fragment are undefined.** `eval` returns `none` for any +expression it does not cover (maps, unknown operators, ...). Statements treat an undefined +expression as a failure (`Deep/Exec.lean`), so a program outside the fragment cannot be +verified, rather than verified vacuously. + +**Clauses are propositions.** An `assert`, a `requires`, an `ensures` or an `invariant` may +quantify over integers and booleans, which no evaluator computes. `SatT`/`SatF` read a clause +as a Lean proposition: quantifiers become Lean quantifiers over the values of the bound type, +connectives become connectives, and an atom is true when it evaluates to `true`, with the bound +values in scope. +-/ + +@[expose] public section + +namespace Strata.Deep + +/-! ## Values and states -/ + +inductive Val where + | int (i : Int) + | bool (b : Bool) + deriving DecidableEq, Repr, Inhabited + +namespace Val + +/-- Read a value as an integer; a boolean reads as `0`. -/ +def toInt : Val → Int + | int i => i + | bool _ => 0 + +/-- Read a value as a boolean; an integer reads as `false`. -/ +def toBool : Val → Bool + | bool b => b + | int _ => false + +/-- Stated as rewrite lemmas rather than by `rfl`, so that `simp` applies them through +congruence and re-synthesizes a `Decidable` instance whose proposition they change. -/ +@[simp] theorem toInt_int (i : Int) : (int i).toInt = i := by simp [toInt] +@[simp] theorem toBool_bool (b : Bool) : (bool b).toBool = b := by simp [toBool] + +/-- The type a value's tag says it has; a bound variable is typed by its value. -/ +def ty : Val → Lambda.LMonoTy + | int _ => .tcons "int" [] + | bool _ => .tcons "bool" [] + +end Val + +/-- A state maps each variable name to its value. Every name has a value, so a state +never needs to be checked for definedness. -/ +abbrev State := String → Val + +def State.update (σ : State) (x : String) (v : Val) : State := + fun y => if y = x then v else σ y + +/-! ## Expressions -/ + +abbrev Expr := Core.Expression.Expr + +/-- Core's unary built-ins, by their factory names (`Strata/DL/Lambda/IntBoolFactory.lean`). -/ +def unop : String → Val → Option Val + | "Int.Neg", v => some (.int (- v.toInt)) + | "Bool.Not", v => some (.bool (! v.toBool)) + | _, _ => none + +/-- Core's binary built-ins. `Int.Div` and `Int.Mod` are undefined on a zero divisor, +matching the factory, which only evaluates them for a nonzero divisor. -/ +def binop : String → Val → Val → Option Val + | "Int.Add", v, w => some (.int (v.toInt + w.toInt)) + | "Int.Sub", v, w => some (.int (v.toInt - w.toInt)) + | "Int.Mul", v, w => some (.int (v.toInt * w.toInt)) + | "Int.Div", v, w => if w.toInt = 0 then none else some (.int (v.toInt / w.toInt)) + | "Int.Mod", v, w => if w.toInt = 0 then none else some (.int (v.toInt % w.toInt)) + | "Int.Lt", v, w => some (.bool (decide (v.toInt < w.toInt))) + | "Int.Le", v, w => some (.bool (decide (v.toInt ≤ w.toInt))) + | "Int.Gt", v, w => some (.bool (decide (v.toInt > w.toInt))) + | "Int.Ge", v, w => some (.bool (decide (v.toInt ≥ w.toInt))) + | "Bool.And", v, w => some (.bool (v.toBool && w.toBool)) + | "Bool.Or", v, w => some (.bool (v.toBool || w.toBool)) + | "Bool.Implies", v, w => some (.bool (!v.toBool || w.toBool)) + | "Bool.Equiv", v, w => some (.bool (v.toBool == w.toBool)) + | _, _, _ => none + +/-- The type of `e`, read off the annotations the Core translator leaves on variables +and operators (an operator's annotation is its arrow type), with `bs` the values of the +bound variables in scope, innermost first, whose tags give their types. -/ +def typeOf (bs : List Val) : Expr → Option Lambda.LMonoTy + | .const _ (.intConst _) => some (.tcons "int" []) + | .const _ (.boolConst _) => some (.tcons "bool" []) + | .fvar _ _ ty => ty + | .bvar _ i => (bs[i]?).map Val.ty + | .app _ (.app _ (.op _ _ (some (.tcons "arrow" [_, .tcons "arrow" [_, r]]))) _) _ => some r + | .app _ (.op _ _ (some (.tcons "arrow" [_, r]))) _ => some r + | .ite _ _ t _ => typeOf bs t + | .eq _ _ _ => some (.tcons "bool" []) + | _ => none + +/-- Equality at a type: integers compare as integers, booleans as booleans. It is +undefined at any other type. -/ +def eqAt : Option Lambda.LMonoTy → Val → Val → Option Val + | some (.tcons "int" []), v, w => some (.bool (decide (v.toInt = w.toInt))) + | some (.tcons "bool" []), v, w => some (.bool (decide (v.toBool = w.toBool))) + | _, _, _ => none + +/-- The value of a Core expression in `σ`, with `bs` the values of the bound variables in +scope, innermost first; `none` outside the fragment. Built-ins are applied curried, +`app (app (op o) a) b`, as the Core translator produces them. -/ +def evalIn (σ : State) (bs : List Val) : Expr → Option Val + | .const _ (.intConst i) => some (.int i) + | .const _ (.boolConst b) => some (.bool b) + | .fvar _ x _ => some (σ x.name) + | .bvar _ i => bs[i]? + | .app _ (.app _ (.op _ o _) a) b => + match evalIn σ bs a, evalIn σ bs b with + | some va, some vb => binop o.name va vb + | _, _ => none + | .app _ (.op _ o _) a => + match evalIn σ bs a with + | some va => unop o.name va + | none => none + | .ite _ c t e => + match evalIn σ bs c with + | some vc => if vc.toBool then evalIn σ bs t else evalIn σ bs e + | none => none + | .eq _ a b => + match evalIn σ bs a, evalIn σ bs b with + | some va, some vb => eqAt (typeOf bs a) va vb + | _, _ => none + | _ => none + +/-- The value of a closed Core expression in `σ`, or `none` outside the fragment. -/ +def eval (σ : State) (e : Expr) : Option Val := evalIn σ [] e + +/-- The value of `e` read as a boolean, with bound values `bs`; `none` if `e` is undefined. -/ +def evalBoolIn (σ : State) (bs : List Val) (e : Expr) : Option Bool := + (evalIn σ bs e).map Val.toBool + +/-- The value of `e` read as a boolean; `none` if `e` is undefined. -/ +def evalBool (σ : State) (e : Expr) : Option Bool := (eval σ e).map Val.toBool + +/-- The value of `e` read as an integer; `none` if `e` is undefined. -/ +def evalInt (σ : State) (e : Expr) : Option Int := (eval σ e).map Val.toInt + +/-! ## Clauses + +A clause may quantify; its meaning is a proposition. `SatT σ bs e` says `e` is true at `σ` +with the bound values `bs` in scope, `SatF` that it is false. A quantifier over `int` or +`bool` is the Lean quantifier over `Int` or `Bool`, the body read with the bound value pushed +on `bs`; a connective is the Lean connective (`==>` an implication, `<==>` an equivalence); +anything else is an atom, true or false according to its value. An atom outside the fragment +is neither true nor false. -/ + +mutual +/-- `e` is true at `σ`, with bound values `bs`. The shape is matched first and the operator +name second, so that `simp` can reduce the match on a concrete expression. -/ +def SatT (σ : State) (bs : List Val) : Expr → Prop + | .quant _ .all _ ty _ body => + if ty = some (.tcons "int" []) then ∀ i : Int, SatT σ (.int i :: bs) body + else if ty = some (.tcons "bool" []) then ∀ b : Bool, SatT σ (.bool b :: bs) body + else False + | .quant _ .exist _ ty _ body => + if ty = some (.tcons "int" []) then ∃ i : Int, SatT σ (.int i :: bs) body + else if ty = some (.tcons "bool" []) then ∃ b : Bool, SatT σ (.bool b :: bs) body + else False + | e@(.app _ (.app _ (.op _ o _) a) b) => + match o.name with + | "Bool.And" => SatT σ bs a ∧ SatT σ bs b + | "Bool.Or" => SatT σ bs a ∨ SatT σ bs b + | "Bool.Implies" => SatT σ bs a → SatT σ bs b + | "Bool.Equiv" => SatT σ bs a ↔ SatT σ bs b + | _ => evalBoolIn σ bs e = some true + | e@(.app _ (.op _ o _) a) => + match o.name with + | "Bool.Not" => SatF σ bs a + | _ => evalBoolIn σ bs e = some true + | e => evalBoolIn σ bs e = some true + +/-- `e` is false at `σ`, with bound values `bs`. -/ +def SatF (σ : State) (bs : List Val) : Expr → Prop + | .quant _ .all _ ty _ body => + if ty = some (.tcons "int" []) then ∃ i : Int, SatF σ (.int i :: bs) body + else if ty = some (.tcons "bool" []) then ∃ b : Bool, SatF σ (.bool b :: bs) body + else False + | .quant _ .exist _ ty _ body => + if ty = some (.tcons "int" []) then ∀ i : Int, SatF σ (.int i :: bs) body + else if ty = some (.tcons "bool" []) then ∀ b : Bool, SatF σ (.bool b :: bs) body + else False + | e@(.app _ (.app _ (.op _ o _) a) b) => + match o.name with + | "Bool.And" => SatF σ bs a ∨ SatF σ bs b + | "Bool.Or" => SatF σ bs a ∧ SatF σ bs b + | "Bool.Implies" => SatT σ bs a ∧ SatF σ bs b + | "Bool.Equiv" => ¬ (SatT σ bs a ↔ SatT σ bs b) + | _ => evalBoolIn σ bs e = some false + | e@(.app _ (.op _ o _) a) => + match o.name with + | "Bool.Not" => SatT σ bs a + | _ => evalBoolIn σ bs e = some false + | e => evalBoolIn σ bs e = some false +end + +/-- `e` is true at `σ`. This is what a program must establish: asserts, postconditions, +loop invariants. -/ +def Holds (σ : State) (e : Expr) : Prop := SatT σ [] e + +/-- `e` is not false at `σ`: it is true, or it is outside the fragment. This is what a +program may assume (`assume`, `requires`). Dropping an assumption that cannot be +evaluated over-approximates the runs, so it is sound, and it keeps such an assumption +from making a triple hold vacuously. -/ +def MayHold (σ : State) (e : Expr) : Prop := ¬ SatF σ [] e + +end Strata.Deep + +end diff --git a/StrataBoole/HoareLogic/Deep/Spec.lean b/StrataBoole/HoareLogic/Deep/Spec.lean new file mode 100644 index 0000000..6e4ef81 --- /dev/null +++ b/StrataBoole/HoareLogic/Deep/Spec.lean @@ -0,0 +1,257 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +module + +public import StrataBoole.HoareLogic.Deep.Triple + +/-! # Deep embedding of Core: proof rules + +One rule per statement form, each a theorem about `Exec`. A rule concludes +`semWP (s :: ss) Q σ` for a statement `s` and reduces it to premises about the rest of +the list: either smaller `semWP` goals, or *verification conditions* (VCs) that mention +no program. `core_vcgen` (`Deep/Tactic.lean`) applies the rules backwards until only VCs +are left, the way `vcgen` applies `@[spec]` lemmas in the `lean-vcgen-tutorial`. + +The premises of a rule are ordered so that a VC comes first and the continuation last. +Their names (`defined`, `assertion`, `entry`, `step`, `ifTrue`, `rest`, …) become the +case tags of the goals `core_vcgen` leaves, so a tag such as `rest.step.rest` reads as +the path to the obligation: +* a definedness VC `(eval σ e).isSome`: the expression is in the fragment; +* a check VC: an assertion, or a loop invariant or measure obligation, wrapped in `Labeled` + with the clause's label where the program has one; +* a continuation: `semWP` of what runs next, possibly under binders (a fresh value, a + guard hypothesis, a loop head state). + +`Exec.unsupported` gives every list one extra run, which fails unless the head statement +is supported. Each proof dismisses that run with `absurd trivial`: `Supported s` reduces +to `True` for the statement forms that have a rule. +-/ + +@[expose] public section + +namespace Strata.Deep + +open Imperative + +variable {Q : State → Prop} {σ : State} {ss : List Core.Statement} + {e c g : Expr} {x : Core.CoreIdent} {l : String} {md : MetaData Core.Expression} + +/-- The empty list: the postcondition must hold now. -/ +theorem wp_nil (h : Q σ) : semWP [] Q σ := by + intro o ho + cases ho with + | nil => exact h + +/-- `x := e`: Hoare's assignment rule. The new value is a fresh `v`, with the hypothesis +`some v = eval σ e`, so the VCs stay readable until `core_lift` evaluates `e`. The +variable is on the left so that `simp_all` substitutes it once `e` is evaluated. -/ +theorem wp_set (defined : (eval σ e).isSome) + (rest : ∀ v, some v = eval σ e → semWP ss Q (σ.update x.name v)) : + semWP (.cmd (.cmd (.set x (.det e) md)) :: ss) Q σ := by + intro o ho + cases ho with + | set he k => exact rest _ he.symm _ k + | set_fail he => simp [he] at defined + | unsupported hs => exact absurd trivial hs + +/-- `havoc x`: the rest must work for every value of `x`. -/ +theorem wp_havoc (rest : ∀ v, semWP ss Q (σ.update x.name v)) : + semWP (.cmd (.cmd (.set x .nondet md)) :: ss) Q σ := by + intro o ho + cases ho with + | havoc k => exact rest _ _ k + | unsupported hs => exact absurd trivial hs + +/-- `var x : T := e`: as `x := e`. -/ +theorem wp_init {ty : Core.Expression.Ty} (defined : (eval σ e).isSome) + (rest : ∀ v, some v = eval σ e → semWP ss Q (σ.update x.name v)) : + semWP (.cmd (.cmd (.init x ty (.det e) md)) :: ss) Q σ := by + intro o ho + cases ho with + | init he k => exact rest _ he.symm _ k + | init_fail he => simp [he] at defined + | unsupported hs => exact absurd trivial hs + +/-- `var x : T`: as `havoc x`. -/ +theorem wp_init_havoc {ty : Core.Expression.Ty} (rest : ∀ v, semWP ss Q (σ.update x.name v)) : + semWP (.cmd (.cmd (.init x ty .nondet md)) :: ss) Q σ := by + intro o ho + cases ho with + | init_havoc k => exact rest _ _ k + | unsupported hs => exact absurd trivial hs + +/-- `assert e`: a VC that `e` holds, under the statement's label, then the rest. -/ +theorem wp_assert (assertion : Labeled l (Holds σ e)) (rest : semWP ss Q σ) : + semWP (.cmd (.cmd (.assert l e md)) :: ss) Q σ := by + intro o ho + cases ho with + | assert _ k => exact rest _ k + | assert_fail hne => exact absurd assertion hne + | unsupported hs => exact absurd trivial hs + +/-- `assume e`: the rest, under the hypothesis, labeled like the statement, that `e` may +hold. -/ +theorem wp_assume (rest : Labeled l (MayHold σ e) → semWP ss Q σ) : + semWP (.cmd (.cmd (.assume l e md)) :: ss) Q σ := by + intro o ho + cases ho with + | assume he k => exact rest he _ k + | unsupported hs => exact absurd trivial hs + +/-- `cover e`: a skip. -/ +theorem wp_cover (rest : semWP ss Q σ) : semWP (.cmd (.cmd (.cover l e md)) :: ss) Q σ := by + intro o ho + cases ho with + | cover k => exact rest _ k + | unsupported hs => exact absurd trivial hs + +/-- `if (*) { t } else { f }`: both branches, followed by the rest. -/ +theorem wp_ite_nondet {t f : List Core.Statement} + (ifTrue : semWP t (semWP ss Q) σ) (ifFalse : semWP f (semWP ss Q) σ) : + semWP (.ite .nondet t f md :: ss) Q σ := by + intro o ho + cases ho with + | ite_nondet_true h k => exact ifTrue _ h _ k + | ite_nondet_true_fail h => exact False.elim (ifTrue _ h) + | ite_nondet_false h k => exact ifFalse _ h _ k + | ite_nondet_false_fail h => exact False.elim (ifFalse _ h) + | unsupported hs => exact absurd trivial hs + +/-- `if (c) { t } else { f }`: each branch, under its value of the guard, followed by +the rest. -/ +theorem wp_ite {t f : List Core.Statement} (defined : (evalBool σ c).isSome) + (ifTrue : evalBool σ c = some true → semWP t (semWP ss Q) σ) + (ifFalse : evalBool σ c = some false → semWP f (semWP ss Q) σ) : + semWP (.ite (.det c) t f md :: ss) Q σ := by + intro o ho + cases ho with + | ite_true hc h k => exact ifTrue hc _ h _ k + | ite_true_fail hc h => exact False.elim (ifTrue hc _ h) + | ite_false hc h k => exact ifFalse hc _ h _ k + | ite_false_fail hc h => exact False.elim (ifFalse hc _ h) + | ite_fail hc => simp [hc] at defined + | unsupported hs => exact absurd trivial hs + +/-- `{ b }`: the block, followed by the rest. -/ +theorem wp_block {b : List Core.Statement} (hb : semWP b (semWP ss Q) σ) : + semWP (.block l b md :: ss) Q σ := by + intro o ho + cases ho with + | block h k => exact hb _ h _ k + | block_fail h => exact False.elim (hb _ h) + | unsupported hs => exact absurd trivial hs + +/-- `while (g) decreases m invariant invs { b }`, with the annotations the program +carries. The head states are `σ.havoc (Block.mods b) τ` for an arbitrary `τ`: the body +can change only the variables it assigns, so every other variable keeps its value from +`σ`. This is the frame Core's verifier gets by havocking just the modified variables. +* `entry`: the invariants and the measure bound hold on entry. +* `guardDefined`: the guard is defined at every head state. +* `step`: an iteration from a head state, with the guard true, re-establishes the + invariants and the bound, and decreases the measure. +* `exit`: from a head state with the guard false, the rest of the list runs. + +The proof inducts on the runs of the loop. -/ +theorem wp_loop {m : Option Expr} {invs : List (String × Expr)} {b : List Core.Statement} + (entry : LoopHead invs m σ) + (guardDefined : ∀ τ, LoopHead invs m (σ.havoc (Block.mods b) τ) → + (evalBool (σ.havoc (Block.mods b) τ) g).isSome) + (step : ∀ τ, LoopHead invs m (σ.havoc (Block.mods b) τ) → + evalBool (σ.havoc (Block.mods b) τ) g = some true → + semWP b (fun σ' => LoopHead invs m σ' ∧ + MeasureDecreased m (σ.havoc (Block.mods b) τ) σ') (σ.havoc (Block.mods b) τ)) + (exit : ∀ τ, LoopHead invs m (σ.havoc (Block.mods b) τ) → + evalBool (σ.havoc (Block.mods b) τ) g = some false → + semWP ss Q (σ.havoc (Block.mods b) τ)) : + semWP (.loop (.det g) m invs b md :: ss) Q σ := by + -- Strengthen to an arbitrary head state `σ₁`: one that agrees with `σ` outside the + -- body's variables and passes the head checks. + suffices key : ∀ l σ₁ o, Exec l σ₁ o → l = .loop (.det g) m invs b md :: ss → + (∀ y, y ∉ Block.mods b → σ₁ y = σ y) → LoopHead invs m σ₁ → o.Sat Q from + fun o ho => key _ _ _ ho rfl (fun _ _ => rfl) entry + intro l σ₁ o h + induction h with + | loop_head_fail hh => intro hl _ hh₁; cases hl; exact absurd hh₁ hh + | loop_guard_fail hh hg => + intro hl hfr _ + cases hl + have := guardDefined _ (by rwa [State.havoc_self hfr]); rw [State.havoc_self hfr] at this + simp [hg] at this + | loop_exit hh hg k _ => + intro hl hfr _ + cases hl + have := exit _ (by rwa [State.havoc_self hfr]) (by rwa [State.havoc_self hfr]) + rw [State.havoc_self hfr] at this + exact this _ k + | loop_body_fail hh hg hb => + intro hl hfr _ + cases hl + have := step _ (by rwa [State.havoc_self hfr]) (by rwa [State.havoc_self hfr]) + rw [State.havoc_self hfr] at this + exact False.elim (this _ hb) + | loop_measure_fail hh hg hb hd => + intro hl hfr _ + cases hl + have := step _ (by rwa [State.havoc_self hfr]) (by rwa [State.havoc_self hfr]) + rw [State.havoc_self hfr] at this + exact absurd (this _ hb).2 hd + | loop_iter hh hg hb hd k _ ih => + intro hl hfr _ + cases hl + have := step _ (by rwa [State.havoc_self hfr]) (by rwa [State.havoc_self hfr]) + rw [State.havoc_self hfr] at this + refine ih rfl (fun y hy => ?_) (this _ hb).1 + rw [hb.frame _ rfl y hy, hfr y hy] + | unsupported hs => intro hl _ _; cases hl; exact absurd trivial hs + | _ => intro hl; cases hl + +/-- `while (*) decreases m invariant invs { b }`: the loop rule with nothing learned from a +guard. The head states are `σ.havoc (Block.mods b) τ` as for `wp_loop`. -/ +theorem wp_loop_nondet {m : Option Expr} {invs : List (String × Expr)} {b : List Core.Statement} + (entry : LoopHead invs m σ) + (step : ∀ τ, LoopHead invs m (σ.havoc (Block.mods b) τ) → + semWP b (fun σ' => LoopHead invs m σ' ∧ + MeasureDecreased m (σ.havoc (Block.mods b) τ) σ') (σ.havoc (Block.mods b) τ)) + (exit : ∀ τ, LoopHead invs m (σ.havoc (Block.mods b) τ) → + semWP ss Q (σ.havoc (Block.mods b) τ)) : + semWP (.loop .nondet m invs b md :: ss) Q σ := by + suffices key : ∀ l σ₁ o, Exec l σ₁ o → l = .loop .nondet m invs b md :: ss → + (∀ y, y ∉ Block.mods b → σ₁ y = σ y) → LoopHead invs m σ₁ → o.Sat Q from + fun o ho => key _ _ _ ho rfl (fun _ _ => rfl) entry + intro l σ₁ o h + induction h with + | loopN_head_fail hh => intro hl _ hh₁; cases hl; exact absurd hh₁ hh + | loopN_exit hh k _ => + intro hl hfr _ + cases hl + have := exit _ (by rwa [State.havoc_self hfr]) + rw [State.havoc_self hfr] at this + exact this _ k + | loopN_body_fail hh hb => + intro hl hfr _ + cases hl + have := step _ (by rwa [State.havoc_self hfr]) + rw [State.havoc_self hfr] at this + exact False.elim (this _ hb) + | loopN_measure_fail hh hb hd => + intro hl hfr _ + cases hl + have := step _ (by rwa [State.havoc_self hfr]) + rw [State.havoc_self hfr] at this + exact absurd (this _ hb).2 hd + | loopN_iter hh hb hd k _ ih => + intro hl hfr _ + cases hl + have := step _ (by rwa [State.havoc_self hfr]) + rw [State.havoc_self hfr] at this + refine ih rfl (fun y hy => ?_) (this _ hb).1 + rw [hb.frame _ rfl y hy, hfr y hy] + | unsupported hs => intro hl _ _; cases hl; exact absurd trivial hs + | _ => intro hl; cases hl + +end Strata.Deep + +end diff --git a/StrataBoole/HoareLogic/Deep/Tactic.lean b/StrataBoole/HoareLogic/Deep/Tactic.lean new file mode 100644 index 0000000..a1a0253 --- /dev/null +++ b/StrataBoole/HoareLogic/Deep/Tactic.lean @@ -0,0 +1,279 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import Lean +import StrataBoole.HoareLogic.Deep.Spec +import StrataBoole.HoareLogic.Lift.Names + +/-! # Deep embedding of Core: tactics + +* `core_vcgen` turns a goal `Procedure.Correct p` (or `Triple P ss Q`) into verification + conditions. It applies the rules of `Deep/Spec.lean` backwards, statement by statement, + as `vcgen` applies `@[spec]` lemmas in the `lean-vcgen-tutorial`. +* `core_lift` names the conditions and evaluates the embedding away in every hypothesis and + the goal (`eval`, `State.update`, the loop and contract predicates), leaving propositions + about `Int` and `Bool`, like the tutorial's `imp_lift`. + +Typical use, after unfolding the procedure: `core_vcgen <;> core_lift <;> omega`. + +The VCs `core_vcgen` leaves still mention the program: they say which Core formulas +must hold in which states, as in `σ.update "m" v ⊨ ⟪m >= x⟫` (with the notation of +`Deep/Delab.lean`), each under the label of its clause (`Labeled "max2_ensures_0" …`). +The binders it introduces have names: `σ` for the initial state and `pre` for the +precondition, `v`/`hv` for an assigned value, `hguard` for a branch condition, +`hassume` for an `assume`, and `τ`/`hhead`/`hguard` for a loop head state. + +`core_lift` then reads like the Strata route's goals: one goal per condition, named +`then.

_ast : Core.Program` when `p` is an identifier, and -every procedure as `_ast : Core.Procedure`. Statements about a procedure, its meaning -`interpProc M _ast` and its specification, are made on these definitions; the program -literal carries the functions, axioms and type declarations the procedure's names refer to. -/ +`shallow_reflect p` type-checks the Boole program `p` (`TypeCheck.lean`) and binds its Core AST +(`ToExpr.lean`): the whole program as `

_ast : Core.Program` when `p` is an identifier, and +every procedure as `_ast : Core.Procedure`. Statements about a procedure, such as its +contract triple, are made on these definitions; the program literal carries the functions, +axioms and type declarations the procedure's names refer to. -/ open Lean Elab Command -namespace Strata.Shallow.Interp +namespace Strata.Reflect syntax (name := shallowReflect) "shallow_reflect " term : command @[command_elab shallowReflect] def elabShallowReflect : CommandElab := fun stx => do let `(shallow_reflect $t:term) := stx | throwUnsupportedSyntax - let prog ← liftTermElabM (Pipeline.evalProgram t) + let prog ← liftTermElabM (evalProgram t) let ns ← getCurrNamespace if let `($x:ident) := t then let pgmName := ns ++ Name.mkSimple s!"{x.getId.eraseMacroScopes.getString!}_ast" - liftTermElabM (Reflect.addProgramAst pgmName prog) + liftTermElabM (addProgramAst pgmName prog) else logWarning "shallow_reflect: the program is bound as a whole only when the argument is an \ identifier; its procedures are bound either way" for d in prog.decls do if let .proc p _ := d then let astName := ns ++ Name.mkSimple s!"{p.header.name.name}_ast" - liftTermElabM (Reflect.addProcedureAst astName p) + liftTermElabM (addProcedureAst astName p) -end Strata.Shallow.Interp +end Strata.Reflect diff --git a/StrataBoole/HoareLogic/Reflect/Core.lean b/StrataBoole/HoareLogic/Reflect/Core.lean new file mode 100644 index 0000000..6f2c3da --- /dev/null +++ b/StrataBoole/HoareLogic/Reflect/Core.lean @@ -0,0 +1,243 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import Lean +import Strata.Languages.Core.DDMTransform.Translate +import Strata.Languages.Core.Verifier + +/-! # Core programs as Lean terms + +`#core_reflect prog` takes a program `prog` written in Core syntax +(`def prog := #strata program Core; … #end`). At elaboration time it runs Strata's Core +translator and type checker on it, and defines ` : Core.Procedure` in the current +namespace for each procedure ``. The value of that definition is the translated AST, +written out as a term, so that the procedure's statements and expressions are visible to +`rfl`, `simp` and the rules, which the result of `translateProgram` is not: the translation is +built from `partial` definitions and never reduces. The definition is reducible, so that +tactics see through the name without being told it. + +The AST is the *type-checked* program, the one Core's verifier works on. Type checking also +annotates every variable and operator with its type, which the typing witnesses of the +denotational reading require. + +Metadata (source locations) is replaced by `MetaData.empty`: the semantics never reads it. +Type declarations and CFG bodies are rejected. + +This file is not a `module`, so its elaborator needs no `meta` phase annotations. A file that +uses `#core_reflect` imports it as an ordinary file. -/ + +namespace Strata.CoreReflect + +open Lean Elab Command Meta + +/-- Run Strata's Core translator and type checker, reporting their errors. -/ +def translateCore (p : StrataDDM.Program) : Except String Core.Program := + let (prog, errs) := TransM.run Inhabited.default (translateProgram p) + if errs.isEmpty then + match Core.typeCheck { Core.VerifyOptions.default with verbose := .quiet } prog with + | .ok prog => .ok prog + | .error msg => .error s!"type checking failed: {msg}" + else .error (String.intercalate "\n" errs.toList) + +/-! ## Building terms -/ + +/-- The implicit arguments every AST constructor takes. -/ +structure Ctx where + /-- The `LExprParamsT` of `Core.Expression.Expr`. -/ + T : Lean.Expr + /-- `Core.Expression`. -/ + P : Lean.Expr + /-- `Core.Command`. -/ + C : Lean.Expr + +def mkCtx : MetaM Ctx := do + let P := mkConst ``Core.Expression + let exprTy ← whnfR (mkApp (mkConst ``Imperative.PureExpr.Expr) P) + let some T := exprTy.app1? ``Lambda.LExpr + | throwError "#core_reflect: unexpected shape of Core.Expression.Expr: {exprTy}" + return { T, P, C := mkConst ``Core.Command } + +def mkList (ty : Lean.Expr) (xs : List Lean.Expr) : Lean.Expr := + xs.foldr (fun x acc => mkApp3 (mkConst ``List.cons [0]) ty x acc) + (mkApp (mkConst ``List.nil [0]) ty) + +def mkOption (ty : Lean.Expr) : Option Lean.Expr → Lean.Expr + | none => mkApp (mkConst ``Option.none [0]) ty + | some e => mkApp2 (mkConst ``Option.some [0]) ty e + +def mkPair (α β a b : Lean.Expr) : Lean.Expr := mkApp4 (mkConst ``Prod.mk [0, 0]) α β a b + +def mkProd (α β : Lean.Expr) : Lean.Expr := mkApp2 (mkConst ``Prod [0, 0]) α β + +def unitE : Lean.Expr := mkConst ``Unit.unit +def stringTy : Lean.Expr := mkConst ``String +def monoTyTy : Lean.Expr := mkConst ``Lambda.LMonoTy +def identTy : Lean.Expr := mkApp (mkConst ``Lambda.Identifier) (mkConst ``Unit) + +def identE (x : Lambda.Identifier Unit) : Lean.Expr := + mkApp3 (mkConst ``Lambda.Identifier.mk) (mkConst ``Unit) (toExpr x.name) unitE + +partial def monoTyE : Lambda.LMonoTy → Lean.Expr + | .ftvar n => mkApp (mkConst ``Lambda.LMonoTy.ftvar) (toExpr n) + | .tcons n args => + mkApp2 (mkConst ``Lambda.LMonoTy.tcons) (toExpr n) (mkList monoTyTy (args.map monoTyE)) + | .bitvec n => mkApp (mkConst ``Lambda.LMonoTy.bitvec) (toExpr n) + +def lTyE : Lambda.LTy → Lean.Expr + | .forAll vs ty => + mkApp2 (mkConst ``Lambda.LTy.forAll) (mkList stringTy (vs.map toExpr)) (monoTyE ty) + +def constE : Lambda.LConst → Lean.Expr + | .intConst i => mkApp (mkConst ``Lambda.LConst.intConst) (toExpr i) + | .strConst s => mkApp (mkConst ``Lambda.LConst.strConst) (toExpr s) + | .rationalConst r => + mkApp (mkConst ``Lambda.LConst.rationalConst) + (mkApp2 (mkConst ``Rat.divInt) (toExpr r.num) (toExpr (r.den : Int))) + | .bitvecConst n b => mkApp2 (mkConst ``Lambda.LConst.bitvecConst) (toExpr n) (toExpr b) + | .boolConst b => mkApp (mkConst ``Lambda.LConst.boolConst) (toExpr b) + +def quantE : Lambda.QuantifierKind → Lean.Expr + | .all => mkConst ``Lambda.QuantifierKind.all + | .exist => mkConst ``Lambda.QuantifierKind.exist + +def optTyE (ty : Option Lambda.LMonoTy) : Lean.Expr := mkOption monoTyTy (ty.map monoTyE) + +partial def exprE (c : Ctx) : Core.Expression.Expr → Lean.Expr + | .const _ k => mkApp3 (mkConst ``Lambda.LExpr.const) c.T unitE (constE k) + | .op _ o ty => mkApp4 (mkConst ``Lambda.LExpr.op) c.T unitE (identE o) (optTyE ty) + | .bvar _ i => mkApp3 (mkConst ``Lambda.LExpr.bvar) c.T unitE (toExpr i) + | .fvar _ x ty => mkApp4 (mkConst ``Lambda.LExpr.fvar) c.T unitE (identE x) (optTyE ty) + | .abs _ n ty e => + mkApp5 (mkConst ``Lambda.LExpr.abs) c.T unitE (toExpr n) (optTyE ty) (exprE c e) + | .quant _ k n ty tr e => + mkAppN (mkConst ``Lambda.LExpr.quant) + #[c.T, unitE, quantE k, toExpr n, optTyE ty, exprE c tr, exprE c e] + | .app _ f a => mkApp4 (mkConst ``Lambda.LExpr.app) c.T unitE (exprE c f) (exprE c a) + | .ite _ x y z => + mkApp5 (mkConst ``Lambda.LExpr.ite) c.T unitE (exprE c x) (exprE c y) (exprE c z) + | .eq _ a b => mkApp4 (mkConst ``Lambda.LExpr.eq) c.T unitE (exprE c a) (exprE c b) + +def exprTy (c : Ctx) : Lean.Expr := mkApp (mkConst ``Imperative.PureExpr.Expr) c.P + +def mdE (c : Ctx) : Lean.Expr := mkApp (mkConst ``Imperative.MetaData.empty) c.P + +def eonE (c : Ctx) : Imperative.ExprOrNondet Core.Expression → Lean.Expr + | .det e => mkApp2 (mkConst ``Imperative.ExprOrNondet.det) c.P (exprE c e) + | .nondet => mkApp (mkConst ``Imperative.ExprOrNondet.nondet) c.P + +def cmdE (c : Ctx) : Imperative.Cmd Core.Expression → Lean.Expr + | .init x ty e _ => + mkApp5 (mkConst ``Imperative.Cmd.init) c.P (identE x) (lTyE ty) (eonE c e) (mdE c) + | .set x e _ => mkApp4 (mkConst ``Imperative.Cmd.set) c.P (identE x) (eonE c e) (mdE c) + | .assert l e _ => + mkApp4 (mkConst ``Imperative.Cmd.assert) c.P (toExpr l) (exprE c e) (mdE c) + | .assume l e _ => + mkApp4 (mkConst ``Imperative.Cmd.assume) c.P (toExpr l) (exprE c e) (mdE c) + | .cover l e _ => + mkApp4 (mkConst ``Imperative.Cmd.cover) c.P (toExpr l) (exprE c e) (mdE c) + +def callArgE (c : Ctx) : Imperative.CallArg Core.Expression → Lean.Expr + | .inArg e => mkApp2 (mkConst ``Imperative.CallArg.inArg) c.P (exprE c e) + | .inoutArg x => mkApp2 (mkConst ``Imperative.CallArg.inoutArg) c.P (identE x) + | .outArg x => mkApp2 (mkConst ``Imperative.CallArg.outArg) c.P (identE x) + +def commandE (c : Ctx) : Core.Command → Lean.Expr + | .cmd k => mkApp2 (mkConst ``Imperative.CmdExt.cmd) c.P (cmdE c k) + | .call p args _ => + mkApp4 (mkConst ``Imperative.CmdExt.call) c.P (toExpr p) + (mkList (mkApp (mkConst ``Imperative.CallArg) c.P) (args.map (callArgE c))) (mdE c) + +mutual +partial def stmtE (c : Ctx) : Core.Statement → Except String Lean.Expr + | .cmd k => pure <| mkApp3 (mkConst ``Imperative.Stmt.cmd) c.P c.C (commandE c k) + | .block l b _ => do + pure <| mkApp5 (mkConst ``Imperative.Stmt.block) c.P c.C (toExpr l) (← stmtsE c b) (mdE c) + | .ite g t f _ => do + pure <| mkAppN (mkConst ``Imperative.Stmt.ite) + #[c.P, c.C, eonE c g, ← stmtsE c t, ← stmtsE c f, mdE c] + | .loop g m invs b _ => do + let invTy := mkProd stringTy (exprTy c) + let invsE := mkList invTy (invs.map fun (l, e) => mkPair stringTy (exprTy c) (toExpr l) (exprE c e)) + pure <| mkAppN (mkConst ``Imperative.Stmt.loop) + #[c.P, c.C, eonE c g, mkOption (exprTy c) (m.map (exprE c)), invsE, ← stmtsE c b, mdE c] + | .exit l _ => pure <| mkApp4 (mkConst ``Imperative.Stmt.exit) c.P c.C (toExpr l) (mdE c) + | .typeDecl _ _ => throw "type declarations are not supported" + +partial def stmtsE (c : Ctx) (ss : List Core.Statement) : Except String Lean.Expr := do + return mkList (mkApp2 (mkConst ``Imperative.Stmt) c.P c.C) (← ss.mapM (stmtE c)) +end + +def checkE (c : Ctx) (ch : Imperative.Check Core.Expression) : Lean.Expr := + let attr := match ch.attr with + | .Free => mkConst ``Imperative.CheckAttr.Free + | .Default => mkConst ``Imperative.CheckAttr.Default + mkApp4 (mkConst ``Imperative.Check.mk) c.P (exprE c ch.expr) attr (mdE c) + +def specE (c : Ctx) (s : Imperative.Spec Core.Expression) : Lean.Expr := + let checkTy := mkApp (mkConst ``Imperative.Check) c.P + let clauses (cs : ListMap String (Imperative.Check Core.Expression)) := + mkList (mkProd stringTy checkTy) + (cs.toList.map fun (l, ch) => mkPair stringTy checkTy (toExpr l) (checkE c ch)) + mkApp3 (mkConst ``Imperative.Spec.mk) c.P (clauses s.preconditions) (clauses s.postconditions) + +def sigE (sig : @Lambda.LMonoTySignature Unit) : Lean.Expr := + mkList (mkProd identTy monoTyTy) + (sig.toList.map fun (x, ty) => mkPair identTy monoTyTy (identE x) (monoTyE ty)) + +def headerE (h : Core.Procedure.Header) : Lean.Expr := + mkApp5 (mkConst ``Core.Procedure.Header.mk) (identE h.name) + (mkList stringTy (h.typeArgs.map toExpr)) (sigE h.inputs) (sigE h.outputs) + (mkList stringTy (h.lemmas.map toExpr)) + +def procedureE (c : Ctx) (p : Core.Procedure) : MetaM Lean.Expr := do + let ss ← match p.body with + | .structured ss => pure ss + | .cfg _ => throwError "#core_reflect: procedure {p.header.name.name} has a CFG body" + let body ← match stmtsE c ss with + | .ok e => pure e + | .error msg => throwError "#core_reflect: procedure {p.header.name.name}: {msg}" + mkAppM ``Imperative.Procedure.mk + #[headerE p.header, specE c p.spec, mkApp3 (mkConst ``Imperative.Body.structured) c.P c.C body] + +/-! ## The command -/ + +/-- Translate `prog`. The call is elaborated from syntax, so that `#strata`'s +`SourcedProgram` is coerced to the `Program` the translator expects. -/ +unsafe def evalTranslateUnsafe (prog : Name) : TermElabM (Except String Core.Program) := do + let ty := mkApp2 (mkConst ``Except [0, 0]) stringTy (mkConst ``Core.Program) + let e ← Term.elabTermEnsuringType (← `(translateCore $(mkIdent prog))) ty + Term.synthesizeSyntheticMVarsNoPostponing + Meta.evalExpr (Except String Core.Program) ty (← instantiateMVars e) + +@[implemented_by evalTranslateUnsafe] +opaque evalTranslate (prog : Name) : TermElabM (Except String Core.Program) + +/-- `#core_reflect prog` defines ` : Core.Procedure` in the current namespace for +each procedure `` of the Core program `prog`, with the translated AST as its +value. -/ +syntax (name := coreReflect) "#core_reflect " ident : command + +@[command_elab coreReflect] def elabCoreReflect : CommandElab := fun stx => do + let prog ← liftCoreM <| realizeGlobalConstNoOverloadWithInfo stx[1] + let pgm ← match ← liftTermElabM (evalTranslate prog) with + | .ok pgm => pure pgm + | .error msg => throwError "#core_reflect: {msg}" + let ctx ← liftTermElabM mkCtx + for d in pgm.decls do + let .proc p _ := d | continue + let value ← liftTermElabM (procedureE ctx p) + let name := (← getCurrNamespace) ++ .mkSimple p.header.name.name + liftTermElabM <| do + let type := mkConst ``Core.Procedure + check value + unless ← isDefEq (← inferType value) type do + throwError "#core_reflect: the term for {name} does not have type Core.Procedure" + liftCoreM <| addDecl <| .defnDecl { + name, levelParams := [], type := mkConst ``Core.Procedure, value, + hints := .abbrev, safety := .safe } + liftCoreM <| setReducibilityStatus name .reducible + logInfo m!"defined {name} : Core.Procedure" + +end Strata.CoreReflect diff --git a/StrataBoole/Shallow/Interpreter/Reflect.lean b/StrataBoole/HoareLogic/Reflect/ToExpr.lean similarity index 99% rename from StrataBoole/Shallow/Interpreter/Reflect.lean rename to StrataBoole/HoareLogic/Reflect/ToExpr.lean index 9c602b0..6d88e1c 100644 --- a/StrataBoole/Shallow/Interpreter/Reflect.lean +++ b/StrataBoole/HoareLogic/Reflect/ToExpr.lean @@ -23,7 +23,7 @@ for the Core instantiation `Core.Expression`. -/ open Lean Meta open Lambda Imperative -namespace Strata.Shallow.Reflect +namespace Strata.Reflect /-! ## Leaves -/ @@ -238,4 +238,4 @@ def addProgramAst (name : Name) (p : Core.Program) : MetaM Unit := do let _ ← mkAuxDefinition name (mkConst ``Core.Program) value enableRealizationsForConst name -end Strata.Shallow.Reflect +end Strata.Reflect diff --git a/StrataBoole/Shallow/Pipeline.lean b/StrataBoole/HoareLogic/Reflect/TypeCheck.lean similarity index 62% rename from StrataBoole/Shallow/Pipeline.lean rename to StrataBoole/HoareLogic/Reflect/TypeCheck.lean index fd6b435..6bc0a2f 100644 --- a/StrataBoole/Shallow/Pipeline.lean +++ b/StrataBoole/HoareLogic/Reflect/TypeCheck.lean @@ -7,16 +7,15 @@ import StrataBoole.Verify /-! # From Boole source to a type-checked Core program, at elaboration time -The translator (`shallow_embed`) and the interpreter's command (`shallow_reflect`, -`Interpreter/Command.lean`) start from the same object: the Core program -obtained by `Strata.Boole.typeCheck`, that is `getProgram → toCoreProgram → Core.typeCheck`, -before any Core transform phase. This file is the one place that computes it, so the two sides -cannot disagree about which program they talk about. The computation runs compiled code -(`Term.evalTerm`): its result is a value in the elaborator, not a term the kernel can reduce. -/ +`shallow_reflect` (`Boole.lean`) starts from the Core program obtained by +`Strata.Boole.typeCheck`, that is `getProgram → toCoreProgram → Core.typeCheck`, before any Core +transform phase: the program Core's verifier works on. This file computes it. The computation +runs compiled code (`Term.evalTerm`): its result is a value in the elaborator, not a term the +kernel can reduce. -/ open Lean Elab Term Meta -namespace Strata.Shallow.Pipeline +namespace Strata.Reflect /-- Lower and type-check; render the error as a string so the result can be evaluated at elaboration time without naming Strata's message type. -/ @@ -28,7 +27,7 @@ def typeCheckStr (p : StrataDDM.Program) : Except String Core.Program := unsafe def evalProgramUnsafe (t : Term) : TermElabM Core.Program := do let ty := mkApp2 (mkConst ``Except [.zero, .zero]) (mkConst ``String) (mkConst ``Core.Program) let r ← Term.evalTerm (Except String Core.Program) ty - (← `(Strata.Shallow.Pipeline.typeCheckStr $t)) + (← `(Strata.Reflect.typeCheckStr $t)) match r with | .ok p => pure p | .error m => throwError m!"Core type checking failed: {m}" @@ -37,4 +36,4 @@ unsafe def evalProgramUnsafe (t : Term) : TermElabM Core.Program := do @[implemented_by evalProgramUnsafe] opaque evalProgram (t : Term) : TermElabM Core.Program -end Strata.Shallow.Pipeline +end Strata.Reflect diff --git a/StrataBoole/Shallow/Layer.lean b/StrataBoole/HoareLogic/Shallow/Layer.lean similarity index 100% rename from StrataBoole/Shallow/Layer.lean rename to StrataBoole/HoareLogic/Shallow/Layer.lean diff --git a/StrataBoole/Shallow/Emit.lean b/StrataBoole/Shallow/Emit.lean deleted file mode 100644 index 8d92cc1..0000000 --- a/StrataBoole/Shallow/Emit.lean +++ /dev/null @@ -1,173 +0,0 @@ -/- - Copyright Strata Contributors - - SPDX-License-Identifier: Apache-2.0 OR MIT --/ -import Lean -import Std.Do -import Std.Tactic.Do -import StrataBoole.Shallow.Layer - -/-! # Shallow embedding: emitting Lean syntax - -Builders for the `do`-notation programs and `Triple` theorems that the Core-to-Lean -translator produces (`StrataBoole.Shallow.Translate`). This half has no dependency on -Strata, so the shape of the output can be fixed and tested on its own. - -The generated code refers to the layer (`Strata.Shallow.ND.*`) by full name (the layer is -imported here so the quotations pre-resolve those names) and wraps each theorem in -`open Std.Do in`, because the triple notations `⦃ ⦄`, `⌜ ⌝`, `⇓` are scoped. The output shape follows `StrataBooleTest/shallow_find_max.lean`: -parameters are arguments, locals are `let mut`, a loop is `whileInv` on the tuple of -the variables its body assigns. --/ - -open Lean Elab Command Term Meta -open Std.Do - -namespace Strata.Shallow.Emit - -abbrev DoItem := TSyntax ``Lean.Parser.Term.doSeqItem -abbrev DoElem := TSyntax `doElem - -/-- Wrap a `doElem` as a sequence item. -/ -def item (e : DoElem) : MacroM DoItem := `(Lean.Parser.Term.doSeqItem| $e:doElem) - -/-- `do` block from items; an empty block is `pure ()`. -/ -def doBlock (items : Array DoItem) : MacroM Term := do - if items.isEmpty then `(do pure ()) else `(do $items*) - -/-! ## Tuples: right-nested products, as Lean's `(a, b, c)` -/ - -/-- `(a, b, c)`; `()` for none; the term itself for one. -/ -def tuple (xs : Array Term) : MacroM Term := do - match xs.size with - | 0 => `(()) - | 1 => pure xs[0]! - | _ => - let x := xs[0]! - let rest := xs[1:].toArray - `(($x, $rest,*)) - -/-- `A × B × C`; `Unit` for none. -/ -def tupleType (ts : Array Term) : MacroM Term := do - match ts.size with - | 0 => `(Unit) - | _ => do - let mut acc := ts.back! - for t in ts.pop.reverse do - acc ← `($t × $acc) - pure acc - -/-- Projection of component `j` out of `k` from a right-nested tuple `s`. -/ -def proj (s : Term) (j k : Nat) : MacroM Term := do - if k ≤ 1 then pure s - else - let mut acc := s - for _ in [:j] do - acc ← `(($acc).2) - if j + 1 < k then `(($acc).1) else pure acc - -/-! ## Statements -/ - -def letMut (x : Ident) (ty : Term) (e : Term) : MacroM DoElem := - `(doElem| let mut $x:ident : $ty := $e) - -def letMutHavoc (x : Ident) (ty : Term) : MacroM DoElem := - `(doElem| let mut $x:ident : $ty ← Strata.Shallow.ND.havoc) - -def assign (x : Ident) (e : Term) : MacroM DoElem := - `(doElem| $x:ident := $e) - -def assignHavoc (x : Ident) : MacroM DoElem := - `(doElem| $x:ident ← Strata.Shallow.ND.havoc) - -def assume (p : Term) : MacroM DoElem := - `(doElem| Strata.Shallow.ND.assume $p) - -def assert (p : Term) : MacroM DoElem := - `(doElem| Strata.Shallow.ND.assert $p) - -def ret (e : Term) : MacroM DoElem := - `(doElem| return $e) - -/-- `if c then … else …`; an empty branch becomes `pure ()`. -/ -def ite (c : Term) (thenItems elseItems : Array DoItem) : MacroM DoElem := do - let thenItems ← if thenItems.isEmpty then pure #[← item (← `(doElem| pure ()))] else pure thenItems - if elseItems.isEmpty then - `(doElem| if $c then $thenItems*) - else - `(doElem| if $c then $thenItems* else $elseItems*) - -/-- A nondeterministic branch: `let b ← havoc; if b then … else …`. -/ -def iteNondet (b : Ident) (thenItems elseItems : Array DoItem) : MacroM (Array DoElem) := do - let pick ← `(doElem| let $b:ident : Bool ← Strata.Shallow.ND.havoc) - let branch ← ite (← `($b)) thenItems elseItems - pure #[pick, branch] - -/-- A `while` loop with invariant on the state tuple of the variables `vars` that the body -assigns. `inv` and `guard` receive the state term, so the caller can substitute projections -for the variables; `body` receives it as well and returns the body items, which may read and -assign the `vars`. Generic in the monad so the translator can run its own context inside the -callbacks. - -The tuple `(x₁, …, xₖ)` is built once and used in four places: as the pattern that unpacks the -state into mutable copies at the start of the body (`let mut (x₁, …, xₖ) := s`), as the new -state the body returns (`pure (x₁, …, xₖ)`), as the initial state passed to the loop, and as -the pattern that copies the final state back (`(x₁, …, xₖ) ← whileInv …`). Inside the body -the names refer to the body's own copies; outside, to the enclosing variables. With one -variable the pattern is the variable itself; with none the state is `()` and the loop is a -plain statement. Returns the single item for the loop. -/ -def whileInv {m : Type → Type} [Monad m] [MonadLiftT MacroM m] - (s : Ident) (vars : Array Ident) (tys : Array Term) - (inv guard : Term → m Term) (body : Term → m (Array DoItem)) : - m (Array DoItem) := do - let stTy ← (tupleType tys : MacroM Term) - let sTerm : Term ← (`($s) : MacroM Term) - let invBody ← inv sTerm - let guardBody ← guard sTerm - let invFn ← (`(fun ($s : $stTy) => $invBody) : MacroM Term) - let guardFn ← (`(fun ($s : $stTy) => $guardBody) : MacroM Term) - let stateTup ← (tuple (vars.map fun v => (v : Term)) : MacroM Term) - let unpack ← (do - match vars.size with - | 0 => pure #[] - | 1 => pure #[← item (← letMut vars[0]! tys[0]! sTerm)] - | _ => pure #[← item (← `(doElem| let mut $stateTup:term := $sTerm))] - : MacroM (Array DoItem)) - let bodyItems := unpack ++ (← body sTerm) - let ret ← (do item (← `(doElem| pure $stateTup)) : MacroM DoItem) - let bodyBlock ← (doBlock (bodyItems.push ret) : MacroM Term) - let bodyFn ← (`(fun ($s : $stTy) => $bodyBlock) : MacroM Term) - let call ← (`(Strata.Shallow.ND.whileInv $invFn $guardFn $bodyFn $stateTup) : MacroM Term) - let loop ← (do - match vars.size with - | 0 => item (← `(doElem| $call:term)) - | 1 => item (← `(doElem| $(vars[0]!):ident ← $call:term)) - | _ => item (← `(doElem| $stateTup:term ← $call:term)) - : MacroM DoItem) - pure #[loop] - -/-! ## Declarations -/ - -/-- `def name (x₁ : T₁) … : Strata.Shallow.ND R := body`. -/ -def procDef (name : Ident) (params : Array (Ident × Term)) (retTy : Term) (body : Term) : - MacroM Command := do - let binders ← params.mapM fun (x, t) => `(bracketedBinder| ($x:ident : $t)) - `(command| def $name:ident $binders* : Strata.Shallow.ND $retTy := $body) - -/-- `theorem name_spec (x₁ : T₁) … : ⦃⌜pre⌝⦄ name x₁ … ⦃⇓ r => ⌜post⌝⦄ := by …`, wrapped in -`open Std.Do in` for the scoped notation and with the experimental-tactic warning off. -/ -def specTheorem (thmName fnName : Ident) (params : Array (Ident × Term)) (pre : Term) - (r : Ident) (post : Term) : MacroM Command := do - let binders ← params.mapM fun (x, t) => `(bracketedBinder| ($x:ident : $t)) - let args : Array Term := params.map fun (x, _) => (x : Term) - let warnOpt := mkIdent `mvcgen.warning - let stdDo := mkIdent `Std.Do - `(command| - set_option $warnOpt:ident false in - open $stdDo:ident in - theorem $thmName:ident $binders* : - ⦃⌜$pre⌝⦄ $fnName:ident $args* ⦃⇓ $r:ident => ⌜$post⌝⦄ := by - (mvcgen [$fnName:ident]; all_goals (try grind))) - -end Strata.Shallow.Emit diff --git a/StrataBoole/Shallow/Interpreter/Interp.lean b/StrataBoole/Shallow/Interpreter/Interp.lean deleted file mode 100644 index 7ae4ae9..0000000 --- a/StrataBoole/Shallow/Interpreter/Interp.lean +++ /dev/null @@ -1,355 +0,0 @@ -/- - Copyright Strata Contributors - - SPDX-License-Identifier: Apache-2.0 OR MIT --/ -module - -public import StrataBoole.Verify -public import Strata.DL.Lambda.Denote.LExprDenote -import all Strata.DL.Lambda.Denote.LExprDenote -public import Strata.DL.Lambda.Denote.LExprAnnotated -import all Strata.DL.Lambda.Denote.LExprAnnotated -public import StrataBoole.Shallow.Layer -public import StrataBoole.Shallow.Interpreter.Sort - -/-! # The interpreter: Core statements as `ND` computations - -One Lean function gives every Core program its meaning in the `ND` layer. It is the object -the adequacy theorem is about (Core's operational semantics on one side, `interpStmts` on -the other) and the object that is unfolded on a concrete program to obtain its verification -conditions. - -* **Store.** `FreeVarVal Core.CoreLParams tcInterp`: a Lean value for every variable at every - sort. This is exactly the free-variable valuation that `LExpr.denote` reads, so expressions - are evaluated by `denote` directly; there is no second evaluator. -* **Expressions.** `evalExpr σ e τ` runs Strata's computable type checker `LExpr.typeCheck` - and, on success, `LExpr.denote` with the derivation obtained from `typeCheck_to_HasTypeA`. -* **Failure, never vacuity.** An ill-typed expression (a loop guard is checked before the loop, - since inside `whileInv` it is a proposition), and every construct the interpreter does not - handle, is `ND.fail`: the outcome `none` of a failed `assert`. A computation with no outcome - at all would satisfy every specification; this one satisfies none. -* **Loops are frame-aware.** The loop state carries only the variables the body assigns - (`Block.modifiedVars` minus `Block.initVars`); all other variables are read from the store - at loop entry (`Store.merge`). Without this the loop invariant would have to restate that - every unmodified variable is unchanged. -* **Blocks** restore the entry values of the names they declare on exit, as Core's - `projectStore` does. -* **Outputs** are arbitrary at procedure entry (`havoc`); an inout parameter keeps its input - value. -* **Unsupported for now** (`ND.fail`): procedure calls, `exit`, nondeterministic loops, local - `type` declarations. - -The model `(tcInterp, opInterp, vt)` is a parameter bundled in `Sem`; `Model.lean` provides -the concrete one for Core's built-ins. --/ - -@[expose] public section - -namespace Strata.Shallow.Interp - -open Lambda Imperative Strata.Shallow - -/-- The semantic parameters: a type-constructor interpretation, an operator interpretation, -and a type-variable valuation. -/ -structure Sem where - tcInterp : TyConstrInterp - opInterp : OpInterp tcInterp - [inhab : TyConstrInterp.AllInhabited tcInterp] - vt : TyVarVal - -attribute [instance] Sem.inhab - -abbrev Ident := Core.CoreIdent - -/-! ### Re-exported unfolding lemmas for `denote` - -Strata states these without `public`; they are visible here only through `import all`, and a -module may use them in *proofs* of public theorems but not in public statements or exposed -bodies. A proof written in a user's file (or generated into it) can refer to public names only, -so each lemma is restated under a primed name. `denote_op'` and `denote_fvar'` are stated at the -annotated type (`τ := ty`), which is the form `typeCheck` produces, so no cast appears. -(`denote_boolConst`, `denote_eq_true`, `denote_quant_all_true` are already public.) -/ - -section ReExports - -variable {T : LExprParams} {tcInterp : TyConstrInterp} {opInterp : OpInterp tcInterp} - {fvarVal : FreeVarVal T tcInterp} {vt : TyVarVal} {Δ : List LMonoTy} - (bvarVal : BVarVal tcInterp vt Δ) - -theorem denote_intConst' {m : T.mono.base.Metadata} {i : Int} - (h : LExpr.HasTypeA Δ (.const m (.intConst i)) (.tcons "int" [])) : - LExpr.denote tcInterp opInterp fvarVal vt bvarVal (.const m (.intConst i)) (.tcons "int" []) h - = i := - Lambda.denote_intConst tcInterp opInterp fvarVal vt bvarVal h - -theorem denote_op' {m : T.mono.base.Metadata} {o : T.Identifier} {ty : LMonoTy} - (h : LExpr.HasTypeA Δ (.op m o (some ty)) ty) : - LExpr.denote tcInterp opInterp fvarVal vt bvarVal (.op m o (some ty)) ty h - = opInterp o.name (ty.substTyVars vt) := - Lambda.denote_op tcInterp opInterp fvarVal vt bvarVal h - -theorem denote_fvar' {m : T.mono.base.Metadata} {name : T.Identifier} {ty : LMonoTy} - (h : LExpr.HasTypeA Δ (.fvar m name (some ty)) ty) : - LExpr.denote tcInterp opInterp fvarVal vt bvarVal (.fvar m name (some ty)) ty h - = fvarVal name (ty.substTyVars vt) := - Lambda.denote_fvar tcInterp opInterp fvarVal vt bvarVal h - -theorem denote_bvar' {m : T.mono.base.Metadata} {i : Nat} {τ : LMonoTy} - (h : LExpr.HasTypeA Δ (.bvar m i) τ) : - LExpr.denote tcInterp opInterp fvarVal vt bvarVal (.bvar m i) τ h - = bvarVal.get i (HasTypeA.bvar_inv h) := - Lambda.denote_bvar tcInterp opInterp fvarVal vt bvarVal h - -theorem denote_app' {m : T.Metadata} {fn arg : LExpr T.mono} {aty τ : LMonoTy} - (h_fn : LExpr.HasTypeA Δ fn (.arrow aty τ)) (h_arg : LExpr.HasTypeA Δ arg aty) - (h_app : LExpr.HasTypeA Δ (.app m fn arg) τ) : - LExpr.denote tcInterp opInterp fvarVal vt bvarVal (.app m fn arg) τ h_app = - (LExpr.denote tcInterp opInterp fvarVal vt bvarVal fn (.arrow aty τ) h_fn) - (LExpr.denote tcInterp opInterp fvarVal vt bvarVal arg aty h_arg) := - Lambda.denote_app bvarVal h_fn h_arg h_app - -theorem denote_abs' {m : T.Metadata} {name : String} {body : LExpr T.mono} {aty rty : LMonoTy} - (h_body : LExpr.HasTypeA (aty :: Δ) body rty) - (h_abs : LExpr.HasTypeA Δ (.abs m name (some aty) body) (.arrow aty rty)) : - LExpr.denote tcInterp opInterp fvarVal vt bvarVal - (.abs m name (some aty) body) (.arrow aty rty) h_abs = - fun x => LExpr.denote tcInterp opInterp fvarVal vt (.cons x bvarVal) body rty h_body := - Lambda.denote_abs bvarVal h_body h_abs - -theorem denote_eq_false' {m : T.Metadata} {e1 e2 : LExpr T.mono} {ty' : LMonoTy} - (h_1 : LExpr.HasTypeA Δ e1 ty') (h_2 : LExpr.HasTypeA Δ e2 ty') - (h_eq : LExpr.HasTypeA Δ (.eq m e1 e2) .bool) - (hne : LExpr.denote tcInterp opInterp fvarVal vt bvarVal e1 ty' h_1 ≠ - LExpr.denote tcInterp opInterp fvarVal vt bvarVal e2 ty' h_2) : - LExpr.denote tcInterp opInterp fvarVal vt bvarVal (.eq m e1 e2) .bool h_eq = false := - Lambda.denote_eq_false bvarVal h_1 h_2 h_eq hne - -theorem denote_ite' {m : T.Metadata} {c t e : LExpr T.mono} {τ : LMonoTy} - (h_c : LExpr.HasTypeA Δ c .bool) (h_t : LExpr.HasTypeA Δ t τ) (h_e : LExpr.HasTypeA Δ e τ) - (h_ite : LExpr.HasTypeA Δ (.ite m c t e) τ) : - LExpr.denote tcInterp opInterp fvarVal vt bvarVal (.ite m c t e) τ h_ite = - bif LExpr.denote tcInterp opInterp fvarVal vt bvarVal c .bool h_c - then LExpr.denote tcInterp opInterp fvarVal vt bvarVal t τ h_t - else LExpr.denote tcInterp opInterp fvarVal vt bvarVal e τ h_e := - Lambda.denote_ite bvarVal h_c h_t h_e h_ite - -theorem denote_quant_all_false' {m : T.Metadata} {name : String} {tr body : LExpr T.mono} - {qty : LMonoTy} - (h_body : LExpr.HasTypeA (qty :: Δ) body .bool) - (h_quant : LExpr.HasTypeA Δ (.quant m .all name (some qty) tr body) .bool) - (w : TyDenote tcInterp vt qty) - (hw : (LExpr.denote tcInterp opInterp fvarVal vt (.cons w bvarVal) body .bool h_body : Bool) - = false) : - LExpr.denote tcInterp opInterp fvarVal vt bvarVal - (.quant m .all name (some qty) tr body) .bool h_quant = false := - Lambda.denote_quant_all_false bvarVal h_body h_quant w hw - -theorem denote_quant_exist_true' {m : T.Metadata} {name : String} {tr body : LExpr T.mono} - {qty : LMonoTy} - (h_body : LExpr.HasTypeA (qty :: Δ) body .bool) - (h_quant : LExpr.HasTypeA Δ (.quant m .exist name (some qty) tr body) .bool) - (w : TyDenote tcInterp vt qty) - (hw : (LExpr.denote tcInterp opInterp fvarVal vt (.cons w bvarVal) body .bool h_body : Bool) - = true) : - LExpr.denote tcInterp opInterp fvarVal vt bvarVal - (.quant m .exist name (some qty) tr body) .bool h_quant = true := - Lambda.denote_quant_exist_true bvarVal h_body h_quant w hw - -theorem denote_quant_exist_false' {m : T.Metadata} {name : String} {tr body : LExpr T.mono} - {qty : LMonoTy} - (h_body : LExpr.HasTypeA (qty :: Δ) body .bool) - (h_quant : LExpr.HasTypeA Δ (.quant m .exist name (some qty) tr body) .bool) - (hall : ∀ x : TyDenote tcInterp vt qty, - (LExpr.denote tcInterp opInterp fvarVal vt (.cons x bvarVal) body .bool h_body : Bool) - = false) : - LExpr.denote tcInterp opInterp fvarVal vt bvarVal - (.quant m .exist name (some qty) tr body) .bool h_quant = false := - Lambda.denote_quant_exist_false bvarVal h_body h_quant hall - -end ReExports - -/-- The store: a value for every variable at every sort (Strata's `FreeVarVal`). -/ -abbrev Store (M : Sem) := FreeVarVal Core.CoreLParams M.tcInterp - -/-- The sort of a Core type under the type-variable valuation. -/ -abbrev sortOf (M : Sem) (τ : LMonoTy) : LSort := LMonoTy.substTyVars M.vt τ - -namespace Store - -variable {M : Sem} - -/-- Write `v` for `x` at sort `s`; every other (name, sort) pair is unchanged. -/ -def upd (σ : Store M) (x : Ident) (s : LSort) (v : SortDenote M.tcInterp s) : Store M := - fun y s' => - if y = x then - if h : s' = s then cast (congrArg (SortDenote M.tcInterp) h.symm) v else σ y s' - else σ y s' - -/-- Names in `vs` from `t`, everything else from `σ`. -/ -def merge (σ : Store M) (vs : List Ident) (t : Store M) : Store M := - fun y s => if y ∈ vs then t y s else σ y s - -/-- The store with every variable at its default value. -/ -noncomputable def default : Store M := fun _ s => (Inhabited.default : SortDenote M.tcInterp s) - -@[simp] theorem upd_same (σ : Store M) (x : Ident) (s : LSort) (v : SortDenote M.tcInterp s) : - upd σ x s v x s = v := by - simp [upd] - -@[simp] theorem upd_other (σ : Store M) (x y : Ident) (s s' : LSort) (v : SortDenote M.tcInterp s) - (h : y ≠ x) : upd σ x s v y s' = σ y s' := by - simp [upd, h] - -@[simp] theorem merge_mem (σ t : Store M) (vs : List Ident) (y : Ident) (s : LSort) (h : y ∈ vs) : - merge σ vs t y s = t y s := by - simp [merge, h] - -@[simp] theorem merge_not_mem (σ t : Store M) (vs : List Ident) (y : Ident) (s : LSort) - (h : y ∉ vs) : merge σ vs t y s = σ y s := by - simp [merge, h] - -end Store - -/-- The failing computation: its only outcome is `none`, as after a failed `assert`. Used for -ill-typed expressions and for every statement the interpreter does not handle, so that no -specification holds of them vacuously. -/ -def ND.fail {α : Type} : ND α := ⟨fun r => r = none⟩ - -/-! ## Expressions -/ - -/-- The value of the closed, annotated expression `e` at type `τ`, if it type-checks at `τ`. -/ -noncomputable def evalExpr (M : Sem) (σ : Store M) (e : Core.Expression.Expr) (τ : LMonoTy) : - Option (TyDenote M.tcInterp M.vt τ) := - if h : LExpr.typeCheck (T := Core.CoreLParams) [] e = some τ then - some (LExpr.denote (T := Core.CoreLParams) M.tcInterp M.opInterp σ M.vt .nil e τ - (LExpr.typeCheck_to_HasTypeA h)) - else none - -/-- A Boolean condition: `some b` if `e` type-checks at `bool`. -/ -noncomputable def evalBool (M : Sem) (σ : Store M) (e : Core.Expression.Expr) : Option Bool := - evalExpr M σ e LMonoTy.bool - -/-- All invariants of a loop hold in `σ`. -/ -def invsHold (M : Sem) (σ : Store M) : List (String × Core.Expression.Expr) → Prop - | [] => True - | (_, e) :: rest => evalBool M σ e = some true ∧ invsHold M σ rest - -/-! ## Statements -/ - -/-- What the interpreter carries along a statement list: the declared types of the variables -in scope, needed only to pick the sort of a `havoc`. -/ -structure Ctx where - tys : List (Ident × LMonoTy) - -/-- The loop-carried variables of a body: assigned in it, not declared in it. -/ -def loopVars (body : List Core.Statement) : List Ident := - let decl := Imperative.Block.initVars body - (Imperative.Block.modifiedVars body).filter (· ∉ decl) - -/-- `x := e` or `x := *` for a variable of type `τ`. -/ -noncomputable def assignVar (M : Sem) (σ : Store M) (x : Ident) (τ : LMonoTy) : - ExprOrNondet Core.Expression → ND (Store M) - | .det e => - match evalExpr M σ e τ with - | some v => pure (σ.upd x (sortOf M τ) v) - | none => ND.fail - | .nondet => do - let v ← ND.havoc (α := SortDenote M.tcInterp (sortOf M τ)) - pure (σ.upd x (sortOf M τ) v) - -/-- One base command. `init` is handled by `interpStmts`, which also extends the context. -/ -noncomputable def interpCmd (M : Sem) (Γ : Ctx) (σ : Store M) : Cmd Core.Expression → ND (Store M) - | .init .. => ND.fail - | .set x (.det e) _ => - match LExpr.typeCheck (T := Core.CoreLParams) [] e with - | some τ => assignVar M σ x τ (.det e) - | none => ND.fail - | .set x .nondet _ => - match Γ.tys.lookup x with - | some τ => assignVar M σ x τ .nondet - | none => ND.fail - | .assert _ e _ => - match evalBool M σ e with - | some b => do ND.assert (b = true); pure σ - | none => ND.fail - | .assume _ e _ => - match evalBool M σ e with - | some b => do ND.assume (b = true); pure σ - | none => ND.fail - | .cover _ _ _ => pure σ - -mutual - -/-- A statement list. `init` extends the context for the rest of the list. -/ -noncomputable def interpStmts (M : Sem) (Γ : Ctx) : List Core.Statement → Store M → ND (Store M) - | [], σ => pure σ - | .cmd (.cmd (.init x ty rhs _)) :: rest, σ => - match ty.toMonoType? with - | some τ => do - let σ' ← assignVar M σ x τ rhs - interpStmts M { tys := (x, τ) :: Γ.tys } rest σ' - | none => ND.fail - | s :: rest, σ => do - let σ' ← interpStmt M Γ s σ - interpStmts M Γ rest σ' - -/-- One statement. -/ -noncomputable def interpStmt (M : Sem) (Γ : Ctx) : Core.Statement → Store M → ND (Store M) - | .cmd (.cmd c), σ => interpCmd M Γ σ c - | .cmd (.call ..), _ => ND.fail - | .block _ ss _, σ => interpBlock M Γ ss σ - | .ite (.det c) t e _, σ => - match evalBool M σ c with - | some true => interpBlock M Γ t σ - | some false => interpBlock M Γ e σ - | none => ND.fail - | .ite .nondet t e _, σ => do - let b ← ND.havoc (α := Bool) - if b then interpBlock M Γ t σ else interpBlock M Γ e σ - | .loop (.det g) _ invs body _, σ => - if LExpr.typeCheck (T := Core.CoreLParams) [] g = some LMonoTy.bool then do - let vs := loopVars body - let t ← ND.whileInv - (fun t => invsHold M (σ.merge vs t) invs) - (fun t => evalBool M (σ.merge vs t) g = some true) - (fun t => interpBlock M Γ body (σ.merge vs t)) - σ - pure (σ.merge vs t) - else ND.fail - | .loop .nondet .., _ => ND.fail - | .exit .., _ => ND.fail - | .typeDecl .., _ => ND.fail - -/-- A block: run the statements, then restore the entry values of the names declared inside. -/ -noncomputable def interpBlock (M : Sem) (Γ : Ctx) (ss : List Core.Statement) (σ : Store M) : - ND (Store M) := do - let σ' ← interpStmts M Γ ss σ - pure (σ'.merge (Imperative.Block.initVars ss) σ) - -end - -/-! ## Procedures -/ - -/-- Give each listed variable an arbitrary value of its type. -/ -noncomputable def havocVars (M : Sem) : List (Ident × LMonoTy) → Store M → ND (Store M) - | [], σ => pure σ - | (x, τ) :: rest, σ => do - let v ← ND.havoc (α := SortDenote M.tcInterp (sortOf M τ)) - havocVars M rest (σ.upd x (sortOf M τ) v) - -/-- A procedure from a store holding its inputs: outputs that are not also inputs start -arbitrary, then the body runs. The result is the final store; outputs are read from it. -/ -noncomputable def interpProc (M : Sem) (p : Core.Procedure) (σ₀ : Store M) : ND (Store M) := - let inputs := p.header.inputs.toList - let outputs := p.header.outputs.toList - let outOnly := outputs.filter fun (o, _) => inputs.all fun (i, _) => i ≠ o - do - let σ ← havocVars M outOnly σ₀ - match p.body with - | .structured ss => interpStmts M ⟨inputs ++ outputs⟩ ss σ - | .cfg _ => ND.fail - -end Strata.Shallow.Interp - -end diff --git a/StrataBoole/Shallow/Interpreter/Model.lean b/StrataBoole/Shallow/Interpreter/Model.lean deleted file mode 100644 index ebb9dc2..0000000 --- a/StrataBoole/Shallow/Interpreter/Model.lean +++ /dev/null @@ -1,209 +0,0 @@ -/- - Copyright Strata Contributors - - SPDX-License-Identifier: Apache-2.0 OR MIT --/ -module - -public import Strata.DL.Lambda.Denote.LExprDenote -public import StrataBoole.Shallow.Interpreter.Sort -import all Strata.DL.Lambda.Denote.LExprDenote - -/-! # A concrete model of Core's built-in types and operators - -`LExpr.denote` (`Strata/DL/Lambda/Denote/LExprDenote.lean`) gives Core expressions a -meaning in Lean, but it is parametric in two things Strata does not fix: - -* `tcInterp : TyConstrInterp` — a Lean type for every type constructor that `SortDenote` - does not already map (`SortDenote` fixes `bool`, `int`, `real`, `string`, `bitvec`, `arrow`); -* `opInterp : OpInterp tcInterp` — a Lean value for every operator, by name and sort. - -The model is partial: it covers the four non-built-in type constructors Core uses and the -operators of the `int`/`bool`/`Map`/`Sequence` fragment. Every other operator is interpreted -by `default`; an operator without a `body` or `concreteEval` imposes no consistency -obligation, so these can be refined later without touching any proof. The consistency proofs -relating the model to Strata's `concreteEval` functions (`InterpConsistentEval`) are not part -of this file. - -Conventions: `Int.Div`/`Int.Mod` are Lean's `/`/`%` (`Int.ediv`/`Int.emod`, the SMT-LIB -convention, as Lean's own docstring says), `DivT`/`ModT` are `Int.tdiv`/`Int.tmod`, the -`Safe*` operators denote the same functions as their unchecked versions (their preconditions -are obligations, not part of the value). Comparisons return `Bool`. --/ - -@[expose] public section - -namespace Strata.Shallow.Model - -open Lambda - -/-! ## Sorts -/ - -/-- A Lean type for every sort. Agrees with `SortDenote` on the built-ins and adds `Map`, -`Sequence`, `Set` and `regex`; unknown constructors get `Unit`. -/ -def coreSortDenote : LSort → Type - | .tcons "bool" [] => Bool - | .tcons "int" [] => Int - | .tcons "real" [] => Rat - | .tcons "string" [] => String - | .bitvec n => BitVec n - | .tcons "arrow" [a, b] => coreSortDenote a → coreSortDenote b - | .tcons "Map" [k, v] => coreSortDenote k → coreSortDenote v - | .tcons "Sequence" [t] => List (coreSortDenote t) - | .tcons "Set" [t] => coreSortDenote t → Prop - | .tcons "regex" [] => String → Prop - | .tcons _ _ => Unit - - -/-- Every sort is inhabited. The catch-all branch of `coreSortDenote` does not reduce on a -variable sort, so this goes through `split`, as Strata's `SortDenote.inhabited` does. -/ -@[reducible] def coreSortDenote.inhabited : (s : LSort) → Inhabited (coreSortDenote s) := - sortRec (P := fun s => Inhabited (coreSortDenote s)) - (fun name args ih => by - unfold coreSortDenote - split - all_goals first - | exact ⟨false⟩ - | exact ⟨(0 : Int)⟩ - | exact ⟨(0 : Rat)⟩ - | exact ⟨""⟩ - | exact ⟨(0 : BitVec _)⟩ - | exact ⟨[]⟩ - | exact ⟨fun _ => False⟩ - | exact ⟨()⟩ - | exact ⟨fun _ => (ih _ (by simp_all)).default⟩) - (fun n => ⟨(0 : BitVec n)⟩) - -/-- The type-constructor interpretation handed to `SortDenote`: whatever `SortDenote` does -not fix is looked up in `coreSortDenote`. -/ -def coreTcInterp : TyConstrInterp := fun name args => coreSortDenote (.tcons name args) - -instance : TyConstrInterp.AllInhabited coreTcInterp := - ⟨fun name args => coreSortDenote.inhabited (.tcons name args)⟩ - -/-- `SortDenote coreTcInterp` and `coreSortDenote` are the same type family (by induction on -the sort; the built-in cases are identical, the others go through `coreTcInterp`). Used to -cast the arguments of polymorphic operators. -/ -theorem sortDenote_eq : ∀ s, SortDenote coreTcInterp s = coreSortDenote s := - sortRec (P := fun s => SortDenote coreTcInterp s = coreSortDenote s) - (fun name args ih => by - unfold SortDenote - split - all_goals first - | rfl - | (rename_i heq - cases heq <;> first - | rfl - | exact congr (congrArg (fun (A B : Type) => A → B) (ih _ (by simp))) (ih _ (by simp)))) - (fun n => rfl) - -/-! ## Sort patterns -/ - -@[match_pattern] def sInt : LSort := .tcons "int" [] -@[match_pattern] def sBool : LSort := .tcons "bool" [] -@[match_pattern] def sArrow (a b : LSort) : LSort := .tcons "arrow" [a, b] -@[match_pattern] def sMap (k v : LSort) : LSort := .tcons "Map" [k, v] -@[match_pattern] def sSeq (t : LSort) : LSort := .tcons "Sequence" [t] - -/-! ## Operators -/ - -/-- Transport a value between the two spellings of a sort's type. -/ -def toSD {s : LSort} (v : coreSortDenote s) : SortDenote coreTcInterp s := - cast (sortDenote_eq s).symm v -def ofSD {s : LSort} (v : SortDenote coreTcInterp s) : coreSortDenote s := - cast (sortDenote_eq s) v - -theorem coreSortDenote_map (k v : LSort) : - coreSortDenote (sMap k v) = (coreSortDenote k → coreSortDenote v) := rfl -theorem coreSortDenote_seq (t : LSort) : - coreSortDenote (sSeq t) = List (coreSortDenote t) := rfl - -/-- A map value as a Lean function, and back. -/ -def mapOf {k v : LSort} (m : SortDenote coreTcInterp (sMap k v)) : coreSortDenote k → coreSortDenote v := - cast (coreSortDenote_map k v) (ofSD m) -def mapTo {k v : LSort} (f : coreSortDenote k → coreSortDenote v) : SortDenote coreTcInterp (sMap k v) := - toSD (cast (coreSortDenote_map k v).symm f) -/-- A sequence value as a Lean list, and back. -/ -def seqOf {t : LSort} (l : SortDenote coreTcInterp (sSeq t)) : List (coreSortDenote t) := - cast (coreSortDenote_seq t) (ofSD l) -def seqTo {t : LSort} (l : List (coreSortDenote t)) : SortDenote coreTcInterp (sSeq t) := - toSD (cast (coreSortDenote_seq t).symm l) - -open Classical in -/-- The operator interpretation: by name (`CoreOp.toString`) and instantiated sort. Monomorphic -`int`/`bool` operators match a literal sort; the polymorphic `Map` and `Sequence` operators -match the sort's shape and transport through `toSD`/`ofSD`. Everything else is `default`. -/ -noncomputable def coreOpInterp : OpInterp coreTcInterp := fun name s => - match name, s with - -- integers - | "Int.Add", sArrow sInt (sArrow sInt sInt) => fun (a b : Int) => a + b - | "Int.Sub", sArrow sInt (sArrow sInt sInt) => fun (a b : Int) => a - b - | "Int.Mul", sArrow sInt (sArrow sInt sInt) => fun (a b : Int) => a * b - | "Int.Div", sArrow sInt (sArrow sInt sInt) => fun (a b : Int) => a / b - | "Int.Mod", sArrow sInt (sArrow sInt sInt) => fun (a b : Int) => a % b - | "Int.DivT", sArrow sInt (sArrow sInt sInt) => fun (a b : Int) => Int.tdiv a b - | "Int.ModT", sArrow sInt (sArrow sInt sInt) => fun (a b : Int) => Int.tmod a b - | "Int.SafeDiv", sArrow sInt (sArrow sInt sInt) => fun (a b : Int) => a / b - | "Int.SafeMod", sArrow sInt (sArrow sInt sInt) => fun (a b : Int) => a % b - | "Int.SafeDivT", sArrow sInt (sArrow sInt sInt) => fun (a b : Int) => Int.tdiv a b - | "Int.SafeModT", sArrow sInt (sArrow sInt sInt) => fun (a b : Int) => Int.tmod a b - | "Int.Neg", sArrow sInt sInt => fun (a : Int) => -a - | "Int.Lt", sArrow sInt (sArrow sInt sBool) => fun (a b : Int) => decide (a < b) - | "Int.Le", sArrow sInt (sArrow sInt sBool) => fun (a b : Int) => decide (a ≤ b) - | "Int.Gt", sArrow sInt (sArrow sInt sBool) => fun (a b : Int) => decide (a > b) - | "Int.Ge", sArrow sInt (sArrow sInt sBool) => fun (a b : Int) => decide (a ≥ b) - -- booleans - | "Bool.And", sArrow sBool (sArrow sBool sBool) => fun (a b : Bool) => a && b - | "Bool.Or", sArrow sBool (sArrow sBool sBool) => fun (a b : Bool) => a || b - | "Bool.Implies", sArrow sBool (sArrow sBool sBool) => fun (a b : Bool) => !a || b - | "Bool.Equiv", sArrow sBool (sArrow sBool sBool) => fun (a b : Bool) => a == b - | "Bool.Not", sArrow sBool sBool => fun (a : Bool) => !a - -- maps: `select m k`, `update m k v`, `mapConst v` - | "select", sArrow (sMap k v) (sArrow k' v') => - if h : k = k' ∧ v = v' then - h.1 ▸ h.2 ▸ (fun (m : SortDenote coreTcInterp (sMap k v)) (x : SortDenote coreTcInterp k) => - toSD (mapOf m (ofSD x))) - else default - | "update", sArrow (sMap k v) (sArrow k' (sArrow v' (sMap k'' v''))) => - if h : k = k' ∧ v = v' ∧ k = k'' ∧ v = v'' then - h.1 ▸ h.2.1 ▸ h.2.2.1 ▸ h.2.2.2 ▸ - (fun (m : SortDenote coreTcInterp (sMap k v)) (x : SortDenote coreTcInterp k) - (y : SortDenote coreTcInterp v) => - mapTo (fun z => if toSD z = x then ofSD y else mapOf m z)) - else default - | "mapConst", sArrow v (sMap k v') => - if h : v = v' then - h ▸ (fun (y : SortDenote coreTcInterp v) => mapTo (fun (_ : coreSortDenote k) => ofSD y)) - else default - -- sequences (as lists): the unchecked operations - | "Sequence.length", sArrow (sSeq t) sInt => - fun (l : SortDenote coreTcInterp (sSeq t)) => ((seqOf l).length : Int) - | "Sequence.empty", sSeq t => seqTo ([] : List (coreSortDenote t)) - | "Sequence.append", sArrow (sSeq t) (sArrow (sSeq t') (sSeq t'')) => - if h : t = t' ∧ t = t'' then - h.1 ▸ h.2 ▸ (fun (a b : SortDenote coreTcInterp (sSeq t)) => seqTo (seqOf a ++ seqOf b)) - else default - | "Sequence.select!", sArrow (sSeq t) (sArrow sInt t') => - if h : t = t' then - h ▸ (fun (l : SortDenote coreTcInterp (sSeq t)) (i : Int) => - toSD ((seqOf l).getD i.toNat (coreSortDenote.inhabited t).default)) - else default - | "Sequence.update!", sArrow (sSeq t) (sArrow sInt (sArrow t' (sSeq t''))) => - if h : t = t' ∧ t = t'' then - h.1 ▸ h.2 ▸ (fun (l : SortDenote coreTcInterp (sSeq t)) (i : Int) (y : SortDenote coreTcInterp t) => - seqTo ((seqOf l).set i.toNat (ofSD y))) - else default - | _, _ => default - -/-! ## Sanity checks: the monomorphic cases compute by `rfl` -/ - -example : coreOpInterp "Int.Add" (sArrow sInt (sArrow sInt sInt)) = fun (a b : Int) => a + b := rfl -example : coreOpInterp "Int.Ge" (sArrow sInt (sArrow sInt sBool)) = fun (a b : Int) => decide (a ≥ b) := rfl -example : coreOpInterp "Bool.And" (sArrow sBool (sArrow sBool sBool)) = fun (a b : Bool) => a && b := rfl -example : coreOpInterp "Int.Neg" (sArrow sInt sInt) = fun (a : Int) => -a := rfl -example : SortDenote coreTcInterp (sMap sInt sInt) = (Int → Int) := rfl -example : SortDenote coreTcInterp (sSeq sInt) = List Int := rfl - -end Strata.Shallow.Model - -end diff --git a/StrataBoole/Shallow/Interpreter/Sort.lean b/StrataBoole/Shallow/Interpreter/Sort.lean deleted file mode 100644 index 1a18cfc..0000000 --- a/StrataBoole/Shallow/Interpreter/Sort.lean +++ /dev/null @@ -1,74 +0,0 @@ -/- - Copyright Strata Contributors - - SPDX-License-Identifier: Apache-2.0 OR MIT --/ -module -public import Strata.DL.Lambda.Denote.LExprDenote - -/-! # Sorts: recursion principle and decidable equality for `LSort` - -`LSort` is a nested inductive (`tcons` carries a `List LSort`), so the auto-generated recursor -is awkward to use. Strata already has what is needed, in -`Strata/DL/Lambda/Denote/LExprDenote.lean`, but not as public declarations of that module: - -* `LSort.rec'` (and its `Prop` version `LSort.ind`): recursion with the hypothesis available - for every member of the argument list; -* `instance : DecidableEq LSort`, built from the Boolean comparison `LSort_eqb` and the - private lemmas `LSort_eqb_eq` and `LSort_eqb_refl`. - -A non-public declaration can be used in the proof of a public theorem, but not in a public -statement or in the body of an exposed definition, which is where the model and the interpreter -need these. This file therefore provides public replacements: `sortRec` restates `LSort.rec'` -(with the motive implicit), and `LSort.decEq` decides equality directly by structural recursion -instead of going through `LSort_eqb`. Both are shared by `Model.lean` and `Interp.lean`; they -can be dropped once Strata exports its own. -/ - -@[expose] public section - -namespace Strata.Shallow - -open Lambda - -/-- Recursion over `LSort` with the hypothesis available for every member of the argument list: -Strata's `LSort.rec'` (`Strata/DL/Lambda/Denote/LExprDenote.lean`), which is not public. -/ -def sortRec {P : LSort → Sort u} - (htcons : ∀ name args, (∀ x, x ∈ args → P x) → P (.tcons name args)) - (hbitvec : ∀ n, P (.bitvec n)) : ∀ s, P s - | .tcons name args => htcons name args (fun x _ => sortRec htcons hbitvec x) - | .bitvec n => hbitvec n - -/-- Decidable equality on sorts, by structural recursion. Strata's own instance -(`instance : DecidableEq LSort` in `Strata/DL/Lambda/Denote/LExprDenote.lean`, via `LSort_eqb`) -is not public. -/ -def LSort.decEq : (a b : LSort) → Decidable (a = b) - | .tcons n as, .tcons n' as' => - if hn : n = n' then - match decEqList as as' with - | isTrue h => isTrue (by rw [hn, h]) - | isFalse h => isFalse (by intro e; cases e; exact h rfl) - else isFalse (by intro e; cases e; exact hn rfl) - | .tcons .., .bitvec .. => isFalse nofun - | .bitvec .., .tcons .. => isFalse nofun - | .bitvec n, .bitvec n' => - if h : n = n' then isTrue (by rw [h]) else isFalse (by intro e; cases e; exact h rfl) -where - decEqList : (as bs : List LSort) → Decidable (as = bs) - | [], [] => isTrue rfl - | [], _ :: _ => isFalse nofun - | _ :: _, [] => isFalse nofun - | a :: as, b :: bs => - match LSort.decEq a b, decEqList as bs with - | isTrue h1, isTrue h2 => isTrue (by rw [h1, h2]) - | isFalse h1, _ => isFalse (by intro e; cases e; exact h1 rfl) - | _, isFalse h2 => isFalse (by intro e; cases e; exact h2 rfl) - -instance : DecidableEq LSort := LSort.decEq - -example : (LSort.tcons "int" [] = LSort.tcons "int" []) := by decide -example : (LSort.tcons "arrow" [.tcons "int" [], .bitvec 32] ≠ LSort.tcons "arrow" [.tcons "int" [], .bitvec 64]) := by - decide - -end Strata.Shallow - -end diff --git a/StrataBoole/Shallow/Translate.lean b/StrataBoole/Shallow/Translate.lean deleted file mode 100644 index 541d857..0000000 --- a/StrataBoole/Shallow/Translate.lean +++ /dev/null @@ -1,519 +0,0 @@ -/- - Copyright Strata Contributors - - SPDX-License-Identifier: Apache-2.0 OR MIT --/ -import StrataBoole.Verify -import StrataBoole.Shallow.Layer -import StrataBoole.Shallow.Emit - -/-! # Shallow embedding: Core to Lean - -`shallow_embed p` takes a `StrataDDM.Program` (a `#strata program Boole; … #end` block), -lowers and type-checks it with `Strata.Boole.typeCheck` (`getProgram → toCoreProgram → -Core.typeCheck`, i.e. before any Core transform phase), and for every procedure emits - -* `def p (inputs) : Strata.Shallow.ND (outputs) := do …` -* `theorem p_spec (inputs) : ⦃⌜requires⌝⦄ p inputs ⦃⇓ r => ⌜ensures⌝⦄ := by mvcgen [p]; …` - -in the shape fixed by `StrataBooleTest/shallow_find_max.lean`: parameters are arguments, -outputs are `let mut` variables (arbitrary at entry, copies of the input for `inout`), -locals are `let mut`, a loop is `whileInv` on the tuple of the variables its body assigns. - -Supported in this first cut: `init`, `set`, `havoc`, `assert`, `assume`, deterministic and -nondeterministic `if`, deterministic `while` with invariants (partial correctness; a measure -is ignored with a warning), the procedure's own `exit` (Boole `return`) outside loops, and -the `int`/`bool`/`bv`/`Map`/`Sequence` expression layer. Not yet: `call`, `cover`, labelled -`exit`, nondeterministic `while`, local `function`/`type`, `old`, clause names on goals. - -Operators that carry a precondition obligation in Core (`Safe*`, the checked sequence -operations) are rejected rather than translated without their obligation. The total -operations are mapped to Lean's total functions: `Int.Div`/`Int.Mod` to `/`/`%` (Euclidean on -both sides), `DivT`/`ModT` to `Int.tdiv`/`Int.tmod`, `select!` to `a[i]!`. Where Core leaves a -result unconstrained (division by zero, out-of-range `select!`) Lean returns a default value; -a proof must not rely on that value (open decision in `docs/ShallowEmbedding.md`). --/ - -open Lean Elab Command Term Meta -open Lambda Imperative -open Strata.Shallow.Emit - -namespace Strata.Shallow.Translate - -/-- Lower and type-check; render the error as a string so the result can be evaluated at -elaboration time without naming Strata's message type. -/ -def typeCheckStr (p : StrataDDM.Program) : Except String Core.Program := - match Strata.Boole.typeCheck p Core.VerifyOptions.quiet with - | .ok cp => .ok cp - | .error m => .error (toString (m.format none)) - -/-! ## Translation monad -/ - -/-- What the translator knows while walking a procedure body. -/ -structure Ctx where - /-- Lean term standing for each Core variable in scope: its identifier, or, inside a loop's - invariant and guard, a projection of the loop state. -/ - vars : Std.HashMap String Term := {} - /-- Types of the variables in scope (Bool-typed variables become `x = true` in `Prop`). -/ - tys : Std.HashMap String LMonoTy := {} - /-- Enclosing expression binders for de Bruijn indices, innermost first. -/ - bvars : List (Ident × Option LMonoTy) := [] - /-- The procedure's own block label; `exit` to it is `return`. -/ - procLabel : String := "" - /-- The output variables, returned by `exit procLabel` and at the end of the body. -/ - outputs : Array Ident := #[] - /-- Inside a loop body, `return` would leave the body function, not the procedure. -/ - inLoop : Bool := false - -structure St where - fresh : Nat := 0 - warnings : Array String := #[] - -abbrev TransM := ReaderT Ctx (StateT St MacroM) - -def warn (msg : String) : TransM Unit := - modify fun s => { s with warnings := s.warnings.push msg } - -def fresh (base : String) : TransM Ident := do - let n ← modifyGet fun s => (s.fresh, { s with fresh := s.fresh + 1 }) - pure (mkIdent (Name.mkSimple s!"__{base}{n}")) - -def ident (x : String) : Ident := mkIdent (Name.mkSimple x) - -def fail {α} (msg : String) : TransM α := Macro.throwError s!"shallow_embed: {msg}" - -/-! ## Types -/ - -partial def transTy (t : LMonoTy) : TransM Term := do - match t with - | .tcons "int" [] => `(Int) - | .tcons "bool" [] => `(Bool) - | .tcons "nat" [] => `(Nat) - | .tcons "real" [] => `(Rat) - | .tcons "string" [] => `(String) - | .bitvec n => `(BitVec $(quote n)) - | .tcons "Map" [k, v] => do `($(← transTy k) → $(← transTy v)) - | .tcons "Sequence" [a] => do `(Array $(← transTy a)) - | .tcons "arrow" [a, b] => do `($(← transTy a) → $(← transTy b)) - | .tcons n [] => pure (ident n) - | .tcons n args => do - let args ← args.mapM transTy - `($(ident n) $(args.toArray)*) - | .ftvar n => pure (ident n) - -def isBoolTy : Option LMonoTy → Bool - | some (.tcons "bool" []) => true - | _ => false - -/-- Result type of an operator of type `ty` applied to `n` arguments. -/ -def resultTy : Option LMonoTy → Nat → Option LMonoTy - | some (.tcons "arrow" [_, b]), n + 1 => resultTy (some b) n - | t, 0 => t - | _, _ => none - -/-! ## Expressions -/ - -/-- `prop`: the result is a `Prop` (assertion positions). `val`: the result is a value, a -`Bool` for Boolean expressions. -/ -inductive Mode | prop | val - -def asProp (t : Term) : TransM Term := `($t = true) -def asBool (p : Term) : TransM Term := `(decide $p) - -/-- Head and arguments of an application spine. -/ -def spine : Core.Expression.Expr → Core.Expression.Expr × List Core.Expression.Expr - | .app _ f a => let (h, as) := spine f; (h, as ++ [a]) - | e => (e, []) - -def conj (ps : List Term) : TransM Term := do - match ps with - | [] => `(True) - | [p] => pure p - | p :: rest => do `($p ∧ $(← conj rest)) - -def transConst (mode : Mode) (c : LConst) : TransM Term := do - match c with - | .intConst i => - if i < 0 then `((-$(quote i.natAbs) : Int)) else `(($(quote i.toNat) : Int)) - | .boolConst b => - match mode, b with - | .prop, true => `(True) - | .prop, false => `(False) - | .val, true => `(true) - | .val, false => `(false) - | .strConst s => pure (quote s) - | .bitvecConst n v => `(($(quote v.toNat) : BitVec $(quote n))) - | .realConst _ => fail "real constants are not supported yet" - -/-- A binder name for a quantifier or lambda that does not clash with enclosing binders. -/ -def binderName (n : String) : TransM Ident := do - let base := if n.isEmpty then "x" else n - let taken := (← read).bvars.map (·.1.getId) - if taken.contains (Name.mkSimple base) then fresh base else pure (ident base) - -mutual - -partial def transExpr (mode : Mode) (e : Core.Expression.Expr) : TransM Term := do - let ctx ← read - match e with - | .const _ c => transConst mode c - | .fvar _ x ty => - let t := ctx.vars.getD x.name (ident x.name) - let ty := ty <|> ctx.tys[x.name]? - match mode with - | .prop => if isBoolTy ty then asProp t else pure t - | .val => pure t - | .bvar _ i => - match ctx.bvars[i]? with - | some (x, ty) => - match mode with - | .prop => if isBoolTy ty then asProp x else pure x - | .val => pure x - | none => fail s!"unbound de Bruijn index {i}" - | .op _ o ty => transOp mode o.name ty [] - | .app .. => - let (h, args) := spine e - match h with - | .op _ o ty => transOp mode o.name ty args - | _ => - let f ← transExpr .val h - let args ← args.mapM (transExpr .val) - `($f $(args.toArray)*) - | .ite _ c t f => - let c ← transExpr .prop c - let t ← transExpr mode t - let f ← transExpr mode f - `(if $c then $t else $f) - | .eq _ a b => - let a ← transExpr .val a - let b ← transExpr .val b - match mode with - | .prop => `($a = $b) - | .val => `(decide ($a = $b)) - | .quant _ k n ty _trig body => - let x ← binderName n - let some mty := ty | fail "quantifier without a type annotation" - let tyT ← transTy mty - let body ← withReader (fun c => { c with bvars := (x, ty) :: c.bvars }) (transExpr .prop body) - let p ← match k with - | .all => `(∀ $x:ident : $tyT, $body) - | .exist => `(∃ $x:ident : $tyT, $body) - match mode with - | .prop => pure p - | .val => asBool p - | .abs _ n ty body => - let x ← binderName n - let body ← withReader (fun c => { c with bvars := (x, ty) :: c.bvars }) (transExpr .val body) - match ty with - | some mty => do `(fun ($x:ident : $(← transTy mty)) => $body) - | none => `(fun $x:ident => $body) - -/-- Operators by their Core name (`CoreOp.toString`): `Int.Add`, `Bool.And`, `Bv32.SLt`, -`select`, `Sequence.length`, …; anything else is a user function. -/ -partial def transOp (mode : Mode) (name : String) (ty : Option LMonoTy) - (args : List Core.Expression.Expr) : TransM Term := do - let vals : TransM (List Term) := args.mapM (transExpr .val) - let props : TransM (List Term) := args.mapM (transExpr .prop) - -- a predicate: `Prop` in prop mode, `Bool` via `decide` in val mode - let cmp (p : Term) : TransM Term := match mode with | .prop => pure p | .val => asBool p - -- a `Bool`-valued operation: `= true` in prop mode - let boolRes (t : Term) : TransM Term := match mode with | .prop => asProp t | .val => pure t - let un (f : Term → TransM Term) : TransM Term := do - match ← vals with | [a] => f a | _ => fail s!"{name}: expected one argument" - let bin (f : Term → Term → TransM Term) : TransM Term := do - match ← vals with | [a, b] => f a b | _ => fail s!"{name}: expected two arguments" - let binP (f : Term → Term → TransM Term) : TransM Term := do - match ← props with | [a, b] => f a b | _ => fail s!"{name}: expected two arguments" - let unP (f : Term → TransM Term) : TransM Term := do - match ← props with | [a] => f a | _ => fail s!"{name}: expected one argument" - let parts := name.splitOn "." - match parts with - -- integers and reals - | ["Int", k] | ["Real", k] => - match k with - | "Add" => bin fun a b => `($a + $b) - | "Sub" => bin fun a b => `($a - $b) - | "Mul" => bin fun a b => `($a * $b) - | "Neg" => un fun a => `(-$a) - | "Div" => bin fun a b => `($a / $b) - | "Mod" => bin fun a b => `($a % $b) - | "DivT" => bin fun a b => `(Int.tdiv $a $b) - | "ModT" => bin fun a b => `(Int.tmod $a $b) - | "SafeDiv" | "SafeMod" | "SafeDivT" | "SafeModT" => - fail s!"{name} carries a precondition obligation that the translator does not emit yet" - - | "Lt" => bin fun a b => do cmp (← `($a < $b)) - | "Le" => bin fun a b => do cmp (← `($a ≤ $b)) - | "Gt" => bin fun a b => do cmp (← `($a > $b)) - | "Ge" => bin fun a b => do cmp (← `($a ≥ $b)) - | _ => - if k.startsWith "ToBv" then - let some n := (String.ofList (k.toList.drop 4)).toNat? | fail s!"bad operator {name}" - un fun a => `(BitVec.ofInt $(quote n) $a) - else fail s!"operator {name} is not supported yet" - -- booleans - | ["Bool", k] => - match mode, k with - | .prop, "And" => binP fun a b => `($a ∧ $b) - | .prop, "Or" => binP fun a b => `($a ∨ $b) - | .prop, "Not" => unP fun a => `(¬ $a) - | .prop, "Implies" => binP fun a b => `($a → $b) - | .prop, "Equiv" => binP fun a b => `($a ↔ $b) - | .val, "And" => bin fun a b => `($a && $b) - | .val, "Or" => bin fun a b => `($a || $b) - | .val, "Not" => un fun a => `(!$a) - | .val, "Implies" => bin fun a b => `(!$a || $b) - | .val, "Equiv" => bin fun a b => `($a == $b) - | _, _ => fail s!"operator {name} is not supported yet" - -- bit vectors `Bv{n}.{kind}` - | [bv, k] => - if bv.startsWith "Bv" then - match k with - | "Add" => bin fun a b => `($a + $b) - | "Sub" => bin fun a b => `($a - $b) - | "Mul" => bin fun a b => `($a * $b) - | "Neg" => un fun a => `(-$a) - | "Not" => un fun a => `(~~~$a) - | "And" => bin fun a b => `($a &&& $b) - | "Or" => bin fun a b => `($a ||| $b) - | "Xor" => bin fun a b => `($a ^^^ $b) - | "Shl" => bin fun a b => `($a <<< $b) - | "UShr" => bin fun a b => `($a >>> $b) - | "SShr" => bin fun a b => `(BitVec.sshiftRight $a ($b).toNat) - | "UDiv" => bin fun a b => `($a / $b) - | "UMod" => bin fun a b => `($a % $b) - | "SDiv" => bin fun a b => `(BitVec.sdiv $a $b) - | "SMod" => bin fun a b => `(BitVec.smod $a $b) - | "ULt" => bin fun a b => do cmp (← `($a < $b)) - | "ULe" => bin fun a b => do cmp (← `($a ≤ $b)) - | "UGt" => bin fun a b => do cmp (← `($a > $b)) - | "UGe" => bin fun a b => do cmp (← `($a ≥ $b)) - | "SLt" => bin fun a b => do boolRes (← `(BitVec.slt $a $b)) - | "SLe" => bin fun a b => do boolRes (← `(BitVec.sle $a $b)) - | "SGt" => bin fun a b => do boolRes (← `(BitVec.slt $b $a)) - | "SGe" => bin fun a b => do boolRes (← `(BitVec.sle $b $a)) - | "Concat" => bin fun a b => `($a ++ $b) - | "ToUInt" => un fun a => `((($a).toNat : Int)) - | "ToInt" => un fun a => `(($a).toInt) - | _ => - if k.startsWith "Extract_" then - match (String.ofList (k.toList.drop 8)).splitOn "_" with - | [hi, lo] => - let some hi := hi.toNat? | fail s!"bad operator {name}" - let some lo := lo.toNat? | fail s!"bad operator {name}" - un fun a => `(BitVec.extractLsb $(quote hi) $(quote lo) $a) - | _ => fail s!"bad operator {name}" - else if k.startsWith "Safe" || k.endsWith "Overflow" then - fail s!"{name} carries an overflow obligation that the translator does not emit yet" - else fail s!"operator {name} is not supported yet" - else if bv == "Sequence" then - match k with - | "length" => un fun s => `((($s).size : Int)) - | "select!" => bin fun s i => `($s[($i).toNat]!) - | "update!" => do - match ← vals with - | [s, i, v] => `(($s).set! ($i).toNat $v) - | _ => fail s!"{name}: expected three arguments" - | "empty" => `(#[]) - | "append" => bin fun a b => `($a ++ $b) - | "contains" => bin fun s v => do boolRes (← `(($s).contains $v)) - | "take!" => bin fun s n => `(($s).extract 0 ($n).toNat) - | "drop!" => bin fun s n => `(($s).extract ($n).toNat ($s).size) - | "select" | "update" | "take" | "drop" => - fail s!"{name} carries a bounds obligation that the translator does not emit yet; the unchecked `{k}!` form is translated" - | _ => fail s!"operator {name} is not supported yet" - else userFn - -- maps - | ["select"] => bin fun m k => `($m $k) - | ["update"] => do - -- a lambda rather than `Function.update`, which lives in Mathlib - match ← vals with - | [m, k, v] => `(fun k' => if k' = $k then $v else $m k') - | _ => fail "update: expected three arguments" - | ["mapConst"] => un fun v => `(fun _ => $v) - | _ => userFn -where - /-- A user-declared function, applied; `= true` in prop mode if its result is `bool`. -/ - userFn : TransM Term := do - let vs ← args.mapM (transExpr .val) - let t ← if vs.isEmpty then pure (ident name : Term) else `($(ident name) $(vs.toArray)*) - match mode with - | .prop => if isBoolTy (resultTy ty args.length) then asProp t else pure t - | .val => pure t - -end - -/-! ## Statements -/ - -/-- The loop-carried variables of a body, as the contract states them: Strata's -`Block.modifiedVars` (`set`, `havoc`, call `inout`/`out` arguments, at any depth) minus the -variables the body itself declares (`Block.initVars`, i.e. `definedVars` with scoped names -included), first occurrence first. -/ -def loopVars (body : List Core.Statement) : List String := - let decl := (Imperative.Block.initVars body).map (·.name) - (((Imperative.Block.modifiedVars body).map (·.name)).filter (· ∉ decl)).eraseDups - -mutual - -partial def transStmts (ss : List Core.Statement) : TransM (Array DoItem) := do - match ss with - | [] => pure #[] - | .cmd (.cmd (.init x ty rhs _)) :: rest => - let some mty := ty.toMonoType? | fail s!"local {x.name} has a polymorphic type" - let tyT ← transTy mty - let xI := ident x.name - let it ← match rhs with - | .det e => do letMut xI tyT (← transExpr .val e) - | .nondet => letMutHavoc xI tyT - let restItems ← withReader - (fun c => { c with vars := c.vars.insert x.name xI, tys := c.tys.insert x.name mty }) - (transStmts rest) - pure (#[← item it] ++ restItems) - | s :: rest => - let items ← transStmt s - let restItems ← transStmts rest - pure (items ++ restItems) - -partial def transStmt (s : Core.Statement) : TransM (Array DoItem) := do - let ctx ← read - match s with - | .cmd (.cmd c) => - match c with - | .init x .. => fail s!"internal: init {x.name} not handled by transStmts" - | .set x (.det e) _ => do pure #[← item (← assign (ident x.name) (← transExpr .val e))] - | .set x .nondet _ => do pure #[← item (← assignHavoc (ident x.name))] - | .assert _ e _ => do pure #[← item (← assert (← transExpr .prop e))] - | .assume _ e _ => do pure #[← item (← assume (← transExpr .prop e))] - | .cover l _ _ => do warn s!"cover {l} ignored: no counterpart in the layer yet"; pure #[] - | .cmd (.call n _ _) => fail s!"call to {n}: procedure calls are not supported yet" - | .block _ ss _ => transStmts ss - | .ite (.det c) t e _ => do - let c ← transExpr .prop c - let t ← transStmts t - let e ← transStmts e - pure #[← item (← ite c t e)] - | .ite .nondet t e _ => do - let b ← fresh "b" - let t ← transStmts t - let e ← transStmts e - let elems ← iteNondet b t e - elems.mapM fun el => do pure (← item el) - | .loop (.det g) measure invs body _ => do - if measure.isSome then warn "loop measure ignored (partial correctness)" - let vars := (loopVars body).toArray - let tys ← vars.mapM fun x => do - let some t := ctx.tys[x]? | fail s!"loop assigns {x}, which is not in scope" - transTy t - let s ← fresh "s" - let k := vars.size - -- in the invariant and guard, each loop variable is a projection of the state - let withProj (st : Term) (act : TransM Term) : TransM Term := do - let mut m := ctx.vars - for j in [:k] do - m := m.insert vars[j]! (← proj st j k) - withReader (fun c => { c with vars := m }) act - let invConj : TransM Term := do - let ps ← invs.mapM fun (_, e) => transExpr .prop e - conj ps - whileInv s (vars.map ident) tys - (inv := fun st => withProj st invConj) - (guard := fun st => withProj st (transExpr .prop g)) - (body := fun _ => withReader (fun c => { c with inLoop := true }) (transStmts body)) - | .loop .nondet .. => fail "nondeterministic loops are not supported yet" - | .exit l _ => - if l == ctx.procLabel then - if ctx.inLoop then fail "exit (return) inside a loop body is not supported yet" - else do pure #[← item (← ret (← tuple (ctx.outputs.map fun o => (o : Term))))] - else fail s!"exit {l}: labelled exits are not supported yet" - | .funcDecl .. => fail "local function declarations are not supported (lift them first)" - | .typeDecl .. => fail "local type declarations are not supported (lift them first)" - -end - -/-! ## Procedures -/ - -def transProc (p : Core.Procedure) : TransM (Array Command) := do - let name := p.header.name.name - let inputs := p.header.inputs.toList - let outputs := p.header.outputs.toList - let inputNames := inputs.map (·.1.name) - let mut vars : Std.HashMap String Term := {} - let mut tys : Std.HashMap String LMonoTy := {} - for (x, t) in inputs ++ outputs do - vars := vars.insert x.name (ident x.name) - tys := tys.insert x.name t - let outIds := (outputs.map fun (o, _) => ident o.name).toArray - let ctx : Ctx := { vars, tys, procLabel := name, outputs := outIds } - let body ← match p.body with - | .structured ss => pure ss - | .cfg _ => fail s!"{name}: CFG bodies are not supported" - if body.isEmpty then - warn s!"{name}: no body (abstract procedure), skipped" - return #[] - -- the definition - let items ← withReader (fun _ => ctx) do - let mut pre : Array DoItem := #[] - for (o, t) in outputs do - let tyT ← transTy t - let oI := ident o.name - if inputNames.contains o.name then pre := pre.push (← item (← letMut oI tyT oI)) - else pre := pre.push (← item (← letMutHavoc oI tyT)) - let bodyItems ← transStmts body - let retItem ← item (← ret (← tuple (outIds.map fun o => (o : Term)))) - pure (pre ++ bodyItems ++ #[retItem]) - let params ← inputs.mapM fun (x, t) => do pure (ident x.name, ← transTy t) - let outTys ← outputs.mapM fun (_, t) => transTy t - let retTy ← tupleType outTys.toArray - let defCmd ← procDef (ident name) params.toArray retTy (← doBlock items) - -- the specification: requires (all) as precondition, non-free ensures as postcondition - let rName := if inputNames.contains "r" || outputs.any (·.1.name == "r") then "__r" else "r" - let r := ident rName - let k := outputs.length - let preT ← withReader (fun _ => ctx) do - conj (← p.spec.preconditions.toList.mapM fun (_, c) => transExpr .prop c.expr) - let postT ← do - let mut m := vars - for j in [:k] do - m := m.insert (outputs[j]!).1.name (← proj (r : Term) j k) - withReader (fun _ => { ctx with vars := m }) do - let checked := p.spec.postconditions.toList.filter fun (_, c) => - match c.attr with | .Free => false | _ => true - conj (← checked.mapM fun (_, c) => transExpr .prop c.expr) - let specCmd ← specTheorem (ident s!"{name}_spec") (ident name) params.toArray preT r postT - pure #[defCmd, specCmd] - -/-! ## The command -/ - -unsafe def evalProgramUnsafe (t : Term) : TermElabM Core.Program := do - let ty := mkApp2 (mkConst ``Except [.zero, .zero]) (mkConst ``String) (mkConst ``Core.Program) - let r ← Term.evalTerm (Except String Core.Program) ty (← `(Strata.Shallow.Translate.typeCheckStr $t)) - match r with - | .ok p => pure p - | .error m => throwError m!"shallow_embed: {m}" - -@[implemented_by evalProgramUnsafe] -opaque evalProgram (t : Term) : TermElabM Core.Program - -/-- `shallow_embed p`: translate every procedure of the Boole program `p` into a `def` on the -`ND` layer and a `_spec` theorem, elaborating both. The generated commands are shown as -info messages. -/ -syntax (name := shallowEmbed) "shallow_embed " term : command - -@[command_elab shallowEmbed] def elabShallowEmbed : CommandElab := fun stx => do - let `(shallow_embed $t:term) := stx | throwUnsupportedSyntax - let prog ← liftTermElabM (evalProgram t) - for d in prog.decls do - match d with - | .proc p _ => - let (cmds, st) ← liftMacroM (((transProc p).run {}).run {}) - for w in st.warnings do logWarning w - for c in cmds do - logInfo m!"{c}" - elabCommand c - | .func f _ => logWarning m!"shallow_embed: function {f.name.name} skipped (not supported yet)" - | .recFuncBlock .. => logWarning "shallow_embed: recursive functions skipped (not supported yet)" - | .ax .. => logWarning "shallow_embed: axiom skipped (not supported yet)" - | .type .. => logWarning "shallow_embed: type declaration skipped (not supported yet)" - | .distinct .. => logWarning "shallow_embed: distinct declaration skipped (not supported yet)" - -end Strata.Shallow.Translate diff --git a/StrataBooleTest.lean b/StrataBooleTest.lean index c6744bd..03bade0 100644 --- a/StrataBooleTest.lean +++ b/StrataBooleTest.lean @@ -61,6 +61,20 @@ import StrataBooleTest.FeatureRequests.scalar_reduce import StrataBooleTest.FeatureRequests.seq_empty_literal import StrataBooleTest.FeatureRequests.sha256_compact_indexed import StrataBooleTest.CoreTests.DefineFunRecTests -import StrataBooleTest.shallow_find_max -import StrataBooleTest.hoare_max2 -import StrataBooleTest.generic_datatypes +import StrataBooleTest.HoareLogic.shallow_find_max +import StrataBooleTest.HoareLogic.hoare_max2 +import StrataBooleTest.HoareLogic.generic_datatypes +import StrataBooleTest.HoareLogic.shallow_reflect +import StrataBooleTest.HoareLogic.hoare_find_max_core +import StrataBooleTest.HoareLogic.hoare_locals_core +import StrataBooleTest.HoareLogic.hoare_ops_core +import StrataBooleTest.HoareLogic.hoare_frame_core +import StrataBooleTest.HoareLogic.hoare_quant_core +import StrataBooleTest.HoareLogic.hoare_havoc_gap +import StrataBooleTest.HoareLogic.hoare_nondet_core +import StrataBooleTest.HoareLogic.deep_max2 +import StrataBooleTest.HoareLogic.deep_count_up +import StrataBooleTest.HoareLogic.deep_quant +import StrataBooleTest.HoareLogic.deep_nondet +import StrataBooleTest.HoareLogic.boole_globals +import StrataBooleTest.HoareLogic.demo_pipeline diff --git a/StrataBooleTest/HoareLogic/boole_globals.lean b/StrataBooleTest/HoareLogic/boole_globals.lean new file mode 100644 index 0000000..10b20dd --- /dev/null +++ b/StrataBooleTest/HoareLogic/boole_globals.lean @@ -0,0 +1,75 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.MetaVerifier +import StrataBoole.HoareLogic.Reflect.Boole +import StrataBoole.HoareLogic.Deep.Delab +import StrataBoole.HoareLogic.Hoare.Tactic +import StrataBoole.HoareLogic.Deep.Tactic + +/-! # Two results, a modified global and `old` across a loop, from Boole, on both routes + +`returns (count: int, last: int)` gives two `out` parameters, `modifies total` makes the global +an `inout` parameter with an `old total` snapshot, and the loop writes the global. The frame +carries `old total` and `n` through the loop. -/ + +namespace Strata.BooleTest + +def globalsPgm : StrataDDM.Program := +#strata +program Boole; + +var total : int; + +procedure addAll (n: int) returns (count: int, last: int) +spec { + modifies total; + requires (n >= 0); + ensures [cnt]: (count == n); + ensures [tot]: (total == old(total) + n); + ensures [lst]: (last == n); +} +{ + count := 0; + last := 0; + while (count < n) + invariant [c]: (0 <= count && count <= n) + invariant [t]: (total == old(total) + count) + invariant [l]: (last == count) + { + total := total + 1; + count := count + 1; + last := count; + } +}; +#end + +shallow_reflect globalsPgm + +set_option maxHeartbeats 400000 in +theorem addAll_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple globalsPgm_ast params "addAll" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals omega + +theorem addAll_correct : Strata.Deep.Procedure.Correct addAll_ast := by + unfold addAll_ast + core_vcgen <;> core_lift <;> omega + +/-- info: 'Strata.BooleTest.addAll_contract' depends on axioms: [propext, + Classical.choice, + Quot.sound, + Core.WFFactory._native.native_decide.ax_1✝, + Core.WFFactoryArray_func_name_nodup._native.native_decide.ax_1_1✝] -/ +#guard_msgs in +#print axioms addAll_contract + +/-- info: 'Strata.BooleTest.addAll_correct' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms addAll_correct + +end Strata.BooleTest diff --git a/StrataBooleTest/HoareLogic/deep_count_up.lean b/StrataBooleTest/HoareLogic/deep_count_up.lean new file mode 100644 index 0000000..7f1e843 --- /dev/null +++ b/StrataBooleTest/HoareLogic/deep_count_up.lean @@ -0,0 +1,72 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import Strata.Languages.Core +import StrataDDM.Integration.Lean.HashCommands +import StrataBoole.HoareLogic.Reflect.Core +import StrataBoole.HoareLogic.Deep.Delab +import StrataBoole.HoareLogic.Deep.Tactic + +/-! # Example: a loop with invariants and a `decreases` clause + +The loop carries its own annotations, so `core_vcgen` needs no `invariants` clause: +the loop rule (`wp_loop`) reads them off the AST. After `core_lift`, five conditions are +left, named after the obligation and the clause (the invariants are unlabeled, so they are +`inv_1` and `inv_2`; `bound` is the lower bound of the measure at the head, `decreases` its +decrease over an iteration): +``` +case step.inv_1 +i : Int +hinv_1 : 0 ≤ i +n : Int +hcountUp_requires_0 : 0 ≤ n +hguard : i < n +hbound : i ≤ n +⊢ 0 ≤ i + 1 +``` +with `step.inv_2 : i + 1 ≤ n`, `step.bound : i + 1 ≤ n`, `step.decreases : i < i + 1` and +`exit.countUp_ensures_1 : i = n` (under `hguard : n ≤ i`). The entry conditions (`i := 0` +establishes the invariants and `n - i ≥ 0`) are closed by `core_lift`. In the VCs, `i` is the +value in an arbitrary loop-head state, while `n` is still the value in the initial state: the +body assigns only `i`, so the loop rule frames `n`. +-/ + +open StrataDDM (Program) +open Strata.Deep + +-- `countUp` below is defined by `#core_reflect`; if that failed, an auto-bound implicit +-- would silently stand in for it. +set_option autoImplicit false + +namespace Strata.DeepExamples + +def countUpPgm := +#strata +program Core; + +procedure countUp(n : int, out i : int) +spec { + requires (int.ge(n, 0)); + ensures (i == n); +} +{ + i := 0; + while (int.lt(i, n)) + decreases int.sub(n, i) + invariant int.le(0, i) + invariant int.le(i, n) + { + i := int.add(i, 1); + } +}; +#end + +#core_reflect countUpPgm + +theorem countUp_correct : Procedure.Correct countUp := by + unfold countUp + core_vcgen <;> core_lift <;> omega + +end Strata.DeepExamples diff --git a/StrataBooleTest/HoareLogic/deep_max2.lean b/StrataBooleTest/HoareLogic/deep_max2.lean new file mode 100644 index 0000000..c423faa --- /dev/null +++ b/StrataBooleTest/HoareLogic/deep_max2.lean @@ -0,0 +1,116 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import Strata.Languages.Core +import StrataDDM.Integration.Lean.HashCommands +import StrataBoole.HoareLogic.Reflect.Core +import StrataBoole.HoareLogic.Deep.Delab +import StrataBoole.HoareLogic.Deep.Tactic + +/-! # Example: the maximum of two integers, through the deep embedding + +1. Write the procedure in Core syntax. +2. `#core_reflect` translates and type checks it with Strata's Core front end, and + defines `max2 : Core.Procedure`, the AST as a Lean term. +3. `Procedure.Correct max2` is the procedure's contract read as a Hoare triple: + `{requires} body {ensures}` over the big-step semantics `Exec`. +4. `core_vcgen` applies one rule per statement and leaves verification conditions; + `core_lift` names them and evaluates the embedding away; `omega` closes the arithmetic. + +`#print max2` shows the procedure in Core notation (`Deep/Delab.lean`). After +`core_vcgen`, the VC of the then branch reads +``` +case ifTrue.rest +σ : State +hguard : evalBool σ ⟪x >= y⟫ = some true +v : Val +hv : some v = eval σ ⟪x⟫ +⊢ Labeled "max2_ensures_0" (σ.update "m" v ⊨ ⟪m >= x⟫) ∧ + Labeled "max2_ensures_1" (σ.update "m" v ⊨ ⟪m >= y⟫) ∧ + Labeled "max2_ensures_2" (σ.update "m" v ⊨ ⟪m == x || m == y⟫) +``` +and `core_lift` closes all but one of the six conditions, leaving +``` +case else.max2_ensures_0 +x y : Int +hguard : x < y +⊢ x ≤ y +``` +-/ + +open StrataDDM (Program) +open Strata.Deep + +-- `max2` below is defined by `#core_reflect`; if that failed, an auto-bound implicit would +-- silently stand in for it. +set_option autoImplicit false + +namespace Strata.DeepExamples + +def max2Pgm := +#strata +program Core; + +procedure max2(x : int, y : int, out m : int) +spec { + ensures (int.ge(m, x)); + ensures (int.ge(m, y)); + ensures (m == x || m == y); +} +{ + if (int.ge(x, y)) { + m := x; + } else { + m := y; + } +}; +#end + +#core_reflect max2Pgm + +theorem max2_correct : Procedure.Correct max2 := by + unfold max2 + simp only [Procedure.Correct] + core_vcgen <;> core_lift <;> omega + +/-! ## A wrong contract is refuted + +The triple is not vacuous: with `ensures (m == x)`, the VC of the else branch is false, +and a concrete run shows the contract itself is false. From `x = 0`, `y = 1` the guard +is false, the body sets `m := y = 1`, and `m == x` fails. -/ + +def max2WrongPgm := +#strata +program Core; + +procedure max2Wrong(x : int, y : int, out m : int) +spec { + ensures (m == x); +} +{ + if (int.ge(x, y)) { + m := x; + } else { + m := y; + } +}; +#end + +#core_reflect max2WrongPgm + +theorem max2Wrong_refuted : ¬ Procedure.Correct max2Wrong := by + unfold max2Wrong + simp only [Procedure.Correct, Procedure.pre, Procedure.post, Triple] + intro h + let σ : State := fun v => if v = "y" then .int 1 else .int 0 + -- The run `ite_false` → `m := y` → end, from `σ`. + have := h σ (by simp [σ, OldSnapshot, PresHold, Core.Procedure.Header.getInoutParams, + Core.getInoutParams, ListMap.keys]) _ + (.ite_false (by simp [σ, evalBool, eval, evalIn, binop]) + (.set (v := .int 1) (by simp [σ, eval, evalIn]) .nil) .nil) + simp [σ, Outcome.Sat, PostsHold, Labeled, Holds, SatT, evalBoolIn, evalIn, eqAt, typeOf, + State.update] at this + +end Strata.DeepExamples diff --git a/StrataBooleTest/HoareLogic/deep_nondet.lean b/StrataBooleTest/HoareLogic/deep_nondet.lean new file mode 100644 index 0000000..6ccd966 --- /dev/null +++ b/StrataBooleTest/HoareLogic/deep_nondet.lean @@ -0,0 +1,77 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.HoareLogic.Reflect.Core +import StrataBoole.HoareLogic.Deep.Delab +import StrataBoole.HoareLogic.Deep.Tactic +import StrataDDM.Integration.Lean.HashCommands + +/-! # Nondeterministic control and `cover`, on the deep embedding + +`if (*)` proves both branches, `while (*)` is the loop rule with nothing learned from a +guard, and `cover` is a skip. -/ + +open StrataDDM (Program) +open Strata.Deep + +set_option autoImplicit false + +namespace Strata.DeepExamples + +def nondetPgm := +#strata +program Core; + +procedure pick(n : int, out r : int) +spec { + requires [nonneg]: int.ge(n, 0); + ensures [range]: int.le(0, r) && int.le(r, n); +} +{ + if * { + r := 0; + } else { + r := n; + } + cover [reach]: int.ge(r, 0); +}; + +procedure drift(n : int, out r : int) +spec { + requires [nonneg]: int.ge(n, 0); + ensures [bound]: int.le(0, r) && int.le(r, n); +} +{ + r := 0; + while * + invariant [inv]: int.le(0, r) && int.le(r, n) + { + if (int.lt(r, n)) { + r := int.add(r, 1); + } else { + } + } +}; +#end + +#core_reflect nondetPgm + +theorem pick_correct : Procedure.Correct pick := by + unfold pick + core_vcgen <;> core_lift <;> omega + +theorem drift_correct : Procedure.Correct drift := by + unfold drift + core_vcgen <;> core_lift <;> omega + +/-- info: 'Strata.DeepExamples.pick_correct' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms pick_correct + +/-- info: 'Strata.DeepExamples.drift_correct' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms drift_correct + +end Strata.DeepExamples diff --git a/StrataBooleTest/HoareLogic/deep_quant.lean b/StrataBooleTest/HoareLogic/deep_quant.lean new file mode 100644 index 0000000..b9022a3 --- /dev/null +++ b/StrataBooleTest/HoareLogic/deep_quant.lean @@ -0,0 +1,117 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.HoareLogic.Reflect.Core +import StrataBoole.HoareLogic.Deep.Delab +import StrataBoole.HoareLogic.Deep.Tactic +import StrataDDM.Integration.Lean.HashCommands + +/-! # Quantifiers in clauses, on the deep embedding + +A clause is read as a proposition (`SatT`), so `forall` and `exists` over integers lift to +the Lean quantifiers wherever a clause appears: a `requires` (a hypothesis to instantiate), an +`ensures` and an `assert` (goals), an `invariant` (both), nested binders included. The last +procedure is the shape a Boole `choose` lowers to: an `assert` of an `exists`, a `havoc`, an +`assume`; the deep embedding's values are canonical, so the havocked value lifts. -/ + +open StrataDDM (Program) +open Strata.Deep + +set_option autoImplicit false + +namespace Strata.DeepExamples + +def quantPgm := +#strata +program Core; + +procedure bounds(n : int, out r : int) +spec { + requires [nonneg]: int.ge(n, 0); + ensures [all]: forall i : int :: int.le(i, n) ==> int.lt(i, r); + ensures [witness]: exists i : int :: int.gt(i, n) && int.lt(i, r); + ensures [pairs]: forall i : int :: forall j : int :: + int.le(i, j) ==> int.le(int.add(i, r), int.add(j, r)); +} +{ + r := int.add(n, 2); +}; + +procedure fromForall(n : int, out r : int) +spec { + requires [lb]: forall i : int :: int.ge(i, n) ==> int.ge(i, 0); + ensures [nonneg]: int.ge(r, 0); +} +{ + r := n; +}; + +procedure fill(n : int, out r : int) +spec { + requires [nonneg]: int.ge(n, 0); + ensures [done]: forall i : int :: int.le(0, i) && int.lt(i, n) ==> int.lt(i, r); +} +{ + r := 0; + while (int.lt(r, n)) + invariant [range]: int.le(0, r) && int.le(r, n) + invariant [below]: forall i : int :: int.lt(i, r) ==> int.lt(i, n) + { + r := int.add(r, 1); + } +}; + +procedure chooseIt(n : int, out r : int) +spec { + requires [nonneg]: int.ge(n, 0); + ensures [ge]: int.ge(r, n); + ensures [lt]: int.lt(r, int.add(n, 2)); +} +{ + assert [some_pick]: exists i : int :: int.ge(i, n) && int.lt(i, int.add(n, 2)); + havoc r; + assume [pick]: int.ge(r, n) && int.lt(r, int.add(n, 2)); +}; +#end + +#core_reflect quantPgm + +theorem bounds_correct : Procedure.Correct bounds := by + unfold bounds + core_vcgen <;> core_lift + case witness => exact ⟨n + 1, by omega⟩ + all_goals (intros; omega) + +theorem fromForall_correct : Procedure.Correct fromForall := by + unfold fromForall + core_vcgen <;> core_lift + +theorem fill_correct : Procedure.Correct fill := by + unfold fill + core_vcgen <;> core_lift <;> (intros; omega) + +theorem chooseIt_correct : Procedure.Correct chooseIt := by + unfold chooseIt + core_vcgen <;> core_lift + case some_pick => exact ⟨n, by omega⟩ + all_goals omega + +/-- info: 'Strata.DeepExamples.bounds_correct' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms bounds_correct + +/-- info: 'Strata.DeepExamples.fromForall_correct' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms fromForall_correct + +/-- info: 'Strata.DeepExamples.fill_correct' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms fill_correct + +/-- info: 'Strata.DeepExamples.chooseIt_correct' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms chooseIt_correct + +end Strata.DeepExamples diff --git a/StrataBooleTest/HoareLogic/demo_pipeline.lean b/StrataBooleTest/HoareLogic/demo_pipeline.lean new file mode 100644 index 0000000..0d652b1 --- /dev/null +++ b/StrataBooleTest/HoareLogic/demo_pipeline.lean @@ -0,0 +1,291 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.HoareLogic.Pipeline + +namespace Strata.PipelineDemo + +def demoPgm : StrataDDM.Program := +#strata +program Boole; + +procedure max2 (x: int, y: int) returns (r: int) +spec { + ensures [ge_x]: (r >= x); + ensures [ge_y]: (r >= y); + ensures [one_of]: (r == x || r == y); +} +{ + if (x >= y) { + r := x; + } else { + r := y; + } +}; + +procedure loopSimple (n: int) returns (r: int) +spec { + requires [nonneg]: (n >= 0); +} +{ + var sum : int; + var i : int; + + sum := 0; + i := 0; + while(i < n) + invariant (i <= n && ((i * (i-1)) div 2 == sum)) + { + sum := sum + i; + i := i + 1; + } + assert [sum_assert]: ((n * (n-1)) div 2 == sum); + assert [neg_cond]: (i == n); + r := sum; +}; + +procedure max2Wrong (x: int, y: int) returns (r: int) +spec { + ensures [strict]: (r > x); +} +{ + if (x >= y) { + r := x; + } else { + r := y; + } +}; + +procedure caller (x: int) returns (r: int) +spec { + ensures [same]: (r == x); +} +{ + call r := max2(x, x); +}; +#end + +shallow_reflect demoPgm + +/-- +info: def Strata.PipelineDemo.max2_ast : Core.Procedure := +⟦procedure max2(x : int, y : int, out r : int) + spec { + ensures [ge_x]: r >= x; + ensures [ge_y]: r >= y; + ensures [one_of]: r == x || r == y; + } + { + max2: { if (x >= y) { r := x } else { r := y } } + }⟧ +-/ +#guard_msgs in +#print max2_ast + +/-- +info: def Strata.PipelineDemo.loopSimple_ast : Core.Procedure := +⟦procedure loopSimple(n : int, out r : int) + spec { + requires [nonneg]: n >= 0; + } + { + loopSimple: { + var sum : int; + var i : int; + sum := 0; + i := 0; + while (i < n) + invariant i <= n && i * (i - 1) / 2 == sum + { sum := sum + i; i := i + 1 }; + assert [sum_assert]: n * (n - 1) / 2 == sum; + assert [neg_cond]: i == n; + r := sum + } + }⟧ +-/ +#guard_msgs in +#print loopSimple_ast + +theorem max2_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple demoPgm_ast params "max2" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals omega + +theorem max2_correct : Strata.Deep.Procedure.Correct max2_ast := by + unfold max2_ast + core_vcgen + all_goals core_lift + all_goals omega + +theorem loopSimple_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple demoPgm_ast params "loopSimple" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals first | omega | grind + +theorem loopSimple_correct : Strata.Deep.Procedure.Correct loopSimple_ast := by + unfold loopSimple_ast + core_vcgen + all_goals core_lift + all_goals first | omega | grind + +def morePgm : StrataDDM.Program := +#strata +program Boole; + +var total : int; + +procedure sumTo (n: int) returns (s: int) +spec { + requires (n >= 0); + ensures [total]: (2 * s == n * (n + 1)); +} +{ + s := 0; + for i : int := 1 to n + invariant [range]: (1 <= i && i <= n + 1) + invariant [partial]: (2 * s == (i - 1) * i) + { + s := s + i; + } +}; + +procedure bounds (n: int) returns (r: int) +spec { + requires (n >= 0); + ensures [all]: (∀ i : int :: (i <= n ==> i < r)); + ensures [pairs]: (∀ i : int :: (∀ j : int :: (i <= j ==> i + r <= j + r))); +} +{ + r := n + 2; +}; + +procedure pick (n: int) returns (r: int) +spec { + requires (n >= 0); + ensures [range]: (0 <= r && r <= n); + ensures [positive]: (r + 1 > 0); +} +{ + if * { + r := 0; + } else { + r := n; + } + cover [reach]: (r >= 0); + assume [extra]: (r + 1 > 0); +}; + +procedure addAll (n: int) returns (count: int) +spec { + modifies total; + requires (n >= 0); + ensures [cnt]: (count == n); + ensures [tot]: (total == old(total) + n); +} +{ + count := 0; + while (count < n) + invariant [c]: (0 <= count && count <= n) + invariant [t]: (total == old(total) + count) + { + total := total + 1; + count := count + 1; + } +}; + +procedure chooseIt (n: int) returns (r: int) +spec { + requires (n >= 0); + ensures [ge]: (r >= n); + ensures [lt]: (r < n + 2); +} +{ + r := ε z : int :: (z >= n && z < n + 2); +}; +#end + +boole_prove morePgm sumTo +boole_prove morePgm bounds +boole_prove morePgm pick +boole_prove morePgm addAll +boole_prove morePgm chooseIt deep with (first | omega | exact ⟨n, by omega⟩) + +/-- +error: unsolved goals +case then.strict +x y : Int +hguard : x ≥ y +⊢ x > x +-/ +#guard_msgs in +boole_prove demoPgm max2Wrong strata + +/-- +error: unsolved goals +case then.strict +y x : Int +hguard : y ≤ x +⊢ False +-/ +#guard_msgs in +boole_prove demoPgm max2Wrong deep + +/-- +error: hoare: no rule for the statement + ⟦call max2(x, x, out r)⟧ +Supported: var, :=, havoc, assert, assume, cover, if, if *, { }, while, while *. +-/ +#guard_msgs in +boole_prove demoPgm caller strata + +/-- +error: core: no rule for the statement + ⟦call max2(x, x, out r)⟧ +Supported: var, :=, havoc, assert, assume, cover, if, if *, { }, while, while *. +-/ +#guard_msgs in +boole_prove demoPgm caller deep + +/-- info: 'Strata.PipelineDemo.max2_contract' depends on axioms: [propext, + Classical.choice, + Quot.sound, + Core.WFFactory._native.native_decide.ax_1✝, + Core.WFFactoryArray_func_name_nodup._native.native_decide.ax_1_1✝] -/ +#guard_msgs in +#print axioms max2_contract + +/-- info: 'Strata.PipelineDemo.max2_correct' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms max2_correct + +/-- info: 'Strata.PipelineDemo.loopSimple_contract' depends on axioms: [propext, + Classical.choice, + Quot.sound, + Core.WFFactory._native.native_decide.ax_1✝, + Core.WFFactoryArray_func_name_nodup._native.native_decide.ax_1_1✝] -/ +#guard_msgs in +#print axioms loopSimple_contract + +/-- info: 'Strata.PipelineDemo.loopSimple_correct' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms loopSimple_correct + +/-- info: 'Strata.PipelineDemo.sumTo_contract' depends on axioms: [propext, + Classical.choice, + Quot.sound, + Core.WFFactory._native.native_decide.ax_1✝, + Core.WFFactoryArray_func_name_nodup._native.native_decide.ax_1_1✝] -/ +#guard_msgs in +#print axioms sumTo_contract + +/-- info: 'Strata.PipelineDemo.chooseIt_correct' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms chooseIt_correct + +end Strata.PipelineDemo diff --git a/StrataBooleTest/generic_datatypes.lean b/StrataBooleTest/HoareLogic/generic_datatypes.lean similarity index 100% rename from StrataBooleTest/generic_datatypes.lean rename to StrataBooleTest/HoareLogic/generic_datatypes.lean diff --git a/StrataBooleTest/HoareLogic/hoare_find_max_core.lean b/StrataBooleTest/HoareLogic/hoare_find_max_core.lean new file mode 100644 index 0000000..691d58b --- /dev/null +++ b/StrataBooleTest/HoareLogic/hoare_find_max_core.lean @@ -0,0 +1,69 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.HoareLogic.Reflect.Core +import StrataBoole.HoareLogic.Deep.Delab +import StrataBoole.HoareLogic.Hoare.Tactic +import StrataDDM.Integration.Lean.HashCommands + +/-! # The maximum of a map's first `n` entries: refused + +The procedure reads `nums[0]` and `nums[i]`, applications of `select`, which `Core.Factory` has +no concrete evaluation for. `Expression.eval` then returns `none` on `var max : int := nums[0]`, +the statement has no execution, and every contract of the procedure holds vacuously of it. The +rules would prove any such contract, so `hoare_contract` refuses the procedure with an error +instead; the refusal is pinned below. The procedure becomes provable once `select` evaluates +over a map value form in Strata. -/ + +open StrataDDM (Program) + +namespace Strata.HoareTest + +def findMaxPgm : Program := +#strata +program Core; + +procedure findMax(nums : Map int int, n : int, out ret : int) +spec { + requires [nonempty]: int.gt(n, 0); + ensures [upper]: forall __q0 : int :: int.le(0, __q0) && int.lt(__q0, n) ==> int.ge(ret, nums[__q0]); + ensures [attained]: exists __q0 : int :: int.le(0, __q0) && int.lt(__q0, n) && ret == nums[__q0]; +} +{ + var max : int := nums[0]; + var maxIndex : int := 0; + var i : int := 1; + while (int.lt(i, n)) + decreases int.sub(n, i) + invariant [bounds]: int.le(1, i) && int.le(i, n) + invariant [above]: forall __q0 : int :: int.le(0, __q0) && int.lt(__q0, i) ==> int.ge(max, nums[__q0]) + invariant [witness]: int.le(0, maxIndex) && int.lt(maxIndex, i) && max == nums[maxIndex] + { + if (int.gt(nums[i], max)) { + max := nums[i]; + maxIndex := i; + } + i := int.add(i, 1); + } + assert [found]: int.le(0, maxIndex) && int.lt(maxIndex, n) && max == nums[maxIndex]; + ret := nums[maxIndex]; +}; +#end + +#core_reflect findMaxPgm + +noncomputable def findMaxProg : Core.Program := { decls := [.proc findMax .empty] } + +example : findMaxProg.findProcByString? "findMax" = some findMax := rfl + +/-- +error: hoare: `var max := …` applies `select`, which `Core.Factory` does not evaluate: the statement has no execution, so its triple would hold vacuously +-/ +#guard_msgs in +example (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple findMaxProg params "findMax" := by + hoare_contract + +end Strata.HoareTest diff --git a/StrataBooleTest/HoareLogic/hoare_frame_core.lean b/StrataBooleTest/HoareLogic/hoare_frame_core.lean new file mode 100644 index 0000000..2209546 --- /dev/null +++ b/StrataBooleTest/HoareLogic/hoare_frame_core.lean @@ -0,0 +1,138 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.HoareLogic.Reflect.Core +import StrataBoole.HoareLogic.Deep.Delab +import StrataBoole.HoareLogic.Hoare.Tactic +import StrataDDM.Integration.Lean.HashCommands + +/-! # Variables a loop does not write, against `Core.Logic.Hoare` + +A loop only changes the variables its body writes. What the entry knew about any other variable +survives the loop without being repeated in an invariant: a precondition on an input (`addK`), +an assignment before the loop (`keep`), and both across nested loops (`nested`). -/ + +open StrataDDM (Program) + +namespace Strata.HoareTest + +def framePgm : Program := +#strata +program Core; + +procedure addK(n : int, k : int, out r : int) +spec { + requires [nonneg]: int.ge(n, 0); + requires [pos]: int.gt(k, 0); + ensures [res]: r == int.add(n, k); + ensures [more]: int.gt(r, n); +} +{ + var i : int := 0; + r := k; + while (int.lt(i, n)) + invariant [range]: int.le(0, i) && int.le(i, n) + invariant [acc]: r == int.add(k, i) + { + r := int.add(r, 1); + i := int.add(i, 1); + } +}; + +procedure keep(n : int, c : int, out r : int, out k : int) +spec { + requires [nonneg]: int.ge(n, 0); + ensures [count]: r == n; + ensures [kept]: k == int.add(c, 1); +} +{ + var t : int := int.add(c, 1); + r := 0; + while (int.lt(r, n)) + invariant [range]: int.le(0, r) && int.le(r, n) + { + r := int.add(r, 1); + } + k := t; +}; + +procedure nested(n : int, k : int, out r : int) +spec { + requires [nonneg]: int.ge(n, 0); + requires [pos]: int.gt(k, 0); + ensures [res]: int.gt(r, 0); +} +{ + var i : int := 0; + r := k; + while (int.lt(i, n)) + invariant [range]: int.le(0, i) && int.le(i, n) + invariant [acc]: int.ge(r, k) + { + var j : int := 0; + while (int.lt(j, i)) + invariant [jrange]: int.le(0, j) && int.le(j, i) + invariant [acc]: int.ge(r, k) + { + r := int.add(r, 1); + j := int.add(j, 1); + } + i := int.add(i, 1); + } +}; +#end + +#core_reflect framePgm + +noncomputable def frameProg : Core.Program := + { decls := [.proc addK .empty, .proc keep .empty, .proc nested .empty] } + +theorem addK_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple frameProg params "addK" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals first | omega | grind + +theorem keep_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple frameProg params "keep" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals first | omega | grind + +set_option maxHeartbeats 400000 in +theorem nested_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple frameProg params "nested" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals first | omega | grind + +/-- info: 'Strata.HoareTest.addK_contract' depends on axioms: [propext, + Classical.choice, + Quot.sound, + Core.WFFactory._native.native_decide.ax_1✝, + Core.WFFactoryArray_func_name_nodup._native.native_decide.ax_1_1✝] -/ +#guard_msgs in +#print axioms addK_contract + +/-- info: 'Strata.HoareTest.keep_contract' depends on axioms: [propext, + Classical.choice, + Quot.sound, + Core.WFFactory._native.native_decide.ax_1✝, + Core.WFFactoryArray_func_name_nodup._native.native_decide.ax_1_1✝] -/ +#guard_msgs in +#print axioms keep_contract + +/-- info: 'Strata.HoareTest.nested_contract' depends on axioms: [propext, + Classical.choice, + Quot.sound, + Core.WFFactory._native.native_decide.ax_1✝, + Core.WFFactoryArray_func_name_nodup._native.native_decide.ax_1_1✝] -/ +#guard_msgs in +#print axioms nested_contract + +end Strata.HoareTest diff --git a/StrataBooleTest/HoareLogic/hoare_havoc_gap.lean b/StrataBooleTest/HoareLogic/hoare_havoc_gap.lean new file mode 100644 index 0000000..9affbf1 --- /dev/null +++ b/StrataBooleTest/HoareLogic/hoare_havoc_gap.lean @@ -0,0 +1,46 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.HoareLogic.Hoare.Tactic + +/-! # Why the value of a `havoc` is not lifted + +`havoc x` and `var x : int;` give `x` a value `v` about which the semantics says only +`HasVal.valueOfTy Core.Factory v int`: `v` is a value (`isValue`) and the syntactic type checker +assigns it `int`. Neither check looks at the type annotation an operator carries, so a partially +applied operator whose annotation lies is such a value, and it is not a numeral. The lifting +reads integer variables as numerals, so it cannot read `x` after a `havoc`; a `choose` lowers to +`assert ∃; havoc; assume` and stops there. Making `valueOfTy` canonical for the base types (as +`Procedure.valueHasType`, which types a procedure's inputs, already is) would close the gap; the +facts below are what such a change has to refute. -/ + +open Strata Core Lambda + +namespace Strata.HoareTest + +/-- `Int.Neg`, annotated as an integer: a value of type `int` that is not a numeral. -/ +def junk : Core.Expression.Expr := .op () ⟨"Int.Neg", ()⟩ (some .int) + +theorem junk_typeCheck : LExpr.typeCheck [] junk = some .int := rfl + +theorem junk_isValue : LExpr.isValue Core.Factory junk = true := by + rw [LExpr.isValue.eq_def] + simp only [junk, Lambda.Factory.callOfLFunc, Lambda.getLFuncCall, Lambda.getLFuncCall.go] + rw [Strata.Hoare.Eval.coreFactory_intNeg] + simp [Lambda.intNegFunc, Lambda.unaryOp] + +/-- The value a `havoc x` or an uninitialized `var x : int` may store. -/ +theorem junk_valueOfTy : + Imperative.HasVal.valueOfTy (P := Core.Expression) Core.Factory junk (.forAll [] .int) := + ⟨.int, junk_isValue, rfl, rfl⟩ + +/-- A clause reading `x` stays well typed, so its denotation is a real, model-dependent +proposition rather than a vacuous one. -/ +theorem junk_hasTypeA : LExpr.HasTypeA (T := Core.CoreLParams) [] junk .int := .op + +theorem junk_not_numeral (i : Int) : junk ≠ .const () (.intConst i) := by + simp [junk] + +end Strata.HoareTest diff --git a/StrataBooleTest/HoareLogic/hoare_locals_core.lean b/StrataBooleTest/HoareLogic/hoare_locals_core.lean new file mode 100644 index 0000000..39b7679 --- /dev/null +++ b/StrataBooleTest/HoareLogic/hoare_locals_core.lean @@ -0,0 +1,89 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.HoareLogic.Reflect.Core +import StrataBoole.HoareLogic.Deep.Delab +import StrataBoole.HoareLogic.Hoare.Tactic +import StrataDDM.Integration.Lean.HashCommands + +/-! # Declarations that go out of scope, against `Core.Logic.Hoare` + +Leaving a block drops the variables it declared, so the rules for blocks, branches and loop +bodies have to say how the postcondition survives that. The rules here state it at the projected +environment instead of asking for `PostWF`, so the three placements a Boole lowering produces +all go through: `sumTo` declares its locals at the procedure level and has an `ensures`; +`count` declares one in a nested block, as a `for` loop lowers, and one in a branch. -/ + +open StrataDDM (Program) + +namespace Strata.HoareTest + +def localsPgm : Program := +#strata +program Core; + +procedure sumTo(n : int, out r : int) +spec { + requires [nonneg]: int.ge(n, 0); + ensures [sum]: int.mul(2, r) == int.mul(n, int.add(n, 1)); +} +{ + var s : int := 0; + var i : int := 0; + while (int.lt(i, n)) + invariant [bounds]: int.le(0, i) && int.le(i, n) + invariant [partial]: int.mul(2, s) == int.mul(i, int.add(i, 1)) + { + i := int.add(i, 1); + s := int.add(s, i); + } + r := s; +}; + +procedure count(n : int, out r : int) +spec { + requires [nonneg]: int.ge(n, 0); + ensures [counted]: r == n; +} +{ + var c : int := 0; + loop: { + var i : int := 0; + while (int.lt(i, n)) + invariant [range]: int.le(0, i) && int.le(i, n) + invariant [tracks]: c == i + { + c := int.add(c, 1); + i := int.add(i, 1); + } + } + if (int.lt(c, 0)) { + var t : int := 0; + c := t; + } else { + } + r := c; +}; +#end + +#core_reflect localsPgm + +noncomputable def localsProg : Core.Program := { decls := [.proc sumTo .empty, .proc count .empty] } + +theorem sumTo_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple localsProg params "sumTo" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals first | omega | grind + +theorem count_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple localsProg params "count" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals first | omega | grind + +end Strata.HoareTest diff --git a/StrataBooleTest/hoare_max2.lean b/StrataBooleTest/HoareLogic/hoare_max2.lean similarity index 99% rename from StrataBooleTest/hoare_max2.lean rename to StrataBooleTest/HoareLogic/hoare_max2.lean index 1c0cc2b..a637340 100644 --- a/StrataBooleTest/hoare_max2.lean +++ b/StrataBooleTest/HoareLogic/hoare_max2.lean @@ -3,14 +3,14 @@ SPDX-License-Identifier: Apache-2.0 OR MIT -/ -import StrataBoole.HoareLift +import StrataBoole.HoareLogic.HoareLift import StrataBoole.MetaVerifier /-! # `max2` against Core's Hoare logic, by hand The first procedure proved on the Lean route of `docs/HoareLogic.md`. Everything the tactic of step 1 will automate is written out once here; the lifting lemmas it uses -are in `StrataBoole.HoareLift`. +are in `StrataBoole.HoareLogic.HoareLift`. -/ open Strata Lambda Core HoareLift diff --git a/StrataBooleTest/HoareLogic/hoare_nondet_core.lean b/StrataBooleTest/HoareLogic/hoare_nondet_core.lean new file mode 100644 index 0000000..3d21233 --- /dev/null +++ b/StrataBooleTest/HoareLogic/hoare_nondet_core.lean @@ -0,0 +1,91 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.HoareLogic.Reflect.Core +import StrataBoole.HoareLogic.Deep.Delab +import StrataBoole.HoareLogic.Hoare.Tactic +import StrataDDM.Integration.Lean.HashCommands + +/-! # Nondeterministic control and `cover`, against `Core.Logic.Hoare` + +`if (*)` proves both branches, `while (*)` is the framed loop rule with nothing learned from a +guard, and `cover` is a skip. -/ + +open StrataDDM (Program) + +namespace Strata.HoareTest + +def nondetPgm : Program := +#strata +program Core; + +procedure pick(n : int, out r : int) +spec { + requires [nonneg]: int.ge(n, 0); + ensures [range]: int.le(0, r) && int.le(r, n); +} +{ + if * { + r := 0; + } else { + r := n; + } + cover [reach]: int.ge(r, 0); +}; + +procedure drift(n : int, out r : int) +spec { + requires [nonneg]: int.ge(n, 0); + ensures [bound]: int.le(0, r) && int.le(r, n); +} +{ + r := 0; + while * + invariant [inv]: int.le(0, r) && int.le(r, n) + { + if (int.lt(r, n)) { + r := int.add(r, 1); + } else { + } + } +}; +#end + +#core_reflect nondetPgm + +noncomputable def nondetProg : Core.Program := + { decls := [.proc pick .empty, .proc drift .empty] } + +theorem pick_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple nondetProg params "pick" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals omega + +theorem drift_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple nondetProg params "drift" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals omega + +/-- info: 'Strata.HoareTest.pick_contract' depends on axioms: [propext, + Classical.choice, + Quot.sound, + Core.WFFactory._native.native_decide.ax_1✝, + Core.WFFactoryArray_func_name_nodup._native.native_decide.ax_1_1✝] -/ +#guard_msgs in +#print axioms pick_contract + +/-- info: 'Strata.HoareTest.drift_contract' depends on axioms: [propext, + Classical.choice, + Quot.sound, + Core.WFFactory._native.native_decide.ax_1✝, + Core.WFFactoryArray_func_name_nodup._native.native_decide.ax_1_1✝] -/ +#guard_msgs in +#print axioms drift_contract + +end Strata.HoareTest diff --git a/StrataBooleTest/HoareLogic/hoare_ops_core.lean b/StrataBooleTest/HoareLogic/hoare_ops_core.lean new file mode 100644 index 0000000..82283bc --- /dev/null +++ b/StrataBooleTest/HoareLogic/hoare_ops_core.lean @@ -0,0 +1,121 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.HoareLogic.Reflect.Core +import StrataBoole.HoareLogic.Deep.Delab +import StrataBoole.HoareLogic.Hoare.Tactic +import StrataDDM.Integration.Lean.HashCommands + +/-! # The remaining integer and boolean operators, against `Core.Logic.Hoare` + +Unary negation and `!`, the connectives `==>` and `<==>`, `==` on booleans, conditional +expressions, and guards built from `&&`, `||` and `!`. Each is read in two places: by the +evaluator when it sits in a guard or on the right of an assignment, and by the denotation when +it sits in a clause. -/ + +open StrataDDM (Program) + +namespace Strata.HoareTest + +def opsPgm : Program := +#strata +program Core; + +procedure absVal(x : int, out r : int) +spec { + ensures [nonneg]: int.ge(r, 0); + ensures [neg]: int.lt(x, 0) ==> r == int.neg(x); + ensures [pos]: int.ge(x, 0) ==> r == x; +} +{ + r := if int.lt(x, 0) then int.neg(x) else x; +}; + +procedure clamp(x : int, lo : int, hi : int, out r : int) +spec { + requires [ord]: int.le(lo, hi); + ensures [inRange]: int.le(lo, r) && int.le(r, hi); + ensures [fixed]: !(int.lt(x, lo) || int.gt(x, hi)) ==> r == x; + ensures [same]: (r == x) <==> (int.le(lo, x) && int.le(x, hi)); + ensures [flags]: (int.lt(r, x) == int.gt(x, hi)) && (int.gt(r, x) == int.lt(x, lo)); +} +{ + if (int.lt(x, lo) || int.gt(x, hi)) { + if (int.lt(x, lo)) { + r := lo; + } else { + r := hi; + } + } else { + r := x; + } +}; + +procedure countDown(n : int, out r : int) +spec { + requires [nonneg]: int.ge(n, 0); + ensures [zero]: r == 0; +} +{ + r := n; + while (!(r == 0) && int.gt(r, 0)) + invariant [range]: int.ge(r, 0) + { + r := int.sub(r, 1); + } +}; +#end + +#core_reflect opsPgm + +noncomputable def opsProg : Core.Program := + { decls := [.proc absVal .empty, .proc clamp .empty, .proc countDown .empty] } + +theorem absVal_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple opsProg params "absVal" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals first | omega | grind + +theorem clamp_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple opsProg params "clamp" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals first | omega | grind + +theorem countDown_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple opsProg params "countDown" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals first | omega | grind + +/-- info: 'Strata.HoareTest.absVal_contract' depends on axioms: [propext, + Classical.choice, + Quot.sound, + Core.WFFactory._native.native_decide.ax_1✝, + Core.WFFactoryArray_func_name_nodup._native.native_decide.ax_1_1✝] -/ +#guard_msgs in +#print axioms absVal_contract + +/-- info: 'Strata.HoareTest.clamp_contract' depends on axioms: [propext, + Classical.choice, + Quot.sound, + Core.WFFactory._native.native_decide.ax_1✝, + Core.WFFactoryArray_func_name_nodup._native.native_decide.ax_1_1✝] -/ +#guard_msgs in +#print axioms clamp_contract + +/-- info: 'Strata.HoareTest.countDown_contract' depends on axioms: [propext, + Classical.choice, + Quot.sound, + Core.WFFactory._native.native_decide.ax_1✝, + Core.WFFactoryArray_func_name_nodup._native.native_decide.ax_1_1✝] -/ +#guard_msgs in +#print axioms countDown_contract + +end Strata.HoareTest diff --git a/StrataBooleTest/HoareLogic/hoare_quant_core.lean b/StrataBooleTest/HoareLogic/hoare_quant_core.lean new file mode 100644 index 0000000..75235f5 --- /dev/null +++ b/StrataBooleTest/HoareLogic/hoare_quant_core.lean @@ -0,0 +1,141 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.HoareLogic.Reflect.Core +import StrataBoole.HoareLogic.Deep.Delab +import StrataBoole.HoareLogic.Hoare.Tactic +import StrataDDM.Integration.Lean.HashCommands + +/-! # Quantifiers in clauses, against `Core.Logic.Hoare` + +`forall` and `exists` over integers lift to the Lean quantifiers wherever a clause is read: a +`requires` (a hypothesis to instantiate), an `ensures` and an `assert` (goals), an `invariant` +(both), nested binders included. An `assume` lifts to a hypothesis at the store it was passed +with. -/ + +open StrataDDM (Program) + +namespace Strata.HoareTest + +def quantPgm : Program := +#strata +program Core; + +procedure bounds(n : int, out r : int) +spec { + requires [nonneg]: int.ge(n, 0); + ensures [all]: forall i : int :: int.le(i, n) ==> int.lt(i, r); + ensures [witness]: exists i : int :: int.gt(i, n) && int.lt(i, r); + ensures [pairs]: forall i : int :: forall j : int :: + int.le(i, j) ==> int.le(int.add(i, r), int.add(j, r)); +} +{ + r := int.add(n, 2); +}; + +procedure fromForall(n : int, out r : int) +spec { + requires [lb]: forall i : int :: int.ge(i, n) ==> int.ge(i, 0); + ensures [nonneg]: int.ge(r, 0); +} +{ + r := n; +}; + +procedure fill(n : int, out r : int) +spec { + requires [nonneg]: int.ge(n, 0); + ensures [done]: forall i : int :: int.le(0, i) && int.lt(i, n) ==> int.lt(i, r); +} +{ + r := 0; + while (int.lt(r, n)) + invariant [range]: int.le(0, r) && int.le(r, n) + invariant [below]: forall i : int :: int.lt(i, r) ==> int.lt(i, n) + { + r := int.add(r, 1); + } +}; + +procedure assumed(n : int, out r : int) +spec { + ensures [big]: int.gt(r, n); +} +{ + r := n; + assume [bump]: int.gt(n, 0); + assert [gap]: exists i : int :: int.gt(i, 0) && int.le(i, n); + r := int.add(r, n); +}; +#end + +#core_reflect quantPgm + +noncomputable def quantProg : Core.Program := + { decls := [.proc bounds .empty, .proc fromForall .empty, .proc fill .empty, .proc assumed .empty] } + +theorem bounds_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple quantProg params "bounds" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + case witness => exact ⟨n + 1, by omega⟩ + all_goals (intros; omega) + +theorem fromForall_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple quantProg params "fromForall" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + case nonneg => have := hlb n; omega + +theorem fill_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple quantProg params "fill" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals (intros; omega) + +theorem assumed_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple quantProg params "assumed" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + case gap => exact ⟨n, by omega⟩ + all_goals omega + +/-- info: 'Strata.HoareTest.bounds_contract' depends on axioms: [propext, + Classical.choice, + Quot.sound, + Core.WFFactory._native.native_decide.ax_1✝, + Core.WFFactoryArray_func_name_nodup._native.native_decide.ax_1_1✝] -/ +#guard_msgs in +#print axioms bounds_contract + +/-- info: 'Strata.HoareTest.fromForall_contract' depends on axioms: [propext, + Classical.choice, + Quot.sound, + Core.WFFactory._native.native_decide.ax_1✝, + Core.WFFactoryArray_func_name_nodup._native.native_decide.ax_1_1✝] -/ +#guard_msgs in +#print axioms fromForall_contract + +/-- info: 'Strata.HoareTest.fill_contract' depends on axioms: [propext, + Classical.choice, + Quot.sound, + Core.WFFactory._native.native_decide.ax_1✝, + Core.WFFactoryArray_func_name_nodup._native.native_decide.ax_1_1✝] -/ +#guard_msgs in +#print axioms fill_contract + +/-- info: 'Strata.HoareTest.assumed_contract' depends on axioms: [propext, + Classical.choice, + Quot.sound, + Core.WFFactory._native.native_decide.ax_1✝, + Core.WFFactoryArray_func_name_nodup._native.native_decide.ax_1_1✝] -/ +#guard_msgs in +#print axioms assumed_contract + +end Strata.HoareTest diff --git a/StrataBooleTest/shallow_find_max.lean b/StrataBooleTest/HoareLogic/shallow_find_max.lean similarity index 98% rename from StrataBooleTest/shallow_find_max.lean rename to StrataBooleTest/HoareLogic/shallow_find_max.lean index d28238c..24a0784 100644 --- a/StrataBooleTest/shallow_find_max.lean +++ b/StrataBooleTest/HoareLogic/shallow_find_max.lean @@ -3,7 +3,7 @@ SPDX-License-Identifier: Apache-2.0 OR MIT -/ -import StrataBoole.Shallow.Layer +import StrataBoole.HoareLogic.Shallow.Layer /-! Three programs, written by hand in the form the translation from Core should produce, verified with `mvcgen` on the layer. This file is the diff --git a/StrataBooleTest/HoareLogic/shallow_reflect.lean b/StrataBooleTest/HoareLogic/shallow_reflect.lean new file mode 100644 index 0000000..7c9cc79 --- /dev/null +++ b/StrataBooleTest/HoareLogic/shallow_reflect.lean @@ -0,0 +1,234 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.MetaVerifier +import StrataBoole.HoareLogic.Reflect.Boole + +/-! # Reflection of the type-checked Core procedure + +`shallow_reflect` binds the type-checked Core program to `

_ast` and each of its procedures to +`_ast`. The literals must be the very values the type checker produced (both are computed +and compared here), and they must compute by kernel reduction. The programs cover `havoc` and +`assume`, `Map` types, quantifiers, nested loops, metadata and provenance. -/ + +namespace Strata.ReflectTest + +open Strata + +def pickNatPgm : StrataDDM.Program := #strata +program Boole; + +procedure pick_nat() returns (x : int) +spec { ensures x >= 0; } +{ havoc x; assume x >= 0; }; +#end + +def sumToPgm : StrataDDM.Program := #strata +program Boole; + +procedure sum_to(n : int) returns (r : int) +spec { requires n >= 0; ensures 2 * r == n * (n + 1); } +{ + var i : int := 0; + r := 0; + while (i < n) + invariant 0 <= i && i <= n && 2 * r == i * (i + 1) + { + i := i + 1; + r := r + i; + } +}; +#end + +def findMaxPgm : StrataDDM.Program := #strata +program Boole; + +procedure witnessOccurs(nums: Map int int, n: int, idx: int, value: int) returns () +spec { + requires 0 <= idx && idx < n; + requires value == nums[idx]; + ensures ∃ j: int . 0 <= j && j < n && value == nums[j]; +} +{ + assume ∃ j: int . 0 <= j && j < n && value == nums[j]; +}; + +procedure findMax (nums: Map int int, n: int) returns (ret: int) +spec { + requires n > 0; + ensures ∀ i: int . 0 <= i && i < n ==> ret >= nums[i]; + ensures ∃ j: int . 0 <= j && j < n && ret == nums[j]; +} +{ + var max : int := nums[0]; + var maxIndex : int := 0; + var i : int := 1; + + while (i < n) + decreases n - i + invariant (1 <= i && i <= n) + invariant (∀ k: int . 0 <= k && k < i ==> max >= nums[k]) + invariant (0 <= maxIndex && maxIndex < i && max == nums[maxIndex]) + { + if (nums[i] > max) { + max := nums[i]; + maxIndex := i; + } + i := i + 1; + } + assert 0 <= maxIndex && maxIndex < n && max == nums[maxIndex]; + ret := nums[maxIndex]; +}; +#end + +def loopNoStatePgm : StrataDDM.Program := #strata +program Boole; + +procedure loop_no_state(n : int) returns () +spec { requires n >= 0; } +{ + var j : int := 0; + while (j < 0) + invariant j == 0 + { var t : int := 1; assert t == 1; } + assert j == 0; +}; +#end + +def loopOneVarPgm : StrataDDM.Program := #strata +program Boole; + +procedure loop_one_var(n : int) returns (r : int) +spec { requires n >= 0; ensures r == n; } +{ + r := 0; + while (r < n) + invariant 0 <= r && r <= n + { r := r + 1; } +}; +#end + +def loopNestedPgm : StrataDDM.Program := #strata +program Boole; + +procedure loop_nested(n : int) returns (s : int) +spec { requires n >= 0; ensures s >= 0; } +{ + var i : int := 0; + s := 0; + while (i < n) + invariant 0 <= i && i <= n && s >= 0 + { + var j : int := 0; + while (j < i) + invariant 0 <= j && j <= i && s >= 0 + { s := s + 1; j := j + 1; } + i := i + 1; + } +}; +#end + +#guard_msgs in +shallow_reflect pickNatPgm +#guard_msgs in +shallow_reflect sumToPgm +#guard_msgs in +shallow_reflect findMaxPgm +#guard_msgs in +shallow_reflect loopNoStatePgm +#guard_msgs in +shallow_reflect loopOneVarPgm +#guard_msgs in +shallow_reflect loopNestedPgm + +example : Core.Procedure := sum_to_ast + +/-- Every procedure of the type-checked program is among the reflected literals, and +conversely. -/ +def reflectedFaithfully (pgm : StrataDDM.Program) (asts : List Core.Procedure) : Bool := + match Strata.Reflect.typeCheckStr pgm with + | .ok cp => + let procs := cp.decls.filterMap fun | .proc p _ => some p | _ => none + procs.length == asts.length && procs.all fun p => asts.any fun a => decide (p = a) + | .error _ => false + +/-- info: [true, true, true, true, true, true] -/ +#guard_msgs in +#eval [reflectedFaithfully pickNatPgm [pick_nat_ast], + reflectedFaithfully sumToPgm [sum_to_ast], + reflectedFaithfully findMaxPgm [witnessOccurs_ast, findMax_ast], + reflectedFaithfully loopNoStatePgm [loop_no_state_ast], + reflectedFaithfully loopOneVarPgm [loop_one_var_ast], + reflectedFaithfully loopNestedPgm [loop_nested_ast]] + +/-! The whole program is bound as well, named after the identifier. -/ + +example : Core.Program := findMaxPgm_ast + +def programFaithful (pgm : StrataDDM.Program) (ast : Core.Program) : Bool := + match Strata.Reflect.typeCheckStr pgm with + | .ok cp => decide (cp = ast) + | .error _ => false + +/-- info: [true, true, true, true, true, true] -/ +#guard_msgs in +#eval [programFaithful pickNatPgm pickNatPgm_ast, + programFaithful sumToPgm sumToPgm_ast, + programFaithful findMaxPgm findMaxPgm_ast, + programFaithful loopNoStatePgm loopNoStatePgm_ast, + programFaithful loopOneVarPgm loopOneVarPgm_ast, + programFaithful loopNestedPgm loopNestedPgm_ast] + +/-! ## Declarations other than procedures + +An uninterpreted type and function, an axiom, a function with a body, and a datatype. -/ + +def declsPgm : StrataDDM.Program := #strata +program Boole; + +type Scalar; +function reduce(b : Scalar) : Scalar; +axiom (∀ s : Scalar . (reduce(reduce(s)) == reduce(s))); +function twice(x : int) : int { x + x } +datatype OptionInt () { None(), Some(val: int) }; + +procedure use_decls(x : int) returns (r : int) +spec { ensures r == twice(x); } +{ + var o : OptionInt; + o := Some(x); + r := OptionInt..val(o) + x; +}; +#end + +#guard_msgs in +shallow_reflect declsPgm + +/-- info: true -/ +#guard_msgs in +#eval programFaithful declsPgm declsPgm_ast + +def hasKind (p : Core.Program) (k : Core.Decl → Bool) : Bool := p.decls.any k + +example : hasKind declsPgm_ast (fun | .type (.con _) _ => true | _ => false) = true := by decide +example : hasKind declsPgm_ast (fun | .type (.data _) _ => true | _ => false) = true := by decide +example : hasKind declsPgm_ast (fun | .ax .. => true | _ => false) = true := by decide +example : hasKind declsPgm_ast (fun | .func f _ => f.body.isSome | _ => false) = true := by decide +example : hasKind declsPgm_ast (fun | .func f _ => f.body.isNone | _ => false) = true := by decide +example : hasKind declsPgm_ast (fun | .proc .. => true | _ => false) = true := by decide + +/-! The literal computes by kernel reduction. -/ + +example : sum_to_ast.header.name.name = "sum_to" := rfl +example : sum_to_ast.spec.preconditions.toList.length = 1 := rfl +example : sum_to_ast.spec.postconditions.toList.length = 1 := rfl + +/-- The lowering wraps the body in a block named after the procedure. -/ +example : (match sum_to_ast.body with + | .structured [.block "sum_to" _ _] => true + | _ => false) = true := by + decide + +end Strata.ReflectTest diff --git a/StrataBooleTest/shallow_translate.lean b/StrataBooleTest/shallow_translate.lean deleted file mode 100644 index 57bcef3..0000000 --- a/StrataBooleTest/shallow_translate.lean +++ /dev/null @@ -1,142 +0,0 @@ -/- - Copyright Strata Contributors - - SPDX-License-Identifier: Apache-2.0 OR MIT --/ -import StrataBoole.MetaVerifier -import StrataBoole.Shallow.Layer -import StrataBoole.Shallow.Translate - -/-! # The translator against the hand-written programs - -`shallow_embed` must produce, from Boole source, definitions on which the hand-written -specifications of `shallow_find_max.lean` still prove, and its own `_spec` theorems must -close. The three programs: `pick_nat` and `sum_to` (the sources recorded with the first -experiments) and the repository's Verus-emitted `findMax` without its final `call` -(procedure calls are not translated yet). -/ - -set_option mvcgen.warning false - -namespace Strata.Shallow.TranslateTest - -open Strata Std.Do Strata.Shallow Strata.Shallow.ND - -/-! ## `havoc` and `assume` -/ - -def pickNatPgm : StrataDDM.Program := #strata -program Boole; - -procedure pick_nat() returns (x : int) -spec { ensures x >= 0; } -{ havoc x; assume x >= 0; }; -#end - -#guard_msgs (drop info) in -shallow_embed pickNatPgm - -/-- The hand-written specification, unchanged. -/ -theorem pick_nat_spec' : ⦃⌜True⌝⦄ pick_nat ⦃⇓ x => ⌜x ≥ 0⌝⦄ := by - mvcgen [pick_nat] - -/-- info: 'Strata.Shallow.TranslateTest.pick_nat_spec' depends on axioms: [propext, Quot.sound] -/ -#guard_msgs in -#print axioms pick_nat_spec - -/-- info: 'Strata.Shallow.TranslateTest.pick_nat_spec'' depends on axioms: [propext, Quot.sound] -/ -#guard_msgs in -#print axioms pick_nat_spec' - -/-! ## A loop with an invariant -/ - -def sumToPgm : StrataDDM.Program := #strata -program Boole; - -procedure sum_to(n : int) returns (r : int) -spec { requires n >= 0; ensures 2 * r == n * (n + 1); } -{ - var i : int := 0; - r := 0; - while (i < n) - invariant 0 <= i && i <= n && 2 * r == i * (i + 1) - { - i := i + 1; - r := r + i; - } -}; -#end - -#guard_msgs (drop info) in -shallow_embed sumToPgm - -/-- The hand-written specification, unchanged. -/ -theorem sum_to_spec' (n : Int) (h : n ≥ 0) : - ⦃⌜True⌝⦄ sum_to n ⦃⇓ r => ⌜2 * r = n * (n + 1)⌝⦄ := by - mvcgen [sum_to] - all_goals grind - -/-- info: 'Strata.Shallow.TranslateTest.sum_to_spec' depends on axioms: [propext, Classical.choice, Quot.sound] -/ -#guard_msgs in -#print axioms sum_to_spec - -/-- info: 'Strata.Shallow.TranslateTest.sum_to_spec'' depends on axioms: [propext, Classical.choice, Quot.sound] -/ -#guard_msgs in -#print axioms sum_to_spec' - -/-! ## Maps, `if` without `else`, several invariants, quantifiers, a measure - -The program of `find_max_verus.lean` without its last statement, `call witnessOccurs(...)`. -/ - -def findMaxPgm : StrataDDM.Program := #strata -program Boole; - -procedure witnessOccurs(nums: Map int int, n: int, idx: int, value: int) returns () -spec { - requires 0 <= idx && idx < n; - requires value == nums[idx]; - ensures ∃ j: int . 0 <= j && j < n && value == nums[j]; -} -{ - assume ∃ j: int . 0 <= j && j < n && value == nums[j]; -}; - -procedure findMax (nums: Map int int, n: int) returns (ret: int) -spec { - requires n > 0; - ensures ∀ i: int . 0 <= i && i < n ==> ret >= nums[i]; - ensures ∃ j: int . 0 <= j && j < n && ret == nums[j]; -} -{ - var max : int := nums[0]; - var maxIndex : int := 0; - var i : int := 1; - - while (i < n) - decreases n - i - invariant (1 <= i && i <= n) - invariant (∀ k: int . 0 <= k && k < i ==> max >= nums[k]) - invariant (0 <= maxIndex && maxIndex < i && max == nums[maxIndex]) - { - if (nums[i] > max) { - max := nums[i]; - maxIndex := i; - } - i := i + 1; - } - assert 0 <= maxIndex && maxIndex < n && max == nums[maxIndex]; - ret := nums[maxIndex]; -}; -#end - -/-- warning: loop measure ignored (partial correctness) -/ -#guard_msgs (warning, drop info) in -shallow_embed findMaxPgm - -/-- info: 'Strata.Shallow.TranslateTest.witnessOccurs_spec' depends on axioms: [propext, Quot.sound] -/ -#guard_msgs in -#print axioms witnessOccurs_spec - -/-- info: 'Strata.Shallow.TranslateTest.findMax_spec' depends on axioms: [propext, Classical.choice, Quot.sound] -/ -#guard_msgs in -#print axioms findMax_spec - -end Strata.Shallow.TranslateTest diff --git a/docs/HoareLogic.md b/docs/HoareLogic.md index a6a6247..017cd8f 100644 --- a/docs/HoareLogic.md +++ b/docs/HoareLogic.md @@ -95,7 +95,7 @@ So the tactic below is ours to build, and the triple is a stable target. would leave nothing to prove adequacy against, so the Boole semantics is step 5, not step 1. - Goals over Lean values come from lifting, not from a monadic encoding, so - `Std.Do`/`mvcgen` (`StrataBoole/Shallow/Layer.lean`) is off the path. + `Std.Do`/`mvcgen` (`StrataBoole/HoareLogic/Shallow/Layer.lean`) is off the path. - Failure is never vacuous: a construct the tactic cannot handle leaves the goal open instead of closing it. - Datatypes get one generic model, not one Lean inductive per program: a single inductive @@ -110,7 +110,7 @@ So the tactic below is ours to build, and the triple is a stable target. - This is a deep embedding with shallow goals: the program stays data, the Lean term is the proof about it, and what the user sees are goals over Lean values. It started as a shallow embedding in the Velvet sense; say so when the difference matters. The - `Shallow` names left in the tree (`StrataBoole/Shallow/`, `shallow_find_max`) are that + `Shallow` names left in the tree (`StrataBoole/HoareLogic/Shallow/`, `shallow_find_max`) are that prototype's. ## Coverage of the rules @@ -149,23 +149,37 @@ Everything in steps 1 to 3 is exercised by the first two and reused unchanged by ## Status -- `max2` is proved against Strata's triple, by hand, in `StrataBooleTest/hoare_max2.lean`: +- Everything this document describes is in `StrataBoole/HoareLogic/`, with its tests in + `StrataBooleTest/HoareLogic/`. +- Steps 1 to 3 are automated for integer programs. `boole_prove pgm proc` + (`StrataBoole/HoareLogic/Pipeline.lean`) proves `Procedure.contractTriple` for a + procedure of a Boole program with `hoare_contract`, `hoare_vcs`, `hoare_lift` and `omega` + or `grind`. The milestone is reached: `max2` and the counting loop of `demo.lean` + (`StrataBooleTest/HoareLogic/demo_pipeline.lean`). +- `hoare_contract` and `hoare_vcs` apply weakest-precondition rules proved from Strata's, + `if *` and `while *` included (`StrataBoole/HoareLogic/Hoare/`), and leave one goal per + `assert`, invariant and `ensures`, named after its clause. +- `hoare_lift` (`StrataBoole/HoareLogic/Hoare/Lift/`) lifts the `int` and `bool` + built-ins, `==`, `if … then … else` and `∀`/`∃` over `int` to Lean propositions. +- Not covered yet: `call`, `exit`, loop measures, `bv`, `choose`, `bool` parameters. +- `StrataBoole/HoareLogic/Deep/` proves the same programs against its own semantics, with + `core_vcgen` and `core_lift`, and also proves `choose`. +- `max2` is proved against Strata's triple, by hand, in `StrataBooleTest/HoareLogic/hoare_max2.lean`: `contractTriple_of_core_typed`, then `block`, `block`, `ite` and `set`, every side condition by `native_decide` on the reflected program. The lifting lemmas it uses are - in `StrataBoole/HoareLift.lean`: the evaluator on `Int.Ge` over a store of literals + in `StrataBoole/HoareLogic/HoareLift.lean`: the evaluator on `Int.Ge` over a store of literals (one unfolding of `LExpr.eval.eq_2` plus the factory entry's facts), and the denotation of `Int.Ge`, `Bool.And`, `Bool.Or` and `==` on literals in every model, each from the model's agreement with the operator's concrete evaluation. The proof is the specification of the step 1 tactic: it does these steps for any straight-line body with - `if`. Steps 1 and 2 as automation: not started. `Deep/` has both against its own - semantics, with `max2` and a counting loop proved. -- `StrataBoole/Shallow/Layer.lean` is kept until the milestone is reached. + `if`. +- `StrataBoole/HoareLogic/Shallow/Layer.lean` is kept until the milestone is reached. - Two things the hand proof settled. Under the module system, facts about factory entries are not `rfl`; they need `import all` of the defining files and `simp` unfolding. And the typing derivations (`HasTypeA`) must be spelled with the annotations exactly as the lowering writes them, or the rewrite rules do not fire; the tactic should build them from the term, not from the types. -- `StrataBooleTest/generic_datatypes.lean`: first prototype of the carrier. +- `StrataBooleTest/HoareLogic/generic_datatypes.lean`: first prototype of the carrier. - Risks. Strata's own hand proof of a two-branch `if` is some twenty-five lines with `native_decide` and explicit store facts, so discharging the side conditions automatically is the bulk of step 1. Step 4 also waits on Strata carrying the From 0a1fef95530e86731fcfa71c8a2427993b5f7bf7 Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Sat, 14 Nov 2026 09:31:52 +0100 Subject: [PATCH 36/64] Record the merged Hoare rules and the datatype decision in the doc --- docs/HoareLogic.md | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/docs/HoareLogic.md b/docs/HoareLogic.md index 7e3c0c5..b710d70 100644 --- a/docs/HoareLogic.md +++ b/docs/HoareLogic.md @@ -69,7 +69,7 @@ build, on a stable target. with declarations from `denoteEval_congr`, since a postcondition does not read the variables the block drops; and for a call `bodyFrame` and `bodyOutputsTyped`, which are facts about every run of the callee's body. The rules for `assume`, `assert`, `havoc` - and a declaration without initialiser are in strata-org/Strata#1498. The result is one + and a declaration without initialiser came with strata-org/Strata#1498. The result is one goal per `assert`, loop invariant and `ensures`, over the store. This is `core_vcgen` of the `StrataBoole/Deep/` experiment (fork branch `exp/deep-embedding`), retargeted to Strata's `Triple`. @@ -120,8 +120,9 @@ then the benchmark below. and supply the model from one generic carrier, a single inductive of constructor applications with a well-sortedness predicate (`DT.Carrier`, strata-org/Strata#1493, written for the SMT denotation). `nat` is its `pos`/`nat` with `toInt` by structural - recursion. The per-program inductives of strata-org/Strata#1480 serve the SMT path only; - readable goals are notation added later. + recursion. Per-program Lean inductives (strata-org/Strata#1480) are not used: the SMT + path's goals must equal its denotation, which is over the carrier too. Readable goals + are notation added later. - This is a deep embedding with shallow goals: the program stays data, and the user sees goals over Lean values. The `Shallow` names in the tree are the earlier prototype's. @@ -129,8 +130,7 @@ then the benchmark below. | Core | State | | --- | --- | -| assignments, `init` with a value, blocks, `exit`, deterministic `if` and `while`, `call` | rules exist | -| `assert`, `assume`, `havoc`, declaration without initialiser | rules in strata-org/Strata#1498 | +| assignments, `init` with or without a value, `havoc`, `assert`, `assume`, blocks, `exit`, deterministic `if` and `while`, `call` | rules exist | | `if *`, `while *`, loop measures, `cover` | to add | | `int`, `bool`, `bv n` | lifted: `+`, `-`, `*` and comparisons on `int`, `&&`, `\|\|`, three `bv16` operators; the rest to add (step 2) | | `Map`, `Sequence`, `Set`, `string` | constrained in every model; lifting to add (step 2) | @@ -195,14 +195,15 @@ kernel checks that proof for each program. ## Strata changes for this route -This branch pins the `integration/lean-route` branch of the fork: Strata main plus the open -pull requests below. The pin returns to strata-org/Strata when they merge. +This branch pins the `integration/lean-route` branch of the fork: an earlier Strata main +plus the pull requests below. The pin returns to strata-org/Strata when the open ones +merge. | Change | State | Used by | | --- | --- | --- | -| strata-org/Strata#1498: rules `init_nondet`, `havoc`, `assume`, `assert`, and the forms of the last two that read a condition by evaluation | open | step 1 | +| strata-org/Strata#1498: rules `init_nondet`, `havoc`, `assume`, `assert`, and the forms of the last two that read a condition by evaluation | merged | step 1 | | strata-org/Strata#1492: public unfolding lemmas for quantifiers and binders | approved, not merged | quantifier lifting in step 2 | -| strata-org/Strata#1493: datatypes in the SMT denotation, with the generic carrier | open | the SMT path now, the model of step 4 later | +| strata-org/Strata#1493: datatypes in the SMT denotation, with the generic carrier | open, not reviewed | the SMT path now, the model of step 4 later | | strata-org/Strata#1496: `Map` and `Sequence` statements had no execution, and models did not have to satisfy their axioms | closed, fixed upstream by the denotational evaluation | step 2 | | strata-org/Strata#1490: the SMT path refuses the VCs its denotation does not cover | merged | Goal | From c74feec8116f7e22eeccd2c98d785072e44f14bb Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Sat, 14 Nov 2026 19:33:34 +0100 Subject: [PATCH 37/64] Mark the merged denote lemmas and the closed datatype draft in the doc --- docs/HoareLogic.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/HoareLogic.md b/docs/HoareLogic.md index b710d70..2ae1c91 100644 --- a/docs/HoareLogic.md +++ b/docs/HoareLogic.md @@ -120,7 +120,7 @@ then the benchmark below. and supply the model from one generic carrier, a single inductive of constructor applications with a well-sortedness predicate (`DT.Carrier`, strata-org/Strata#1493, written for the SMT denotation). `nat` is its `pos`/`nat` with `toInt` by structural - recursion. Per-program Lean inductives (strata-org/Strata#1480) are not used: the SMT + recursion. Per-program Lean inductives (strata-org/Strata#1480, closed) are not used: the SMT path's goals must equal its denotation, which is over the carrier too. Readable goals are notation added later. - This is a deep embedding with shallow goals: the program stays data, and the user sees @@ -202,7 +202,7 @@ merge. | Change | State | Used by | | --- | --- | --- | | strata-org/Strata#1498: rules `init_nondet`, `havoc`, `assume`, `assert`, and the forms of the last two that read a condition by evaluation | merged | step 1 | -| strata-org/Strata#1492: public unfolding lemmas for quantifiers and binders | approved, not merged | quantifier lifting in step 2 | +| strata-org/Strata#1492: public unfolding lemmas for quantifiers and binders | merged | quantifier lifting in step 2 | | strata-org/Strata#1493: datatypes in the SMT denotation, with the generic carrier | open, not reviewed | the SMT path now, the model of step 4 later | | strata-org/Strata#1496: `Map` and `Sequence` statements had no execution, and models did not have to satisfy their axioms | closed, fixed upstream by the denotational evaluation | step 2 | | strata-org/Strata#1490: the SMT path refuses the VCs its denotation does not cover | merged | Goal | From fbdf57b0d3bf9ba0446de87aa1071b5179cda8c7 Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Sat, 14 Nov 2026 20:12:17 +0100 Subject: [PATCH 38/64] Bump Strata to main with the open PRs; port to source locations on Core expressions Co-Authored-By: Claude Opus 5.5 --- StrataBoole/HoareLift.lean | 12 +- StrataBoole/Verify.lean | 205 +++++++++--------- .../FeatureRequests/map_extensionality.lean | 12 +- StrataBooleTest/demo.lean | 3 +- StrataBooleTest/hoare_max2.lean | 43 ++-- docs/HoareLogic.md | 4 +- lake-manifest.json | 4 +- lakefile.toml | 7 +- 8 files changed, 151 insertions(+), 139 deletions(-) diff --git a/StrataBoole/HoareLift.lean b/StrataBoole/HoareLift.lean index 0a7ba74..4e2e8cc 100644 --- a/StrataBoole/HoareLift.lean +++ b/StrataBoole/HoareLift.lean @@ -71,11 +71,13 @@ theorem boolAnd_opInterp_of_lookup {factory : Lambda.Factory CoreLParams} (model.opInterp "Bool.And" (Lambda.LSort.mkArrow .bool [.bool, .bool]) p q : Bool) = (p && q) := by have heval : (Lambda.boolAndFunc (T := CoreLParams)).func.concreteEval.bind - (fun ce => ce () [.boolConst () p, .boolConst () q]) = some (.boolConst () (p && q)) := by + (fun ce => ce Core.coreLoc (some ((Lambda.boolAndFunc (T := CoreLParams)).func.instTy Lambda.Subst.empty)) + [.boolConst Core.coreLoc p, .boolConst Core.coreLoc q]) = + some (.boolConst Core.coreLoc (p && q)) := by cases p <;> rfl exact (Core.opInterp_of_concreteEval model hlookup rfl heval (fun _ => .int) (fun _ s => @default _ (@Lambda.SortDenote.instInhabited model.tcInterp model.allInhabited s)) - (.cons .const (.cons .const .nil)) .const).symm + (.cons (.const rfl) (.cons (.const rfl) .nil)) (.const rfl)).symm theorem boolOr_opInterp_of_lookup {factory : Lambda.Factory CoreLParams} (model : Lambda.Interp factory) @@ -84,11 +86,13 @@ theorem boolOr_opInterp_of_lookup {factory : Lambda.Factory CoreLParams} (model.opInterp "Bool.Or" (Lambda.LSort.mkArrow .bool [.bool, .bool]) p q : Bool) = (p || q) := by have heval : (Lambda.boolOrFunc (T := CoreLParams)).func.concreteEval.bind - (fun ce => ce () [.boolConst () p, .boolConst () q]) = some (.boolConst () (p || q)) := by + (fun ce => ce Core.coreLoc (some ((Lambda.boolOrFunc (T := CoreLParams)).func.instTy Lambda.Subst.empty)) + [.boolConst Core.coreLoc p, .boolConst Core.coreLoc q]) = + some (.boolConst Core.coreLoc (p || q)) := by cases p <;> rfl exact (Core.opInterp_of_concreteEval model hlookup rfl heval (fun _ => .int) (fun _ s => @default _ (@Lambda.SortDenote.instInhabited model.tcInterp model.allInhabited s)) - (.cons .const (.cons .const .nil)) .const).symm + (.cons (.const rfl) (.cons (.const rfl) .nil)) (.const rfl)).symm /-! ## Their evaluation -/ diff --git a/StrataBoole/Verify.lean b/StrataBoole/Verify.lean index d0fff26..9ee82c4 100644 --- a/StrataBoole/Verify.lean +++ b/StrataBoole/Verify.lean @@ -23,6 +23,9 @@ namespace Strata.Boole open StrataDDM open Lambda +/-- Location of the Core expressions this translation builds. -/ +abbrev booleLoc : ExprSourceLoc := ExprSourceLoc.synthesized "boole" + /-- Translation state for lowering a Boole program to Core. Pipeline: `Strata.Program` → `BooleDDM.Program.ofAst` → `BooleDDM.Program` @@ -93,7 +96,7 @@ private def withTypeBVars (xs : List String) (k : TranslateM α) : TranslateM α private def withBVars (xs : List String) (k : TranslateM α) : TranslateM α := do let old := (← get).bvars - let fresh := xs.toArray.map (fun n => (.fvar () (mkIdent n) none : Core.Expression.Expr)) + let fresh := xs.toArray.map (fun n => (.fvar booleLoc (mkIdent n) none : Core.Expression.Expr)) modify fun s => { s with bvars := old ++ fresh } try let out ← k @@ -184,7 +187,7 @@ private def getBVarExpr (m : SourceRange) (i : Nat) : TranslateM Core.Expression let xs := (← get).bvars if i < xs.size then match xs[(xs.size - i - 1)]? with - | some (.bvar _ _) => return (.bvar () i) + | some (.bvar _ _) => return (.bvar booleLoc i) | some e => return e | none => throwAt m s!"Unknown bound variable with index {i}" else @@ -224,7 +227,7 @@ private def toCoreMetaData (sr : SourceRange) : TranslateM (Imperative.MetaData return Imperative.MetaData.ofSourceRange (.file file) sr private def mkCoreApp (op : Core.Expression.Expr) (args : List Core.Expression.Expr) : Core.Expression.Expr := - Lambda.LExpr.mkApp () op args + Lambda.LExpr.mkApp booleLoc op args private def typeRange : Boole.Type → SourceRange | .bvar m _ => m @@ -314,17 +317,17 @@ private def bvWidth (m : SourceRange) (ty : Boole.Type) : TranslateM Nat := private def toCoreBvUn (m : SourceRange) (ty : Boole.Type) (op : String) (a : Core.Expression.Expr) : TranslateM Core.Expression.Expr := do let n ← bvWidth m ty - return .app () (.op () ⟨s!"Bv{n}.{op}", ()⟩ none) a + return .app booleLoc (.op booleLoc ⟨s!"Bv{n}.{op}", ()⟩ none) a private def toCoreBvBin (m : SourceRange) (ty : Boole.Type) (op : String) (a b : Core.Expression.Expr) : TranslateM Core.Expression.Expr := do let n ← bvWidth m ty - return mkCoreApp (.op () ⟨s!"Bv{n}.{op}", ()⟩ none) [a, b] + return mkCoreApp (.op booleLoc ⟨s!"Bv{n}.{op}", ()⟩ none) [a, b] private def toCoreTypedUn (m : SourceRange) (ty : Boole.Type) (op : String) (a : Core.Expression.Expr) : TranslateM Core.Expression.Expr := do match ty with | .int _ => - let iop : Core.Expression.Expr := .op () ⟨s!"Int.{op}", ()⟩ none - return .app () iop a + let iop : Core.Expression.Expr := .op booleLoc ⟨s!"Int.{op}", ()⟩ none + return .app booleLoc iop a | .nat _ => throwAt m s!"'nat' does not support unary negation" | _ => toCoreBvUn m ty op a @@ -338,10 +341,10 @@ private def toBvCmpOp (op : String) : String := private def toCoreTypedBin (m : SourceRange) (ty : Boole.Type) (op : String) (a b : Core.Expression.Expr) : TranslateM Core.Expression.Expr := do match ty with | .int _ => - let iop : Core.Expression.Expr := .op () ⟨s!"Int.{op}", ()⟩ none + let iop : Core.Expression.Expr := .op booleLoc ⟨s!"Int.{op}", ()⟩ none return mkCoreApp iop [a, b] | .nat _ => - return mkCoreApp (.op () ⟨s!"nat.{op.toLower}", ()⟩ none) [a, b] + return mkCoreApp (.op booleLoc ⟨s!"nat.{op.toLower}", ()⟩ none) [a, b] | _ => toCoreBvBin m ty (toBvCmpOp op) a b private def toCoreExtensionalEq @@ -351,13 +354,13 @@ private def toCoreExtensionalEq match ty with | .Map _ _ keyTy => let keyTy' ← toCoreMonoType keyTy - let idx : Core.Expression.Expr := .bvar () 0 + let idx : Core.Expression.Expr := .bvar booleLoc 0 let a := Lambda.LExpr.liftBVars 1 a let b := Lambda.LExpr.liftBVars 1 b let lhs := mkCoreApp Core.mapSelectOp [a, idx] let rhs := mkCoreApp Core.mapSelectOp [b, idx] let trigger := lhs - return .quant () .all "" (some keyTy') trigger (.eq () lhs rhs) + return .quant booleLoc .all "" (some keyTy') trigger (.eq booleLoc lhs rhs) | _ => throwAt m s!"Extensional equality is currently only supported for Map types, got: {repr ty}" @@ -384,10 +387,10 @@ private def toCoreQuant (body : Boole.Expr) : TranslateM Core.Expression.Expr := do let decls := declListToList ds let tys ← decls.mapM fun (.bind_mk _ _ _ ty) => toCoreMonoType ty - let qBVars : Array Core.Expression.Expr := (decls.toArray.mapIdx fun i _ => .bvar () i) + let qBVars : Array Core.Expression.Expr := (decls.toArray.mapIdx fun i _ => .bvar booleLoc i) let body' ← withBVarExprs qBVars (toCoreExpr body) let q := if isForall then Lambda.QuantifierKind.all else Lambda.QuantifierKind.exist - return tys.foldr (fun ty acc => .quant () q "" (some ty) (.bvar () 0) acc) body' + return tys.foldr (fun ty acc => .quant booleLoc q "" (some ty) (.bvar booleLoc 0) acc) body' termination_by (SizeOf.sizeOf body, 4) /-- @@ -433,9 +436,9 @@ private def toCoreExpr (e : Boole.Expr) : TranslateM Core.Expression.Expr := do | .fvar m i => let id := mkIdent (← getFVarName m i) if (← getFVarIsOp m i) then - return .op () id none + return .op booleLoc id none else - return .fvar () id none + return .fvar booleLoc id none | .bvar m i => getBVarExpr m i | .let_in_expr _ _bind value body => -- Assumption: `value` contains no free variables that share names with @@ -443,27 +446,27 @@ private def toCoreExpr (e : Boole.Expr) : TranslateM Core.Expression.Expr := do -- are pure arithmetic with no name collisions. let value' ← toCoreExpr value withBVarExprs #[value'] (toCoreExpr body) - | .app _ f a => return .app () (← toCoreExpr f) (← toCoreExpr a) - | .not _ a => return .app () Core.boolNotOp (← toCoreExpr a) - | .bv1Lit _ ⟨_, n⟩ => return .bitvecConst () 1 n - | .bv8Lit _ ⟨_, n⟩ => return .bitvecConst () 8 n - | .bv16Lit _ ⟨_, n⟩ => return .bitvecConst () 16 n - | .bv32Lit _ ⟨_, n⟩ => return .bitvecConst () 32 n - | .bv64Lit _ ⟨_, n⟩ => return .bitvecConst () 64 n - | .bv128Lit _ ⟨_, n⟩ => return .bitvecConst () 128 n - | .natToInt _ ⟨_, n⟩ => return .intConst () (Int.ofNat n) - | .if _ _ c t f => return .ite () (← toCoreExpr c) (← toCoreExpr t) (← toCoreExpr f) + | .app _ f a => return .app booleLoc (← toCoreExpr f) (← toCoreExpr a) + | .not _ a => return .app booleLoc Core.boolNotOp (← toCoreExpr a) + | .bv1Lit _ ⟨_, n⟩ => return .bitvecConst booleLoc 1 n + | .bv8Lit _ ⟨_, n⟩ => return .bitvecConst booleLoc 8 n + | .bv16Lit _ ⟨_, n⟩ => return .bitvecConst booleLoc 16 n + | .bv32Lit _ ⟨_, n⟩ => return .bitvecConst booleLoc 32 n + | .bv64Lit _ ⟨_, n⟩ => return .bitvecConst booleLoc 64 n + | .bv128Lit _ ⟨_, n⟩ => return .bitvecConst booleLoc 128 n + | .natToInt _ ⟨_, n⟩ => return .intConst booleLoc (Int.ofNat n) + | .if _ _ c t f => return .ite booleLoc (← toCoreExpr c) (← toCoreExpr t) (← toCoreExpr f) | .map_get _ _ _ a i => return mkCoreApp Core.mapSelectOp [← toCoreExpr a, ← toCoreExpr i] | .map_set _ _ _ a i v => return mkCoreApp Core.mapUpdateOp [← toCoreExpr a, ← toCoreExpr i, ← toCoreExpr v] - | .btrue _ => return .true () - | .bfalse _ => return .false () + | .btrue _ => return .true booleLoc + | .bfalse _ => return .false booleLoc | .and _ a b => return mkCoreApp Core.boolAndOp [← toCoreExpr a, ← toCoreExpr b] | .or _ a b => return mkCoreApp Core.boolOrOp [← toCoreExpr a, ← toCoreExpr b] | .equiv _ a b => return mkCoreApp Core.boolEquivOp [← toCoreExpr a, ← toCoreExpr b] | .implies _ a b => return mkCoreApp Core.boolImpliesOp [← toCoreExpr a, ← toCoreExpr b] | .ext_equal m ty a b => return ← toCoreExtensionalEq m ty (← toCoreExpr a) (← toCoreExpr b) - | .equal _ _ a b => return .eq () (← toCoreExpr a) (← toCoreExpr b) - | .not_equal _ _ a b => return .app () Core.boolNotOp (.eq () (← toCoreExpr a) (← toCoreExpr b)) + | .equal _ _ a b => return .eq booleLoc (← toCoreExpr a) (← toCoreExpr b) + | .not_equal _ _ a b => return .app booleLoc Core.boolNotOp (.eq booleLoc (← toCoreExpr a) (← toCoreExpr b)) | .le m ty a b => toCoreTypedBin m ty "Le" (← toCoreExpr a) (← toCoreExpr b) | .lt m ty a b => toCoreTypedBin m ty "Lt" (← toCoreExpr a) (← toCoreExpr b) | .ge m ty a b => toCoreTypedBin m ty "Ge" (← toCoreExpr a) (← toCoreExpr b) @@ -518,12 +521,12 @@ private def toCoreExpr (e : Boole.Expr) : TranslateM Core.Expression.Expr := do -- Sequence.dropFirst(s) = drop first element -- Sequence.subrange(s,lo,hi) = take(drop(s,lo), hi-lo) | .seq_skip _ _ s n => return mkCoreApp Core.seqDropOp [← toCoreExpr s, ← toCoreExpr n] - | .seq_drop_first _ _ s => return mkCoreApp Core.seqDropOp [← toCoreExpr s, .intConst () 1] + | .seq_drop_first _ _ s => return mkCoreApp Core.seqDropOp [← toCoreExpr s, .intConst booleLoc 1] | .seq_subrange _ _ s lo hi => do let s' ← toCoreExpr s let lo' ← toCoreExpr lo let hi' ← toCoreExpr hi - let intSub : Core.Expression.Expr := .op () ⟨"Int.Sub", ()⟩ none + let intSub : Core.Expression.Expr := .op booleLoc ⟨"Int.Sub", ()⟩ none return mkCoreApp Core.seqTakeOp [mkCoreApp Core.seqDropOp [s', lo'], mkCoreApp intSub [hi', lo']] | .seq_empty_bv8 _ => return Core.seqEmptyOp (some (.bitvec 8)) @@ -547,41 +550,41 @@ private def toCoreExpr (e : Boole.Expr) : TranslateM Core.Expression.Expr := do | .lambda _ _ decls body => do let declsList := declListToList decls let tys ← declsList.mapM fun (.bind_mk _ _ _ ty) => toCoreMonoType ty - let bvars : Array Core.Expression.Expr := declsList.toArray.mapIdx fun i _ => .bvar () i + let bvars : Array Core.Expression.Expr := declsList.toArray.mapIdx fun i _ => .bvar booleLoc i let body' ← withBVarExprs bvars (toCoreExpr body) - return tys.foldr (fun ty acc => .abs () "" (some ty) acc) body' + return tys.foldr (fun ty acc => .abs booleLoc "" (some ty) acc) body' -- Function application: `(f)(x)` → Core .app - | .apply_expr _ _ _ f x => return .app () (← toCoreExpr f) (← toCoreExpr x) + | .apply_expr _ _ _ f x => return .app booleLoc (← toCoreExpr f) (← toCoreExpr x) -- Core built-in function syntax: as_uint(e), as_sint(e), as_bv{n}(e) | .as_uint m ty e => if let some n := bvWidth? ty then - return mkCoreApp (.op () (mkIdent s!"Bv{n}.ToUInt") none) [← toCoreExpr e] + return mkCoreApp (.op booleLoc (mkIdent s!"Bv{n}.ToUInt") none) [← toCoreExpr e] else match ty with | .int _ => toCoreExpr e | _ => throwAt m s!"'as_uint' requires a bitvector source type, got: {repr ty}" | .as_sint m ty e => if let some n := bvWidth? ty then - return mkCoreApp (.op () (mkIdent s!"Bv{n}.ToInt") none) [← toCoreExpr e] + return mkCoreApp (.op booleLoc (mkIdent s!"Bv{n}.ToInt") none) [← toCoreExpr e] else match ty with | .int _ => toCoreExpr e | _ => throwAt m s!"'as_sint' requires a bitvector source type, got: {repr ty}" - | .as_bv1 _ e => return mkCoreApp (.op () (mkIdent "Int.ToBv1") none) [← toCoreExpr e] - | .as_bv8 _ e => return mkCoreApp (.op () (mkIdent "Int.ToBv8") none) [← toCoreExpr e] - | .as_bv16 _ e => return mkCoreApp (.op () (mkIdent "Int.ToBv16") none) [← toCoreExpr e] - | .as_bv32 _ e => return mkCoreApp (.op () (mkIdent "Int.ToBv32") none) [← toCoreExpr e] - | .as_bv64 _ e => return mkCoreApp (.op () (mkIdent "Int.ToBv64") none) [← toCoreExpr e] - | .as_bv128 _ e => return mkCoreApp (.op () (mkIdent "Int.ToBv128") none) [← toCoreExpr e] - | .nat_toInt _ n => return mkCoreApp (.op () (mkIdent "nat.toInt") none) [← toCoreExpr n] - | .nat_fromInt _ x => return mkCoreApp (.op () (mkIdent "nat.fromInt") none) [← toCoreExpr x] - | .nat_add _ a b => return mkCoreApp (.op () (mkIdent "nat.add") none) [← toCoreExpr a, ← toCoreExpr b] - | .nat_sub _ a b => return mkCoreApp (.op () (mkIdent "nat.sub") none) [← toCoreExpr a, ← toCoreExpr b] - | .nat_mul _ a b => return mkCoreApp (.op () (mkIdent "nat.mul") none) [← toCoreExpr a, ← toCoreExpr b] - | .nat_div _ a b => return mkCoreApp (.op () (mkIdent "nat.div") none) [← toCoreExpr a, ← toCoreExpr b] - | .nat_mod _ a b => return mkCoreApp (.op () (mkIdent "nat.mod") none) [← toCoreExpr a, ← toCoreExpr b] - | .nat_lt _ a b => return mkCoreApp (.op () (mkIdent "nat.lt") none) [← toCoreExpr a, ← toCoreExpr b] - | .nat_le _ a b => return mkCoreApp (.op () (mkIdent "nat.le") none) [← toCoreExpr a, ← toCoreExpr b] - | .nat_gt _ a b => return mkCoreApp (.op () (mkIdent "nat.gt") none) [← toCoreExpr a, ← toCoreExpr b] - | .nat_ge _ a b => return mkCoreApp (.op () (mkIdent "nat.ge") none) [← toCoreExpr a, ← toCoreExpr b] + | .as_bv1 _ e => return mkCoreApp (.op booleLoc (mkIdent "Int.ToBv1") none) [← toCoreExpr e] + | .as_bv8 _ e => return mkCoreApp (.op booleLoc (mkIdent "Int.ToBv8") none) [← toCoreExpr e] + | .as_bv16 _ e => return mkCoreApp (.op booleLoc (mkIdent "Int.ToBv16") none) [← toCoreExpr e] + | .as_bv32 _ e => return mkCoreApp (.op booleLoc (mkIdent "Int.ToBv32") none) [← toCoreExpr e] + | .as_bv64 _ e => return mkCoreApp (.op booleLoc (mkIdent "Int.ToBv64") none) [← toCoreExpr e] + | .as_bv128 _ e => return mkCoreApp (.op booleLoc (mkIdent "Int.ToBv128") none) [← toCoreExpr e] + | .nat_toInt _ n => return mkCoreApp (.op booleLoc (mkIdent "nat.toInt") none) [← toCoreExpr n] + | .nat_fromInt _ x => return mkCoreApp (.op booleLoc (mkIdent "nat.fromInt") none) [← toCoreExpr x] + | .nat_add _ a b => return mkCoreApp (.op booleLoc (mkIdent "nat.add") none) [← toCoreExpr a, ← toCoreExpr b] + | .nat_sub _ a b => return mkCoreApp (.op booleLoc (mkIdent "nat.sub") none) [← toCoreExpr a, ← toCoreExpr b] + | .nat_mul _ a b => return mkCoreApp (.op booleLoc (mkIdent "nat.mul") none) [← toCoreExpr a, ← toCoreExpr b] + | .nat_div _ a b => return mkCoreApp (.op booleLoc (mkIdent "nat.div") none) [← toCoreExpr a, ← toCoreExpr b] + | .nat_mod _ a b => return mkCoreApp (.op booleLoc (mkIdent "nat.mod") none) [← toCoreExpr a, ← toCoreExpr b] + | .nat_lt _ a b => return mkCoreApp (.op booleLoc (mkIdent "nat.lt") none) [← toCoreExpr a, ← toCoreExpr b] + | .nat_le _ a b => return mkCoreApp (.op booleLoc (mkIdent "nat.le") none) [← toCoreExpr a, ← toCoreExpr b] + | .nat_gt _ a b => return mkCoreApp (.op booleLoc (mkIdent "nat.gt") none) [← toCoreExpr a, ← toCoreExpr b] + | .nat_ge _ a b => return mkCoreApp (.op booleLoc (mkIdent "nat.ge") none) [← toCoreExpr a, ← toCoreExpr b] | _ => throw (Message.fromString s!"Unsupported expression: {repr e}") termination_by (SizeOf.sizeOf e, 3) @@ -619,11 +622,11 @@ private def forArithOps (ty : Lambda.LMonoTy) : Core.Expression.Expr × Core.Expression.Expr × Core.Expression.Expr × Core.Expression.Expr := match ty with | .bitvec n => - (.op () ⟨s!"Bv{n}.ULe", ()⟩ none, - .op () ⟨s!"Bv{n}.Add", ()⟩ none, - .op () ⟨s!"Bv{n}.Sub", ()⟩ none, - .bitvecConst () n 1) - | _ => (Core.intLeOp, Core.intAddOp, Core.intSubOp, .intConst () 1) + (.op booleLoc ⟨s!"Bv{n}.ULe", ()⟩ none, + .op booleLoc ⟨s!"Bv{n}.Add", ()⟩ none, + .op booleLoc ⟨s!"Bv{n}.Sub", ()⟩ none, + .bitvecConst booleLoc n 1) + | _ => (Core.intLeOp, Core.intAddOp, Core.intSubOp, .intConst booleLoc 1) private def lowerFor (m : SourceRange) @@ -644,7 +647,7 @@ private def lowerVarStatement (m : SourceRange) (ds : BooleDDM.DeclList SourceRa let mut newBVarsRev : List Core.Expression.Expr := [] for d in declListToList ds do let (id, ty) ← toCoreBind d - newBVarsRev := (.fvar () id none : Core.Expression.Expr) :: newBVarsRev + newBVarsRev := (.fvar booleLoc id none : Core.Expression.Expr) :: newBVarsRev outRev := Core.Statement.init id ty .nondet (← toCoreMetaData m) :: outRev modify fun st => { st with bvars := st.bvars ++ newBVarsRev.reverse.toArray } return outRev.reverse @@ -683,7 +686,7 @@ private def constructProcArgsPrefix (n : String) let (modifiesTyped, readOnlyGlobals) ← getGlobalParamPrefix n let modifiesArgs := modifiesTyped.map fun (id, _) => Imperative.CallArg.inoutArg id let readOnlyArgs := readOnlyGlobals.map - fun (id, _) => Imperative.CallArg.inArg (Lambda.LExpr.fvar () id none : Core.Expression.Expr) + fun (id, _) => Imperative.CallArg.inArg (Lambda.LExpr.fvar booleLoc id none : Core.Expression.Expr) return modifiesArgs ++ readOnlyArgs /-- Returns `true` when the annotation contains a bare `@[reachCheck]` flag, @@ -708,7 +711,7 @@ private def toCoreStmt (s : BooleDDM.Statement SourceRange) : TranslateM Core.St | _ => return .block "var" out (← toCoreMetaData m) | .initStatement m _ ty ⟨_, n⟩ e => let rhs ← toCoreExpr e - modify fun st => { st with bvars := st.bvars.push (.fvar () (mkIdent n) none) } + modify fun st => { st with bvars := st.bvars.push (.fvar booleLoc (mkIdent n) none) } return Core.Statement.init (mkIdent n) (← toCoreType ty) (.det rhs) (← toCoreMetaData m) | .assign m _ _ lhs rhs => let rec lhsParts (lhs : BooleDDM.Lhs SourceRange) : TranslateM (String × List Core.Expression.Expr) := do @@ -719,7 +722,7 @@ private def toCoreStmt (s : BooleDDM.Statement SourceRange) : TranslateM Core.St return (n, (← toCoreExpr i) :: isRev) let (n, idxsRev) ← lhsParts lhs let idxs := idxsRev.reverse - let base := .fvar () (mkIdent n) none + let base := .fvar booleLoc (mkIdent n) none return Core.Statement.set (mkIdent n) (nestMapSet base idxs (← toCoreExpr rhs)) (← toCoreMetaData m) | .assume m _ ⟨_, l?⟩ e => return Core.Statement.assume (← defaultLabel m "assume" l?) (← toCoreExpr e) (← toCoreMetaData m) @@ -741,7 +744,7 @@ private def toCoreStmt (s : BooleDDM.Statement SourceRange) : TranslateM Core.St | .condNondet _ => pure .nondet return .ite cond thenb elseb (← toCoreMetaData m) | .choose_assign m ⟨_, lhs⟩ v pred => - let lhsExpr : Core.Expression.Expr := .fvar () (mkIdent lhs) none + let lhsExpr : Core.Expression.Expr := .fvar booleLoc (mkIdent lhs) none let predExpr ← withBVarExprs #[lhsExpr] (toCoreExpr pred) let md ← toCoreMetaData m let label ← defaultLabel m "choose" none @@ -751,9 +754,9 @@ private def toCoreStmt (s : BooleDDM.Statement SourceRange) : TranslateM Core.St -- obligation verify as a false positive. let .mono_bind_mk _ _ vTy := v let vMonoTy ← toCoreMonoType vTy - let existsBody ← withBVarExprs #[.bvar () 0] (toCoreExpr pred) + let existsBody ← withBVarExprs #[.bvar booleLoc 0] (toCoreExpr pred) let existsExpr : Core.Expression.Expr := - .quant () .exist "" (some vMonoTy) (.bvar () 0) existsBody + .quant booleLoc .exist "" (some vMonoTy) (.bvar booleLoc 0) existsBody let existenceAssert := Core.Statement.assert s!"{label}_exists" existsExpr md let havocStmt := Core.Statement.havoc (mkIdent lhs) md let assumeStmt := Core.Statement.assume label predExpr md @@ -811,13 +814,13 @@ private def toCoreStmt (s : BooleDDM.Statement SourceRange) : TranslateM Core.St let outputMono ← toCoreMonoType ret let k := bsList.length let paramBVars : Array Core.Expression.Expr := - bsList.toArray.mapIdx fun i _ => .bvar () (k - 1 - i) + bsList.toArray.mapIdx fun i _ => .bvar booleLoc (k - 1 - i) let bodyExpr ← withBVarExprs paramBVars (toCoreExpr body) let lambda := inputsMono.foldr - (fun (id, ty) acc => .abs () id.name (some ty) acc) bodyExpr + (fun (id, ty) acc => .abs booleLoc id.name (some ty) acc) bodyExpr let funcTy := Lambda.LMonoTy.mkArrow' outputMono (inputsMono.map (·.2)) -- Keep function name in local scope for subsequent statements. - modify fun st => { st with bvars := st.bvars.push (.fvar () (mkIdent n) (some funcTy)) } + modify fun st => { st with bvars := st.bvars.push (.fvar booleLoc (mkIdent n) (some funcTy)) } return .init (mkIdent n) (.forAll [] funcTy) (.det lambda) (← toCoreMetaData m) | .for_statement m v init guard step invs body => let (id, ty) ← toCoreMonoBind v @@ -837,7 +840,7 @@ private def toCoreStmt (s : BooleDDM.Statement SourceRange) : TranslateM Core.St let limitExpr ← toCoreExpr limit withBVars [id.name] do let initExpr ← toCoreExpr init - let guard := mkCoreApp leOp [.fvar () id none, limitExpr] + let guard := mkCoreApp leOp [.fvar booleLoc id none, limitExpr] let stepExpr ← ((match step? with | none => pure one | some (.step _ e) => toCoreExpr e) : TranslateM Core.Expression.Expr) @@ -846,7 +849,7 @@ private def toCoreStmt (s : BooleDDM.Statement SourceRange) : TranslateM Core.St | some (.measure_mk _ e) => return some (← toCoreExpr e)) let body ← withBVars [] (toCoreBlock body) lowerFor m id ty initExpr guard - (mkCoreApp addOp [.fvar () id none, stepExpr]) + (mkCoreApp addOp [.fvar booleLoc id none, stepExpr]) measureExpr (← toCoreInvariants invs) body | .for_down_to_by_statement m v init limit ⟨_, step?⟩ ⟨_, decr?⟩ invs body => let (id, ty) ← toCoreMonoBind v @@ -854,7 +857,7 @@ private def toCoreStmt (s : BooleDDM.Statement SourceRange) : TranslateM Core.St let limitExpr ← toCoreExpr limit withBVars [id.name] do let initExpr ← toCoreExpr init - let guard := mkCoreApp leOp [limitExpr, .fvar () id none] + let guard := mkCoreApp leOp [limitExpr, .fvar booleLoc id none] let stepExpr ← ((match step? with | none => pure one | some (.step _ e) => toCoreExpr e) : TranslateM Core.Expression.Expr) @@ -863,7 +866,7 @@ private def toCoreStmt (s : BooleDDM.Statement SourceRange) : TranslateM Core.St | some (.measure_mk _ e) => return some (← toCoreExpr e)) let body ← withBVars [] (toCoreBlock body) lowerFor m id ty initExpr guard - (mkCoreApp subOp [.fvar () id none, stepExpr]) + (mkCoreApp subOp [.fvar booleLoc id none, stepExpr]) measureExpr (← toCoreInvariants invs) body termination_by SizeOf.sizeOf s @@ -952,7 +955,7 @@ private def lowerPureFuncDef | .casesBinding _ _ _ => true | _ => false let pres ← withBVars inputNames (toCoreSpecElts m n pres) - let pres := pres.preconditions.map (fun (_, c) => ⟨c.expr, ()⟩) + let pres := pres.preconditions.map (fun (_, c) => ⟨c.expr, booleLoc⟩) let body ← withBVars inputNames (toCoreExpr body) let measure ← withBVars inputNames (measure?.mapM toCoreExpr) let attr := @@ -1095,23 +1098,23 @@ private def toCoreDecls (cmd : BooleDDM.Command SourceRange) : TranslateM (List -- Push n+1 passthrough bvar entries (for z=bvar0, pn=bvar1, ..., p1=bvar n) so that -- getBVarExpr doesn't throw. Passthrough entries return the original index unchanged, -- so pred's natural de Bruijn indices are preserved in both branches of the guard. - let bvarPassthroughs := Array.range (numParams + 1) |>.map (.bvar () ·) + let bvarPassthroughs := Array.range (numParams + 1) |>.map (.bvar booleLoc ·) let predCore ← withBVarExprs bvarPassthroughs (toCoreExpr pred) -- f(p1,...,pn): p1 = bvar n (outermost), p2 = bvar n-1, ..., pn = bvar 1 (innermost param) let funcCallBvar : Core.Expression.Expr := (List.range numParams).foldl (fun acc i => - .app () acc (.bvar () (numParams - i))) - (.op () (mkIdent n) none) - let zEqF : Core.Expression.Expr := .eq () (.bvar () 0) funcCallBvar + .app booleLoc acc (.bvar booleLoc (numParams - i))) + (.op booleLoc (mkIdent n) none) + let zEqF : Core.Expression.Expr := .eq booleLoc (.bvar booleLoc 0) funcCallBvar let axiomInner := mkCoreApp Core.boolImpliesOp [zEqF, predCore] -- Both branches bind their own z; parameter indices stay unchanged. let existsExpr : Core.Expression.Expr := - .quant () .exist "" (some vTy) (.bvar () 0) predCore + .quant booleLoc .exist "" (some vTy) (.bvar booleLoc 0) predCore let choiceExpr : Core.Expression.Expr := - .quant () .all "" (some vTy) (.bvar () 0) axiomInner + .quant booleLoc .all "" (some vTy) (.bvar booleLoc 0) axiomInner let guardedChoice := mkCoreApp Core.boolImpliesOp [existsExpr, choiceExpr] let axiomExpr := (inputs.map Prod.snd).foldr (fun ty acc => - .quant () .all "" (some ty) (.bvar () 0) acc) guardedChoice + .quant booleLoc .all "" (some ty) (.bvar booleLoc 0) acc) guardedChoice let axiomDecl : Core.Decl := .ax { name := s!"{n}_choose_axiom", e := axiomExpr } .empty return [funcDecl, axiomDecl] @@ -1127,7 +1130,7 @@ private def toCoreDecls (cmd : BooleDDM.Command SourceRange) : TranslateM (List | some (.measure_mk _ e) => some e | _ => none let siblingBvars := prevNames.map fun sn => - (.op () (mkIdent sn) none : Core.Expression.Expr) + (.op booleLoc (mkIdent sn) none : Core.Expression.Expr) let f ← withBVarExprs siblingBvars.toArray (lowerPureFuncDef m n tys bs ret pres body false measureExpr?) return ({ f with isRecursive := true } :: acc, prevNames ++ [n]) @@ -1310,14 +1313,14 @@ private def natCorePreamble : List Core.Decl := let natTy : LMonoTy := .tcons "nat" [] let intTy : LMonoTy := .tcons "int" [] let boolTy : LMonoTy := .tcons "bool" [] - let op' (n : String) : Core.Expression.Expr := .op () ⟨n, ()⟩ none - let fv' (n : String) : Core.Expression.Expr := .fvar () ⟨n, ()⟩ none - let int' (n : Int) : Core.Expression.Expr := .intConst () n - let app1 (f a : Core.Expression.Expr) : Core.Expression.Expr := .app () f a - let app2 (f a b : Core.Expression.Expr) : Core.Expression.Expr := .app () (.app () f a) b - let ite' (c t el : Core.Expression.Expr) : Core.Expression.Expr := .ite () c t el - let eq' (a b : Core.Expression.Expr) : Core.Expression.Expr := .eq () a b - let bv0 : Core.Expression.Expr := .bvar () 0 + let op' (n : String) : Core.Expression.Expr := .op booleLoc ⟨n, ()⟩ none + let fv' (n : String) : Core.Expression.Expr := .fvar booleLoc ⟨n, ()⟩ none + let int' (n : Int) : Core.Expression.Expr := .intConst booleLoc n + let app1 (f a : Core.Expression.Expr) : Core.Expression.Expr := .app booleLoc f a + let app2 (f a b : Core.Expression.Expr) : Core.Expression.Expr := .app booleLoc (.app booleLoc f a) b + let ite' (c t el : Core.Expression.Expr) : Core.Expression.Expr := .ite booleLoc c t el + let eq' (a b : Core.Expression.Expr) : Core.Expression.Expr := .eq booleLoc a b + let bv0 : Core.Expression.Expr := .bvar booleLoc 0 let constr (dt cname : String) (args : List (Core.Expression.Ident × LMonoTy)) : LConstr Unit := { name := ⟨cname, ()⟩, args := args, testerName := s!"{dt}..is{cname}" } let mkFunc (name : String) (inputs : List (Core.Expression.Ident × LMonoTy)) @@ -1330,7 +1333,7 @@ private def natCorePreamble : List Core.Decl := -- instead of a `define-fun` macro. Meaning comes from separate axioms. let mkFuncNoBody (name : String) (inputs : List (Core.Expression.Ident × LMonoTy)) (output : LMonoTy) - (pres : List (DL.Util.FuncPrecondition Core.Expression.Expr Unit) := []) : Core.Decl := + (pres : List (DL.Util.FuncPrecondition Core.Expression.Expr Core.ExpressionMetadata) := []) : Core.Decl := .func { name := ⟨name, ()⟩, typeArgs := [], inputs := inputs, output := output, body := none, attr := #[], axioms := [], preconditions := pres, measure := none } @@ -1396,19 +1399,19 @@ private def natCorePreamble : List Core.Decl := -- Bridge axioms let axNonneg : Core.Decl := .ax { name := "nat_nonneg" - e := .quant () .all "" (some natTy) bv0 + e := .quant booleLoc .all "" (some natTy) bv0 (app2 (op' "Int.Le") (int' 0) (app1 (op' "nat.toInt") bv0)) } .empty let axFromIntToInt : Core.Decl := .ax { name := "nat_fromInt_toInt" - e := .quant () .all "" (some intTy) bv0 + e := .quant booleLoc .all "" (some intTy) bv0 (mkCoreApp Core.boolImpliesOp [ app2 (op' "Int.Le") (int' 0) bv0 , eq' (app1 (op' "nat.toInt") (app1 (op' "nat.fromInt") bv0)) bv0 ]) } .empty let axToIntFromInt : Core.Decl := .ax { name := "nat_toInt_fromInt" - e := .quant () .all "" (some natTy) bv0 + e := .quant booleLoc .all "" (some natTy) bv0 (eq' (app1 (op' "nat.fromInt") (app1 (op' "nat.toInt") bv0)) bv0) } .empty @@ -1420,20 +1423,20 @@ private def natCorePreamble : List Core.Decl := .empty let axToIntNpos : Core.Decl := .ax { name := "nat_toInt_Npos" - e := .quant () .all "" (some posTy) bv0 + e := .quant booleLoc .all "" (some posTy) bv0 (eq' (app1 (op' "nat.toInt") (app1 (op' "Npos") bv0)) (app1 (op' "pos.toInt") bv0)) } .empty let axFromIntNonpos : Core.Decl := .ax { name := "nat_fromInt_nonpos" - e := .quant () .all "" (some intTy) bv0 + e := .quant booleLoc .all "" (some intTy) bv0 (mkCoreApp Core.boolImpliesOp [ app2 (op' "Int.Le") bv0 (int' 0) , eq' (app1 (op' "nat.fromInt") bv0) (op' "N0") ]) } .empty let axFromIntPos : Core.Decl := .ax { name := "nat_fromInt_pos" - e := .quant () .all "" (some intTy) bv0 + e := .quant booleLoc .all "" (some intTy) bv0 (mkCoreApp Core.boolImpliesOp [ app2 (op' "Int.Lt") (int' 0) bv0 , eq' (app1 (op' "nat.fromInt") bv0) @@ -1452,7 +1455,7 @@ private def natCorePreamble : List Core.Decl := -- `fromInt(toInt a toInt b)` macros: a bridge round trip per arithmetic -- node, which E-matching does not find on large terms (Strata-Boole #14). -- `bvar 1` is the outer binder (a), `bvar 0` the inner (b). - let bv1 : Core.Expression.Expr := .bvar () 1 + let bv1 : Core.Expression.Expr := .bvar booleLoc 1 let tA := app1 (op' "nat.toInt") bv1 let tB := app1 (op' "nat.toInt") bv0 let distrib (nm op intOp : String) (guard : Option Core.Expression.Expr) : Core.Decl := @@ -1460,7 +1463,7 @@ private def natCorePreamble : List Core.Decl := let body := match guard with | some g => mkCoreApp Core.boolImpliesOp [g, body] | none => body - .ax { name := nm, e := .quant () .all "" (some natTy) bv0 (.quant () .all "" (some natTy) bv0 body) } + .ax { name := nm, e := .quant booleLoc .all "" (some natTy) bv0 (.quant booleLoc .all "" (some natTy) bv0 body) } .empty let axAdd := distrib "nat_toInt_add" "nat.add" "Int.Add" none let axSub := distrib "nat_toInt_sub" "nat.sub" "Int.Sub" (some (app2 (op' "Int.Le") tB tA)) @@ -1474,7 +1477,7 @@ private def natCorePreamble : List Core.Decl := , axToIntN0, axToIntNpos, axFromIntNonpos, axFromIntPos , axNonneg, axFromIntToInt, axToIntFromInt , mkFuncNoBody "nat.add" ab natTy - , mkFuncNoBody "nat.sub" ab natTy [⟨app2 (op' "Int.Le") toIntB toIntA, ()⟩] + , mkFuncNoBody "nat.sub" ab natTy [⟨app2 (op' "Int.Le") toIntB toIntA, booleLoc⟩] , mkFuncNoBody "nat.mul" ab natTy , mkFuncNoBody "nat.div" ab natTy , mkFuncNoBody "nat.mod" ab natTy @@ -1789,9 +1792,9 @@ def verify let decodeEntry (id : Core.Expression.Ident) (e : LExpr Core.CoreLParams.mono) := match lExprToLeanNat e with - | some n => (id, LExpr.intConst () (natToInt n)) + | some n => (id, LExpr.intConst booleLoc (natToInt n)) | none => match lExprToLeanPos e with - | some p => (id, LExpr.intConst () (posToInt p)) + | some p => (id, LExpr.intConst booleLoc (posToInt p)) | none => (id, e) let decodeModel (results : Core.VCResults) : Core.VCResults := results.map fun r => diff --git a/StrataBooleTest/FeatureRequests/map_extensionality.lean b/StrataBooleTest/FeatureRequests/map_extensionality.lean index 421d3a2..308bf87 100644 --- a/StrataBooleTest/FeatureRequests/map_extensionality.lean +++ b/StrataBooleTest/FeatureRequests/map_extensionality.lean @@ -92,7 +92,7 @@ spec { private def mkExprApp (f : Core.Expression.Expr) (args : List Core.Expression.Expr) : Core.Expression.Expr := - Lambda.LExpr.mkApp () f args + Lambda.LExpr.mkApp Strata.Boole.booleLoc f args private def loweredQuantifiedMapExtensionalityCapture? : Option Core.Expression.Expr := do let booleProg <- (Strata.Boole.getProgram quantifiedMapExtensionalityCaptureSeed).toOption @@ -109,10 +109,10 @@ private def loweredQuantifiedMapExtensionalityCapture? : Option Core.Expression. private def expectedQuantifiedMapExtensionalityCapture : Core.Expression.Expr := let mapIntInt := Core.mapTy .int .int - let lhs := mkExprApp Core.mapSelectOp [.bvar () 2, .bvar () 0] - let rhs := mkExprApp Core.mapSelectOp [.bvar () 1, .bvar () 0] - .quant () .all "" (some mapIntInt) (.bvar () 0) - (.quant () .all "" (some mapIntInt) (.bvar () 0) - (.quant () .all "" (some .int) lhs (.eq () lhs rhs))) + let lhs := mkExprApp Core.mapSelectOp [.bvar Strata.Boole.booleLoc 2, .bvar Strata.Boole.booleLoc 0] + let rhs := mkExprApp Core.mapSelectOp [.bvar Strata.Boole.booleLoc 1, .bvar Strata.Boole.booleLoc 0] + .quant Strata.Boole.booleLoc .all "" (some mapIntInt) (.bvar Strata.Boole.booleLoc 0) + (.quant Strata.Boole.booleLoc .all "" (some mapIntInt) (.bvar Strata.Boole.booleLoc 0) + (.quant Strata.Boole.booleLoc .all "" (some .int) lhs (.eq Strata.Boole.booleLoc lhs rhs))) #guard loweredQuantifiedMapExtensionalityCapture? == some expectedQuantifiedMapExtensionalityCapture diff --git a/StrataBooleTest/demo.lean b/StrataBooleTest/demo.lean index 75e07d7..ce9dac3 100644 --- a/StrataBooleTest/demo.lean +++ b/StrataBooleTest/demo.lean @@ -45,7 +45,6 @@ theorem loopSimple_smtVCsCorrectBoole : smtVCsCorrectBoole loopSimple := by Lean.ofReduceBool, Lean.trustCompiler, Quot.sound, - loopSimple_smtVCsCorrectBoole._genSMTVCsBoole_tcbBridge_1_3, - Core.WFFactory._native.native_decide.ax_1✝]-/ + loopSimple_smtVCsCorrectBoole._genSMTVCsBoole_tcbBridge_1_3]-/ #guard_msgs in #print axioms loopSimple_smtVCsCorrectBoole diff --git a/StrataBooleTest/hoare_max2.lean b/StrataBooleTest/hoare_max2.lean index 07da890..1102c44 100644 --- a/StrataBooleTest/hoare_max2.lean +++ b/StrataBooleTest/hoare_max2.lean @@ -36,10 +36,16 @@ spec { }; #end -/-- The type-checked Core program the Boole block lowers to. -/ +/-- The type-checked Core program the Boole block lowers to, with every expression's + location replaced by `valueLoc`, as in Strata's own Hoare tests. Typing and + evaluation ignore locations (`Core.Expression.eval_eraseLocs`), and the shapes below + then match Strata's operator constants and do not depend on the locations the + translation attaches. -/ def max2Core : Core.Program := match Strata.Boole.typeCheck max2Pgm with - | .ok p => p + | .ok p => { p with decls := p.decls.map fun d => match d with + | .proc proc md => .proc (Core.Procedure.mapExprs Core.eraseLocs proc) md + | other => other } | .error _ => default def max2Proc : Core.Procedure := (max2Core.findProcByString? "max2").get! @@ -53,12 +59,12 @@ def yV : Core.Expression.Ident := ⟨"y", ()⟩ def rV : Core.Expression.Ident := ⟨"r", ()⟩ /-- `a >= b`, `a && b`, `a || b` as the lowering writes them. -/ -abbrev geE (a b : E) : E := .app () (.app () Core.intGeOp a) b -abbrev andE (a b : E) : E := .app () (.app () Core.boolAndOp a) b -abbrev orE (a b : E) : E := .app () (.app () Core.boolOrOp a) b +abbrev geE (a b : E) : E := .app Core.valueLoc (.app Core.valueLoc Core.intGeOp a) b +abbrev andE (a b : E) : E := .app Core.valueLoc (.app Core.valueLoc Core.boolAndOp a) b +abbrev orE (a b : E) : E := .app Core.valueLoc (.app Core.valueLoc Core.boolOrOp a) b /-- The condition of the `if`. -/ -abbrev cond : E := geE (.fvar () xV intTy) (.fvar () yV intTy) +abbrev cond : E := geE (.fvar Core.valueLoc xV intTy) (.fvar Core.valueLoc yV intTy) /-- Metadata and labels of the statements and clauses, read off the program so the shapes below are exact. -/ @@ -76,8 +82,8 @@ def md2 : Imperative.MetaData Core.Expression := theorem max2_body_eq : max2Proc.body = .structured [.block "max2" [.ite (.det cond) - [.cmd (.cmd (.set rV (.det (.fvar () xV intTy)) md1))] - [.cmd (.cmd (.set rV (.det (.fvar () yV intTy)) md2))] md3] md4] := by + [.cmd (.cmd (.set rV (.det (.fvar Core.valueLoc xV intTy)) md1))] + [.cmd (.cmd (.set rV (.det (.fvar Core.valueLoc yV intTy)) md2))] md3] md4] := by native_decide def lbl0 : Core.CoreLabel := @@ -90,11 +96,11 @@ def mdP1 : Imperative.MetaData Core.Expression := match max2Proc.spec.postconditions.toList with | _ :: (_, c) :: _ => c.md | _ => #[] theorem max2_posts : max2Proc.spec.postconditions.toList = - [(lbl0, { expr := andE (geE (.fvar () rV intTy) (.fvar () xV intTy)) - (geE (.fvar () rV intTy) (.fvar () yV intTy)), + [(lbl0, { expr := andE (geE (.fvar Core.valueLoc rV intTy) (.fvar Core.valueLoc xV intTy)) + (geE (.fvar Core.valueLoc rV intTy) (.fvar Core.valueLoc yV intTy)), attr := .Default, md := mdP0 }), - (lbl1, { expr := orE (.eq () (.fvar () rV intTy) (.fvar () xV intTy)) - (.eq () (.fvar () rV intTy) (.fvar () yV intTy)), + (lbl1, { expr := orE (.eq Core.valueLoc (.fvar Core.valueLoc rV intTy) (.fvar Core.valueLoc xV intTy)) + (.eq Core.valueLoc (.fvar Core.valueLoc rV intTy) (.fvar Core.valueLoc yV intTy)), attr := .Default, md := mdP1 })] := by native_decide @@ -109,8 +115,9 @@ theorem max2_checksTyped : Core.Logic.Hoare.Procedure.contractChecksTyped max2Pr theorem max2_factory : max2Core.factoryBeforeProcedure "max2" = Core.Factory := Core.Program.factoryBeforeProcedure_eq_core_of_noFunctions (by native_decide) -/-- Gate parameters: no reserved prefixes, every operator counts as declared. -/ -def params : Core.Logic.InitEnvWFParams := ⟨[], fun _ => true⟩ +/-- Gate parameters: no reserved prefixes for identifiers or block labels, every operator + counts as declared. -/ +def params : Core.Logic.InitEnvWFParams := ⟨[], [], fun _ => true⟩ /-! ## The values of the inputs -/ @@ -166,10 +173,10 @@ theorem max2_post (ρ : Imperative.Env Core.Expression) (a b c : Int) intro label check hmem _ rw [max2_posts] at hmem simp only [List.mem_cons, List.not_mem_nil, or_false, Prod.mk.injEq] at hmem - have er := Core.eval_fvar_int (ty := intTy) (m := ()) ρ.factory hx - have ex := Core.eval_fvar_int (ty := intTy) (m := ()) ρ.factory hx - have ey := Core.eval_fvar_int (ty := intTy) (m := ()) ρ.factory hy - have err := Core.eval_fvar_int (ty := intTy) (m := ()) ρ.factory hr + have er := Core.eval_fvar_int (ty := intTy) (m := Core.valueLoc) ρ.factory hx + have ex := Core.eval_fvar_int (ty := intTy) (m := Core.valueLoc) ρ.factory hx + have ey := Core.eval_fvar_int (ty := intTy) (m := Core.valueLoc) ρ.factory hy + have err := Core.eval_fvar_int (ty := intTy) (m := Core.valueLoc) ρ.factory hr have hge : ρ.factory.factory["Int.Ge"]? = some (Lambda.intGeFunc (T := CoreLParams)).func := by rw [hfac]; exact Core.coreFactory_intGe rcases hmem with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩ <;> intro world <;> refine Or.inl ⟨hfac, ?_⟩ <;> diff --git a/docs/HoareLogic.md b/docs/HoareLogic.md index 2ae1c91..3bc8147 100644 --- a/docs/HoareLogic.md +++ b/docs/HoareLogic.md @@ -195,8 +195,8 @@ kernel checks that proof for each program. ## Strata changes for this route -This branch pins the `integration/lean-route` branch of the fork: an earlier Strata main -plus the pull requests below. The pin returns to strata-org/Strata when the open ones +This branch pins the `integration/lean-route` branch of the fork: Strata main plus the +pull requests below that are still open. The pin returns to strata-org/Strata when they merge. | Change | State | Used by | diff --git a/lake-manifest.json b/lake-manifest.json index 56a41e2..c0b5ef2 100644 --- a/lake-manifest.json +++ b/lake-manifest.json @@ -15,10 +15,10 @@ "type": "git", "subDir": null, "scope": "", - "rev": "dcdb7f08446275cf4933615464988f262ca5881b", + "rev": "d68fdcb6e50051d511f2327f259d4e9da0dee7b4", "name": "Strata", "manifestFile": "lake-manifest.json", - "inputRev": "dcdb7f084", + "inputRev": "d68fdcb6e", "inherited": false, "configFile": "lakefile.toml"}, {"url": "https://github.com/leanprover-community/mathlib4.git", diff --git a/lakefile.toml b/lakefile.toml index 61541ea..e2a5dd0 100644 --- a/lakefile.toml +++ b/lakefile.toml @@ -9,11 +9,10 @@ weakLeanArgs = ["--tstack=32768"] name = "Strata" # On this branch Strata is the `integration/lean-route` branch of the fork: Strata main # plus the open PRs the Lean route needs (datatype denotation, checked-to-total sequence -# pass, public denote lemmas, datatypes to Lean, Hoare rules for the base commands). It -# moves back to strata-org/Strata when they merge. A fixed commit, not a branch name, so -# `lake update` cannot move it. +# pass). It moves back to strata-org/Strata when they merge. A fixed commit, not a branch +# name, so `lake update` cannot move it. git = "https://github.com/kondylidou/Strata" -rev = "dcdb7f084" +rev = "d68fdcb6e" [[require]] name = "smt" From f3ae8405490937e929baea4bf6ceed60f1b57878 Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:29:14 +0100 Subject: [PATCH 39/64] Bring the dalek sum_of_slice benchmark to this branch, solver path only --- StrataBooleTest.lean | 1 + StrataBooleTest/dalek_sum_of_slice.lean | 332 ++++++++++++++++++++++++ docs/HoareLogic.md | 10 +- 3 files changed, 339 insertions(+), 4 deletions(-) create mode 100644 StrataBooleTest/dalek_sum_of_slice.lean diff --git a/StrataBooleTest.lean b/StrataBooleTest.lean index c6744bd..f87259f 100644 --- a/StrataBooleTest.lean +++ b/StrataBooleTest.lean @@ -63,4 +63,5 @@ import StrataBooleTest.FeatureRequests.sha256_compact_indexed import StrataBooleTest.CoreTests.DefineFunRecTests import StrataBooleTest.shallow_find_max import StrataBooleTest.hoare_max2 +import StrataBooleTest.dalek_sum_of_slice import StrataBooleTest.generic_datatypes diff --git a/StrataBooleTest/dalek_sum_of_slice.lean b/StrataBooleTest/dalek_sum_of_slice.lean new file mode 100644 index 0000000..5381bd9 --- /dev/null +++ b/StrataBooleTest/dalek_sum_of_slice.lean @@ -0,0 +1,332 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ + +import StrataBoole.MetaVerifier + +open Strata + +/- +`sum_of_slice` from dalek-lite: Verus to Boole to cvc5. +Generated by `verus-boole/dalek/rust_to_boole.sh`; do not edit. On this branch it is the +target of the Lean route of `docs/HoareLogic.md`, which will prove the same contracts +against Core's Hoare logic; the kernel stage of the demo branch is not carried over. + +Level 1: the Verus source. + + /// Compute the sum of all scalars in a slice. + /// + /// # Returns + /// + /// The sum of all scalars modulo the group order. + /// + /// # Example + /// + /// ``` + /// # use curve25519_dalek::scalar::Scalar; + /// let scalars = [ + /// Scalar::from(2u64), + /// Scalar::from(3u64), + /// Scalar::from(5u64), + /// ]; + /// + /// let sum = Scalar::sum_of_slice(&scalars); + /// assert_eq!(sum, Scalar::from(10u64)); + /// ``` + #[allow(clippy::needless_range_loop, clippy::op_ref)] + pub fn sum_of_slice(scalars: &[Scalar]) -> (result: Scalar) + requires + forall|i: int| #![auto] 0 <= i < scalars@.len() ==> is_canonical_scalar(&scalars@[i]), + ensures + scalar_as_nat(&result) < group_order(), + is_canonical_scalar(&result), + scalar_congruent_nat(&result, sum_of_scalars(scalars@)), + { + let n = scalars.len(); + let mut acc = Scalar::ZERO; + + proof { + lemma_scalar_zero_properties(); + assert(scalars@.subrange(0, 0) =~= Seq::::empty()); + } + + for i in 0..n + invariant + n == scalars.len(), + forall|j: int| + #![auto] + 0 <= j < scalars@.len() ==> is_canonical_scalar(&scalars@[j]), + scalar_as_nat(&acc) < group_order(), + is_canonical_scalar(&acc), + scalar_congruent_nat(&acc, sum_of_scalars(scalars@.subrange(0, i as int))), + { + let _old_acc = acc; + + proof { + // Inline: sum extends by one element + let sub = scalars@.subrange(0, (i + 1) as int); + assert(sub.subrange(0, i as int) =~= scalars@.subrange(0, i as int)); + } + + acc = &acc + &scalars[i]; + + proof { + let L = group_order(); + let acc_val = u8_32_as_nat(&acc.bytes); + let old_acc_val = u8_32_as_nat(&_old_acc.bytes); + let scalar_val = u8_32_as_nat(&scalars[i as int].bytes); + let sum_prev = sum_of_scalars(scalars@.subrange(0, i as int)); + + lemma_mod_bound(old_acc_val as int + scalar_val as int, L as int); + lemma_add_mod_noop(old_acc_val as int, scalar_val as int, L as int); + lemma_add_mod_noop(sum_prev as int, scalar_val as int, L as int); + lemma_mod_twice(sum_prev as int + scalar_val as int, L as int); + } + } + + proof { + assert(scalars@.subrange(0, n as int) =~= scalars@); + } + + acc + } +-/ + +-- Level 2: the Boole program, checked by cvc5. +private def sumofsliceTranslatedSeed : StrataDDM.Program := +#strata +program Boole; +type Scalar := Sequence (bv W8); +function u8_32_as_nat (bytes : Sequence (bv W8)) : nat { + nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_add(nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 0))), nat_fromInt(1)), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 1))), nat_fromInt(256))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 2))), nat_fromInt(65536))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 3))), nat_fromInt(16777216))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 4))), nat_fromInt(4294967296))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 5))), nat_fromInt(1099511627776))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 6))), nat_fromInt(281474976710656))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 7))), nat_fromInt(72057594037927936))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 8))), nat_fromInt(18446744073709551616))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 9))), nat_fromInt(4722366482869645213696))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 10))), nat_fromInt(1208925819614629174706176))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 11))), nat_fromInt(309485009821345068724781056))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 12))), nat_fromInt(79228162514264337593543950336))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 13))), nat_fromInt(20282409603651670423947251286016))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 14))), nat_fromInt(5192296858534827628530496329220096))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 15))), nat_fromInt(1329227995784915872903807060280344576))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 16))), nat_fromInt(340282366920938463463374607431768211456))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 17))), nat_fromInt(87112285931760246646623899502532662132736))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 18))), nat_fromInt(22300745198530623141535718272648361505980416))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 19))), nat_fromInt(5708990770823839524233143877797980545530986496))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 20))), nat_fromInt(1461501637330902918203684832716283019655932542976))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 21))), nat_fromInt(374144419156711147060143317175368453031918731001856))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 22))), nat_fromInt(95780971304118053647396689196894323976171195136475136))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 23))), nat_fromInt(24519928653854221733733552434404946937899825954937634816))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 24))), nat_fromInt(6277101735386680763835789423207666416102355444464034512896))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 25))), nat_fromInt(1606938044258990275541962092341162602522202993782792835301376))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 26))), nat_fromInt(411376139330301510538742295639337626245683966408394965837152256))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 27))), nat_fromInt(105312291668557186697918027683670432318895095400549111254310977536))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 28))), nat_fromInt(26959946667150639794667015087019630673637144422540572481103610249216))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 29))), nat_fromInt(6901746346790563787434755862277025452451108972170386555162524223799296))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 30))), nat_fromInt(1766847064778384329583297500742918515827483896875618958121606201292619776))), nat_mul(nat_fromInt(as_uint(Sequence.select!(bytes, 31))), nat_fromInt(452312848583266388373324160190187140051835877600158453279131187530910662656))) +} +function group_order () : nat { + nat_fromInt(7237005577332262213973186563042994240857116359379907606001950938285454250989) +} +function is_canonical_scalar (s : Scalar) : bool { + nat_lt(u8_32_as_nat(s), group_order) && Sequence.select!(s, 31) <= bv{8}(127) +} +function scalar_as_nat (s : Scalar) : nat { + u8_32_as_nat(s) +} +function group_canonical (n : nat) : nat { + nat_mod(n, group_order) +} +function u8_32_as_group_canonical (bytes : Sequence (bv W8)) : nat { + group_canonical(u8_32_as_nat(bytes)) +} +function scalar_as_canonical (s : Scalar) : nat { + u8_32_as_group_canonical(s) +} +rec function sum_of_scalars (scalars : Sequence Scalar, n : nat) : nat + requires nat_toInt(n) <= Sequence.length(scalars); + decreases nat_toInt(n) +{ + if nat_toInt(n) == 0 then nat_fromInt(0) else group_canonical(nat_add(sum_of_scalars(scalars, nat_fromInt(nat_toInt(n) - 1)), scalar_as_nat(Sequence.select(scalars, nat_toInt(n) - 1)))) +}; +axiom [sum_of_scalars_unfold]: ∀ scalars : (Sequence Scalar), n : nat :: nat_toInt(n) <= Sequence.length(scalars) ==> sum_of_scalars(scalars, n) == (if nat_toInt(n) == 0 then nat_fromInt(0) else group_canonical(nat_add(sum_of_scalars(scalars, nat_fromInt(nat_toInt(n) - 1)), scalar_as_nat(Sequence.select(scalars, nat_toInt(n) - 1))))); +function scalar_congruent_nat (s : Scalar, n : nat) : bool { + nat_toInt(scalar_as_canonical(s)) == nat_toInt(group_canonical(n)) +} +function Scalar_obeys_add_spec () : bool { + false +} +function Scalar_add_req (self : Scalar, rhs : Scalar) : bool { + is_canonical_scalar(self) && is_canonical_scalar(rhs) +} +function Scalar_add_spec (self : Scalar, rhs : Scalar) : Scalar; +function Scalar_ZERO () : Scalar; +axiom [Scalar_ZERO_lit_0]: Sequence.length(Scalar_ZERO) == 32; +axiom [Scalar_ZERO_lit_1]: ∀ k : int :: 0 <= k && k < 32 ==> Sequence.select!(Scalar_ZERO, k) == bv{8}(0); +axiom [lemma_scalar_zero_properties_ensures_0]: nat_toInt(scalar_as_nat(Scalar_ZERO)) == 0; +axiom [lemma_scalar_zero_properties_ensures_1]: nat_lt(scalar_as_nat(Scalar_ZERO), group_order); +axiom [lemma_scalar_zero_properties_ensures_2]: is_canonical_scalar(Scalar_ZERO); +axiom [lemma_scalar_zero_properties_ensures_3]: scalar_congruent_nat(Scalar_ZERO, nat_fromInt(0)); +procedure Scalar_add (self : Scalar, _rhs : Scalar) returns (result : Scalar) +spec { + requires Scalar_add_req(self, _rhs); + ensures Scalar_obeys_add_spec ==> result == Scalar_add_spec(self, _rhs); + ensures nat_toInt(scalar_as_nat(result)) == nat_toInt(group_canonical(nat_add(scalar_as_nat(self), scalar_as_nat(_rhs)))); + ensures is_canonical_scalar(result); +} +{ + assume false; +}; +procedure sum_of_slice (scalars : Sequence Scalar) returns (result : Scalar) +spec { + requires ∀ i : int :: 0 <= i && i < Sequence.length(scalars) ==> is_canonical_scalar(Sequence.select(scalars, i)); + ensures nat_lt(scalar_as_nat(result), group_order); + ensures is_canonical_scalar(result); + ensures scalar_congruent_nat(result, sum_of_scalars(scalars, nat_fromInt(Sequence.length(scalars)))); +} +{ + var n : int; + var acc : Scalar; + assume Sequence.length(scalars) <= 18446744073709551615; + n := Sequence.length(scalars); + acc := Scalar_ZERO; + for i : int := 0 to Sequence.length(scalars) - 1 + invariant 0 <= i && i <= Sequence.length(scalars) + invariant n == Sequence.length(scalars) + invariant ∀ j : int :: 0 <= j && j < Sequence.length(scalars) ==> is_canonical_scalar(Sequence.select(scalars, j)) + invariant nat_lt(scalar_as_nat(acc), group_order) + invariant is_canonical_scalar(acc) + invariant nat_toInt(scalar_as_nat(acc)) == nat_toInt(sum_of_scalars(scalars, nat_fromInt(i))) + { + call acc := Scalar_add(acc, Sequence.select(scalars, i)); + } + result := acc; + exit sum_of_slice; +}; +#end + +/-- info: +Obligation: pos.toInt_terminates_0 +Property: assert +Result: ✅ pass + +Obligation: pos.toInt_terminates_1 +Property: assert +Result: ✅ pass + +Obligation: pos.toInt_body_calls_pos..xO_h_0 +Property: assert +Result: ✅ pass + +Obligation: pos.toInt_body_calls_pos..xI_h_1 +Property: assert +Result: ✅ pass + +Obligation: pos.fromInt_terminates_0 +Property: assert +Result: ✅ pass + +Obligation: pos.fromInt_terminates_1 +Property: assert +Result: ✅ pass + +Obligation: pos.fromInt_terminates_2 +Property: assert +Result: ✅ pass + +Obligation: pos.fromInt_terminates_3 +Property: assert +Result: ✅ pass + +Obligation: sum_of_scalars_terminates_0 +Property: assert +Result: ✅ pass + +Obligation: sum_of_scalars_terminates_1 +Property: assert +Result: ✅ pass + +Obligation: sum_of_scalars_body_calls_sum_of_scalars_0 +Property: assert +Result: ✅ pass + +Obligation: sum_of_scalars_body_calls_Sequence.select_1 +Property: out-of-bounds access check +Result: ✅ pass + +Obligation: Scalar_add_ensures_2_9437 +Property: assert +Result: ✅ pass + +Obligation: Scalar_add_ensures_3_9512 +Property: assert +Result: ✅ pass + +Obligation: Scalar_add_ensures_4_9637 +Property: assert +Result: ✅ pass + +Obligation: sum_of_slice_pre_sum_of_slice_requires_6_9783_calls_Sequence.select_0 +Property: out-of-bounds access check +Result: ✅ pass + +Obligation: sum_of_slice_post_sum_of_slice_ensures_9_9995_calls_sum_of_scalars_0 +Property: assert +Result: ✅ pass + +Obligation: loop_invariant_calls_Sequence.select_0 +Property: out-of-bounds access check +Result: ✅ pass + +Obligation: loop_invariant_calls_sum_of_scalars_0 +Property: assert +Result: ✅ pass + +Obligation: insertLoopInvAssert_entry_invariant_loop_7_0 +Property: assert +Result: ✅ pass + +Obligation: insertLoopInvAssert_entry_invariant_loop_7_1 +Property: assert +Result: ✅ pass + +Obligation: insertLoopInvAssert_entry_invariant_loop_7_2 +Property: assert +Result: ✅ pass + +Obligation: insertLoopInvAssert_entry_invariant_loop_7_3 +Property: assert +Result: ✅ pass + +Obligation: insertLoopInvAssert_entry_invariant_loop_7_4 +Property: assert +Result: ✅ pass + +Obligation: insertLoopInvAssert_entry_invariant_loop_7_5 +Property: assert +Result: ✅ pass + +Obligation: init_calls_Sequence.select_0 +Property: out-of-bounds access check +Result: ✅ pass + +Obligation: callElimAssert_Scalar_add_requires_1_9398_3 +Property: assert +Result: ✅ pass + +Obligation: insertLoopInvAssert_arbitrary_iter_maintain_invariant_loop_7_0 +Property: assert +Result: ✅ pass + +Obligation: insertLoopInvAssert_arbitrary_iter_maintain_invariant_loop_7_1 +Property: assert +Result: ✅ pass + +Obligation: insertLoopInvAssert_arbitrary_iter_maintain_invariant_loop_7_2 +Property: assert +Result: ✅ pass + +Obligation: insertLoopInvAssert_arbitrary_iter_maintain_invariant_loop_7_3 +Property: assert +Result: ✅ pass + +Obligation: insertLoopInvAssert_arbitrary_iter_maintain_invariant_loop_7_4 +Property: assert +Result: ✅ pass + +Obligation: insertLoopInvAssert_arbitrary_iter_maintain_invariant_loop_7_5 +Property: assert +Result: ✅ pass + +Obligation: sum_of_slice_ensures_7_9902 +Property: assert +Result: ✅ pass + +Obligation: sum_of_slice_ensures_8_9956 +Property: assert +Result: ✅ pass + +Obligation: sum_of_slice_ensures_9_9995 +Property: assert +Result: ✅ pass +-/ +#guard_msgs in +#eval Strata.Boole.verify "cvc5" sumofsliceTranslatedSeed + (options := { Core.VerifyOptions.quiet with solverTimeout := 30 }) diff --git a/docs/HoareLogic.md b/docs/HoareLogic.md index 3bc8147..9d08481 100644 --- a/docs/HoareLogic.md +++ b/docs/HoareLogic.md @@ -140,10 +140,12 @@ then the benchmark below. ## Target: `dalek_sum_of_slice` -`StrataBooleTest/dalek_sum_of_slice.lean` (branch `demo/dalek-sum-of-slice`, 36 -obligations on the solver path) is the program this route has to reach. On the current -Strata it type checks, both contracts pass `contractChecksTyped`, and caller and callee -see the same factory, as `call_of_contract` requires. +`StrataBooleTest/dalek_sum_of_slice.lean` is the program this route has to reach. On this +branch it is checked on the solver path only, with all 36 obligations passing as on the +frozen demo branch; the demo's kernel stage relied on the trusted bridge of +`gen_smt_vcs_boole` and is not carried over. On the current Strata it type checks, both +contracts pass `contractChecksTyped`, and caller and callee see the same factory, as +`call_of_contract` requires. | It uses | Step | | --- | --- | From 5ea2977bb29d2a7c81ff95566d08224b144a7d65 Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:27:11 +0100 Subject: [PATCH 40/64] Remove the Std.Do prototype and its test; the Hoare route does not build on it The prototype layer and its hand-written examples are off the path of docs/HoareLogic.md. The docs no longer point at them, and the onboarding note describes the Hoare route instead of a shallow embedding. Co-Authored-By: Claude Fable 5.2 --- StrataBoole.lean | 6 - StrataBoole/Shallow/Layer.lean | 177 -------------------------- StrataBooleTest.lean | 1 - StrataBooleTest/shallow_find_max.lean | 112 ---------------- docs/HoareLogic.md | 8 +- docs/onboarding.md | 9 +- 6 files changed, 8 insertions(+), 305 deletions(-) delete mode 100644 StrataBoole/Shallow/Layer.lean delete mode 100644 StrataBooleTest/shallow_find_max.lean diff --git a/StrataBoole.lean b/StrataBoole.lean index 3386c4f..fd8ba41 100644 --- a/StrataBoole.lean +++ b/StrataBoole.lean @@ -30,12 +30,6 @@ dialect of Strata. `Strata.BooleNat.prepend`. The implementation is `natCorePreamble` in `StrataBoole/Verify.lean`; nothing imports this module. `lake build StrataBoole.Nat`. -### `import StrataBoole.Shallow.Layer` - -A shallow-embedding prototype on `Std.Do`: the `ND` monad with `havoc`, -`assume`, `assert` and `whileInv`, each with its `@[spec]` rule for `mvcgen`. -The Hoare-logic route in `docs/HoareLogic.md` does not build on it. - ### `import StrataBoole.MetaVerifier` The `gen_smt_vcs_boole` tactic and `Strata.smtVCsCorrectBoole` are available diff --git a/StrataBoole/Shallow/Layer.lean b/StrataBoole/Shallow/Layer.lean deleted file mode 100644 index 1741e57..0000000 --- a/StrataBoole/Shallow/Layer.lean +++ /dev/null @@ -1,177 +0,0 @@ -/- - Copyright Strata Contributors - - SPDX-License-Identifier: Apache-2.0 OR MIT --/ -module - -public import Std.Do -public import Std.Tactic.Do - -/-! # The shallow embedding's layer on `Std.Do` - -What a Core program needs beyond Lean's `do` notation and `mvcgen`: a -nondeterministic monad with `havoc`, `assume` and `assert`, and a `while` loop -whose invariant is part of the program. Each construct comes with its proof -rule (`@[spec]`), so `mvcgen` generates the verification conditions. - -The design follows Velvet (verse-lab/velvet); the code is ours and runs on the -Lean version Strata is on. It is a prototype: the Hoare-logic route in -`docs/HoareLogic.md` does not build on it. --/ - -public section - -namespace Strata.Shallow - -open Std.Do - -/-- A nondeterministic computation is its set of outcomes; `none` is a failed `assert`. -/ -structure ND (α : Type) where - run : Option α → Prop - -namespace ND - -theorem ext {x y : ND α} (h : ∀ r, x.run r ↔ y.run r) : x = y := by - cases x; cases y; congr; funext r; exact propext (h r) - -instance : Monad ND where - pure a := ⟨fun r => r = some a⟩ - bind x f := ⟨fun r => (∃ a, x.run (some a) ∧ (f a).run r) ∨ (x.run none ∧ r = none)⟩ - -theorem run_pure (a : α) (r : Option α) : (pure a : ND α).run r ↔ r = some a := Iff.rfl - -theorem run_bind (x : ND α) (f : α → ND β) (r : Option β) : - (x >>= f).run r ↔ (∃ a, x.run (some a) ∧ (f a).run r) ∨ (x.run none ∧ r = none) := Iff.rfl - -instance : LawfulMonad ND := LawfulMonad.mk' ND - (id_map := by - intro α x; apply ext; intro r - show (x >>= fun a => pure (id a)).run r ↔ _ - simp only [run_bind, run_pure, id] - cases r <;> simp) - (pure_bind := by - intro α β a f; apply ext; intro r - simp [run_bind, run_pure]) - (bind_assoc := by - intro α β γ x f g; apply ext; intro r - simp only [run_bind] - constructor - · rintro (⟨b, (⟨a, hx, hf⟩ | ⟨hx, hb⟩), hg⟩ | ⟨(⟨a, hx, hf⟩ | ⟨hx, -⟩), rfl⟩) - · exact .inl ⟨a, hx, .inl ⟨b, hf, hg⟩⟩ - · cases hb - · exact .inl ⟨a, hx, .inr ⟨hf, rfl⟩⟩ - · exact .inr ⟨hx, by simp⟩ - · rintro (⟨a, hx, (⟨b, hf, hg⟩ | ⟨hf, rfl⟩)⟩ | ⟨hx, rfl⟩) - · exact .inl ⟨b, .inl ⟨a, hx, hf⟩, hg⟩ - · exact .inr ⟨.inl ⟨a, hx, hf⟩, rfl⟩ - · exact .inr ⟨.inr ⟨hx, by simp⟩, rfl⟩) - -/-- Every outcome is a value satisfying the postcondition (partial correctness). -/ -def wpTrans (x : ND α) : PredTrans .pure α where - trans Q := ⌜∀ r, x.run r → ∃ a, r = some a ∧ (Q.1 a).down⌝ - conjunctiveRaw := by - intro Q₁ Q₂ - simp only [SPred.bientails_nil, SPred.and_nil, SPred.down_pure] - constructor - · intro h - exact ⟨fun r hr => let ⟨a, e, h1, _⟩ := h r hr; ⟨a, e, h1⟩, - fun r hr => let ⟨a, e, _, h2⟩ := h r hr; ⟨a, e, h2⟩⟩ - · rintro ⟨h1, h2⟩ r hr - obtain ⟨a, rfl, ha⟩ := h1 r hr - obtain ⟨b, hb, hb2⟩ := h2 _ hr - cases hb - exact ⟨a, rfl, ha, hb2⟩ - -instance : WP ND .pure := ⟨wpTrans⟩ - -theorem wp_apply (x : ND α) (Q : PostCond α .pure) : - (wp⟦x⟧ Q).down ↔ ∀ r, x.run r → ∃ a, r = some a ∧ (Q.1 a).down := Iff.rfl - -private theorem spred_ext {P Q : SPred []} (h : P.down ↔ Q.down) : P = Q := by - show ULift.up P.down = ULift.up Q.down - rw [propext h] - -instance : WPMonad ND .pure where - wp_pure a := by - apply PredTrans.ext; intro Q - apply spred_ext - rw [wp_apply] - simp [run_pure] - wp_bind x f := by - apply PredTrans.ext; intro Q - apply spred_ext - rw [wp_apply] - simp only [PredTrans.apply_Bind_bind, run_bind] - show _ ↔ ∀ r, x.run r → ∃ a, r = some a ∧ ∀ r', (f a).run r' → ∃ b, r' = some b ∧ (Q.1 b).down - constructor - · intro h r hr - cases r with - | none => exact absurd (h none (.inr ⟨hr, rfl⟩)) (by simp) - | some a => exact ⟨a, rfl, fun r' hr' => h r' (.inl ⟨a, hr, hr'⟩)⟩ - · rintro h r (⟨a, hx, hf⟩ | ⟨hx, rfl⟩) - · obtain ⟨a', ha', h'⟩ := h _ hx - cases ha' - exact h' r hf - · obtain ⟨a', ha', -⟩ := h _ hx - cases ha' - -/-! Statements Lean has no counterpart for. -/ - -/-- `havoc`: any value. -/ -def havoc : ND α := ⟨fun r => ∃ a, r = some a⟩ - -/-- `assume p`: executions where `p` fails do not exist. -/ -def assume (p : Prop) : ND Unit := ⟨fun r => p ∧ r = some ()⟩ - -/-- `assert p`: fails when `p` does not hold. -/ -def assert (p : Prop) : ND Unit := ⟨fun r => (p ∧ r = some ()) ∨ (¬ p ∧ r = none)⟩ - -/-- Executions of `while c do body` from a state: the least relation closed under the -loop's steps, so a diverging run has no outcome (partial correctness). -/ -inductive WhileRel (c : β → Prop) (body : β → ND β) : β → Option β → Prop - | done {s} : ¬ c s → WhileRel c body s (some s) - | step {s s' r} : c s → (body s).run (some s') → WhileRel c body s' r → WhileRel c body s r - | fail {s} : c s → (body s).run none → WhileRel c body s none - -/-- A `while` loop on the state `β`. The invariant is an annotation; it does not affect -what the loop does. -/ -def whileInv (_inv : β → Prop) (c : β → Prop) (body : β → ND β) (init : β) : ND β := - ⟨WhileRel c body init⟩ - -theorem triple_iff {x : ND α} {P : Prop} {Q : α → Prop} : - ⦃⌜P⌝⦄ x ⦃⇓ a => ⌜Q a⌝⦄ ↔ (P → ∀ r, x.run r → ∃ a, r = some a ∧ Q a) := Iff.rfl - -@[spec] theorem havoc_spec : ⦃⌜True⌝⦄ (havoc : ND α) ⦃⇓ _ => ⌜True⌝⦄ := by - rw [triple_iff]; rintro - r ⟨a, rfl⟩; exact ⟨a, rfl, trivial⟩ - -@[spec] theorem assume_spec (p : Prop) : ⦃⌜True⌝⦄ assume p ⦃⇓ _ => ⌜p⌝⦄ := by - rw [triple_iff]; rintro - r ⟨hp, rfl⟩; exact ⟨(), rfl, hp⟩ - -@[spec] theorem assert_spec (p : Prop) : ⦃⌜p⌝⦄ assert p ⦃⇓ _ => ⌜p⌝⦄ := by - rw [triple_iff]; rintro hp r (⟨-, rfl⟩ | ⟨hn, -⟩) - · exact ⟨(), rfl, hp⟩ - · exact absurd hp hn - -/-- The invariant rule: if the body preserves the invariant, the loop ends with the -invariant and the negated condition. -/ -@[spec] theorem whileInv_spec (inv c : β → Prop) (body : β → ND β) (init : β) - (step : ∀ s, ⦃⌜inv s ∧ c s⌝⦄ body s ⦃⇓ s' => ⌜inv s'⌝⦄) : - ⦃⌜inv init⌝⦄ whileInv inv c body init ⦃⇓ s => ⌜inv s ∧ ¬ c s⌝⦄ := by - rw [triple_iff] - intro hinit r hr - induction hr with - | done hc => exact ⟨_, rfl, hinit, hc⟩ - | step hc hb _ ih => - obtain ⟨s'', hs, hinv⟩ := triple_iff.mp (step _) ⟨hinit, hc⟩ _ hb - cases hs - exact ih hinv - | fail hc hb => - obtain ⟨s'', hs, -⟩ := triple_iff.mp (step _) ⟨hinit, hc⟩ _ hb - cases hs - -end ND - -end Strata.Shallow - -end diff --git a/StrataBooleTest.lean b/StrataBooleTest.lean index f87259f..b51c339 100644 --- a/StrataBooleTest.lean +++ b/StrataBooleTest.lean @@ -61,7 +61,6 @@ import StrataBooleTest.FeatureRequests.scalar_reduce import StrataBooleTest.FeatureRequests.seq_empty_literal import StrataBooleTest.FeatureRequests.sha256_compact_indexed import StrataBooleTest.CoreTests.DefineFunRecTests -import StrataBooleTest.shallow_find_max import StrataBooleTest.hoare_max2 import StrataBooleTest.dalek_sum_of_slice import StrataBooleTest.generic_datatypes diff --git a/StrataBooleTest/shallow_find_max.lean b/StrataBooleTest/shallow_find_max.lean deleted file mode 100644 index d28238c..0000000 --- a/StrataBooleTest/shallow_find_max.lean +++ /dev/null @@ -1,112 +0,0 @@ -/- - Copyright Strata Contributors - - SPDX-License-Identifier: Apache-2.0 OR MIT --/ -import StrataBoole.Shallow.Layer - -/-! Three programs, written by hand in the form the translation from Core -should produce, verified with `mvcgen` on the layer. This file is the -contract between the translation and the layer. -/ - --- Lean marks `mvcgen` experimental; see docs/HoareLogic.md. -set_option mvcgen.warning false - -namespace Strata.Shallow.Test - -open Std.Do Strata.Shallow Strata.Shallow.ND - -/-- `havoc x; assume x >= 0`. -/ -def pick_nat : ND Int := do - let x ← havoc - assume (x ≥ 0) - return x - -theorem pick_nat_spec : ⦃⌜True⌝⦄ pick_nat ⦃⇓ x => ⌜x ≥ 0⌝⦄ := by - mvcgen [pick_nat] - -/-- A loop without a termination measure. State: `(i, r)`. -/ -def sum_to (n : Int) : ND Int := do - let s ← whileInv - (fun s : Int × Int => 0 ≤ s.1 ∧ s.1 ≤ n ∧ 2 * s.2 = s.1 * (s.1 + 1)) - (fun s => s.1 < n) - (fun s => pure (s.1 + 1, s.2 + (s.1 + 1))) - (0, 0) - return s.2 - -theorem sum_to_spec (n : Int) (h : n ≥ 0) : - ⦃⌜True⌝⦄ sum_to n ⦃⇓ r => ⌜2 * r = n * (n + 1)⌝⦄ := by - mvcgen [sum_to] - all_goals grind - -/-- Find max, from the Verus translator's Boole output. State: `(max, i)`. -/ -def find_max (nums : Array (BitVec 32)) : ND (BitVec 32) := do - ND.assert (0 < nums.size) - let s ← whileInv - (fun s : BitVec 32 × Int => - (∃ j : Int, 0 ≤ j ∧ j < s.2 ∧ s.1 = nums[j.toNat]!) ∧ - (∀ k : Int, 0 ≤ k ∧ k < s.2 → BitVec.sle nums[k.toNat]! s.1) ∧ - 0 ≤ s.2 ∧ s.2 ≤ nums.size) - (fun s => s.2 < nums.size) - (fun s => do - ND.assert (0 ≤ s.2 ∧ s.2 < nums.size) - let max := if BitVec.slt s.1 nums[s.2.toNat]! then nums[s.2.toNat]! else s.1 - ND.assert (0 ≤ s.2 + 1 ∧ s.2 + 1 ≤ 18446744073709551615) - pure (max, (s.2 + 1) % 18446744073709551616)) - (nums[0]!, 1) - return s.1 - -theorem find_max_spec (nums : Array (BitVec 32)) : - ⦃⌜nums.size > 0 ∧ (nums.size : Int) ≤ 18446744073709551615⌝⦄ - find_max nums - ⦃⇓ ret => ⌜(∀ i : Int, 0 ≤ i ∧ i < nums.size → BitVec.sle nums[i.toNat]! ret) ∧ - (∃ j : Int, 0 ≤ j ∧ j < nums.size ∧ ret = nums[j.toNat]!)⌝⦄ := by - mvcgen [find_max] - all_goals (try simp only [BitVec.sle_iff_toInt_le] at *) - all_goals (try grind) - -- One iteration: the invariant holds again. - · rename_i hpre _ h0 s _ max hb _ hov hinv - obtain ⟨⟨⟨j, hj0, hji, hmax⟩, habove, hi0, hin⟩, hlt⟩ := hinv - have hmaxdef : max = if s.1.slt nums[s.2.toNat]! = true then nums[s.2.toNat]! else s.1 := rfl - clear_value max - subst hmaxdef - rw [Int.emod_eq_of_lt (by omega) (by omega)] - refine ⟨?_, ?_, by omega, by omega⟩ - · split - · exact ⟨s.2, by omega, by omega, rfl⟩ - · exact ⟨j, hj0, by omega, hmax⟩ - · intro k hk0 hk - split - · next hslt => - rw [BitVec.slt_iff_toInt_lt] at hslt - by_cases hki : k < s.2 - · have := habove k hk0 hki - omega - · obtain rfl : k = s.2 := by omega - exact Int.le_refl _ - · next hslt => - rw [BitVec.slt_iff_toInt_lt] at hslt - by_cases hki : k < s.2 - · exact habove k hk0 hki - · obtain rfl : k = s.2 := by omega - omega - -- Entry: the prefix is just `nums[0]`. - · rename_i hpre _ h0 - refine ⟨⟨0, by omega, by omega, by simp⟩, ?_, by omega, by exact_mod_cast h0⟩ - intro k hk0 hk - obtain rfl : k = 0 := by omega - simp - -/-- info: 'Strata.Shallow.Test.pick_nat_spec' depends on axioms: [propext, Quot.sound] -/ -#guard_msgs in -#print axioms pick_nat_spec - -/-- info: 'Strata.Shallow.Test.sum_to_spec' depends on axioms: [propext, Classical.choice, Quot.sound] -/ -#guard_msgs in -#print axioms sum_to_spec - -/-- info: 'Strata.Shallow.Test.find_max_spec' depends on axioms: [propext, Classical.choice, Quot.sound] -/ -#guard_msgs in -#print axioms find_max_spec - -end Strata.Shallow.Test diff --git a/docs/HoareLogic.md b/docs/HoareLogic.md index 9d08481..5a5b045 100644 --- a/docs/HoareLogic.md +++ b/docs/HoareLogic.md @@ -82,8 +82,7 @@ build, on a stable target. This is `core_lift` of the same experiment. 3. **Boole entry.** `Strata.Boole.typeCheck` gives the type-checked Core program of a `#strata program Boole` block as a Lean term, and the triple is stated on its - procedures, as in `hoare_max2.lean`. The prototype's `shallow_reflect` (fork branch) - wraps this as a command. + procedures, as in `hoare_max2.lean`. A reflection command on a fork branch wraps this. 4. **The model, in Strata.** Not needed to prove a triple, needed to trust one. - Datatypes: constructors, testers and destructors enter the visible factory (`Lambda.genBlockFactory` generates them), and the model's datatype laws, today @@ -114,7 +113,7 @@ then the benchmark below. - Core first, then Boole: Core is where the proved semantics lives, so a Boole semantics has something to agree with. - Goals over Lean values come from lifting, not from a monadic encoding, so - `Std.Do`/`mvcgen` (`StrataBoole/Shallow/Layer.lean`) is off the path. + `Std.Do`/`mvcgen` is off the path. - Failure is never vacuous: a construct the tactic cannot handle leaves its goal open. - Datatypes: keep Strata's approach of stating their laws as conditions on every model, and supply the model from one generic carrier, a single inductive of constructor @@ -124,7 +123,7 @@ then the benchmark below. path's goals must equal its denotation, which is over the carrier too. Readable goals are notation added later. - This is a deep embedding with shallow goals: the program stays data, and the user sees - goals over Lean values. The `Shallow` names in the tree are the earlier prototype's. + goals over Lean values. ## Coverage @@ -193,7 +192,6 @@ kernel checks that proof for each program. - Risk: discharging the side conditions is the bulk of step 1. Strata's hand proof of a two-branch `if` is some 25 lines, its call test some 1400 lines for three procedures. - `StrataBooleTest/generic_datatypes.lean` is a first prototype of the carrier. - `StrataBoole/Shallow/Layer.lean` is kept until the first milestone. ## Strata changes for this route diff --git a/docs/onboarding.md b/docs/onboarding.md index 853551e..2870e43 100644 --- a/docs/onboarding.md +++ b/docs/onboarding.md @@ -36,9 +36,10 @@ before you read the code as though it were the design. * **Rust is one front end, not the front end.** Python, C and C++, and Java are intended to reach Boole the same way. -* **A shallow embedding is being explored** alongside the deep one, following - Velvet and Loom, where a program becomes a Lean term directly rather than - data interpreted by a generator. +* **A second Lean route is being built** on Core's Hoare logic + (`docs/HoareLogic.md`): the program stays data, its contract is proved as a + Hoare triple over Core's semantics, and the goals a person reads are over + Lean values. * **cvc5 is one prover among several.** A Lean goal can be closed by `smt` (lean-smt, which calls cvc5 and replays its proof), by Lean Hammer, by `grind`, or by LLM-based and other AI-based provers. @@ -204,7 +205,7 @@ say so and stop. That is a real result, and it belongs in * [Lean-SMT](https://github.com/ufmg-smite/lean-smt), the tactic behind the kernel back end. It hands a goal to cvc5 and reconstructs the returned proof in Lean, so the solver does not have to be trusted. -* Velvet and Loom, for the shallow embedding mentioned above. Loom is +* Velvet and Loom, the related work closest to that route. Loom is [*Foundational Multi-Modal Program Verifiers*](https://ilyasergey.net/assets/pdf/papers/loom-preprint.pdf), and [Velvet](https://ilyasergey.net/assets/pdf/papers/velvet-cav26.pdf) is the Dafny-style verifier built on it. From d80bde450937b6d4fdfede5d60589b9915a3f444 Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:50:41 +0100 Subject: [PATCH 41/64] Bump Strata to main with the merged contract-triple axioms The pin moves to the integration branch at 07dfdf5c8: Strata main with strata-org/Strata#1499 merged, plus the open #1493 and #1483. hoare_max2 names the fields of InitEnvWFParams, the out-of-bounds obligation of seq_slicing now fails as it should, and the Hoare document records the merged change. --- .../FeatureRequests/seq_slicing.lean | 10 ++++---- StrataBooleTest/hoare_max2.lean | 6 ++--- docs/HoareLogic.md | 25 +++++++++++-------- lake-manifest.json | 4 +-- lakefile.toml | 2 +- 5 files changed, 25 insertions(+), 22 deletions(-) diff --git a/StrataBooleTest/FeatureRequests/seq_slicing.lean b/StrataBooleTest/FeatureRequests/seq_slicing.lean index a49c415..fa1e20e 100644 --- a/StrataBooleTest/FeatureRequests/seq_slicing.lean +++ b/StrataBooleTest/FeatureRequests/seq_slicing.lean @@ -166,9 +166,9 @@ example : Strata.smtVCsCorrectBoole seqSlicingSeed := by gen_smt_vcs_boole all_goals (try grind) --- Shape test: Sequence.select on an empty sequence currently produces no --- out-of-bounds precondition VC (that guard is tracked separately). --- The ensures clause passes because the result is unconstrained. +-- Shape test: Sequence.select on an empty sequence is out of bounds, and the +-- bounds check reports it. The ensures clause is unknown: the result is +-- unconstrained. private def seqOutOfBoundsSeed : StrataDDM.Program := #strata program Boole; @@ -185,9 +185,9 @@ spec { /-- info: Obligation: set_v_calls_Sequence.select_0 Property: out-of-bounds access check -Result: ❓ unknown +Result: ❌ fail -Obligation: seq_oob_seed_ensures_0_4990 +Obligation: seq_oob_seed_ensures_0_4950 Property: assert Result: ❓ unknown-/ #guard_msgs in diff --git a/StrataBooleTest/hoare_max2.lean b/StrataBooleTest/hoare_max2.lean index 1102c44..32d9d9b 100644 --- a/StrataBooleTest/hoare_max2.lean +++ b/StrataBooleTest/hoare_max2.lean @@ -115,9 +115,9 @@ theorem max2_checksTyped : Core.Logic.Hoare.Procedure.contractChecksTyped max2Pr theorem max2_factory : max2Core.factoryBeforeProcedure "max2" = Core.Factory := Core.Program.factoryBeforeProcedure_eq_core_of_noFunctions (by native_decide) -/-- Gate parameters: no reserved prefixes for identifiers or block labels, every operator - counts as declared. -/ -def params : Core.Logic.InitEnvWFParams := ⟨[], [], fun _ => true⟩ +/-- Gate parameters: no reserved prefixes, every operator counts as declared. -/ +def params : Core.Logic.InitEnvWFParams := + { prefixIdents := [], declaredFuncs := fun _ => true } /-! ## The values of the inputs -/ diff --git a/docs/HoareLogic.md b/docs/HoareLogic.md index 5a5b045..3a29d96 100644 --- a/docs/HoareLogic.md +++ b/docs/HoareLogic.md @@ -39,8 +39,9 @@ semantics: - `Procedure.contractTriple`: `requires` and `ensures` as the triple to prove, with `old` snapshots and typed parameters and clauses. Its factory is Core's operators plus the functions declared before the procedure, with or without body - (`Program.factoryBeforeProcedure`). Datatype declarations add nothing to it, and the - program's axioms are not in the precondition. + (`Program.factoryBeforeProcedure`). Datatype declarations add nothing to it. Its + precondition assumes the axioms declared before the procedure + (`AxiomsBeforeProcedureDecl`), since strata-org/Strata#1499. - Strata's notion of correctness, `ProcedureAssertsValidOnTraces.denote`: every assertion on every run is valid and the postconditions hold, from entry environments satisfying the axioms declared before the procedure (`AxiomsBeforeProcedureDecl`). @@ -60,10 +61,10 @@ build, on a stable target. ## Plan -1. **Tactic.** State the contract triple with `AxiomsBeforeProcedureDecl` added to its - precondition, so the axioms are available as Strata's notion of correctness assumes - them. A theorem to write takes a proved triple to the part of that notion about runs - that finish; the part about runs that do not also needs termination. Apply the rules +1. **Tactic.** Prove Strata's contract triple. Its precondition has the axioms declared + before the procedure, as Strata's notion of correctness assumes them, and + `contract_of_contractTriple` takes a proved triple to the part of that notion about + runs that finish; the part about runs that do not also needs termination. Apply the rules backwards and discharge their side conditions: `exitsCoveredByBlocks`, and `PostWF` for a block that declares nothing, by evaluation on the concrete AST; `PostWF` for a block with declarations from `denoteEval_congr`, since a postcondition does not read the @@ -90,8 +91,9 @@ build, on a stable target. - A model exists for a program's factory with its axioms, built on the carrier (Decisions). This rules out a vacuous triple, and proves the `nat` bridge axioms of the intended `nat` instead of assuming them. - - `contractTriple` and `call_of_contract` carry the axioms, so a callee's proof may - use them. + - At a call, the callee's axioms are shown in the callee's entry store + (`call_of_contract` asks for them). For closed axioms this follows from the caller's + entry; that lemma is to write. - Function preconditions and termination of recursive functions, which the solver path checks, stated beside the triple. - Rules for nondeterministic `if` and `while`. @@ -196,14 +198,15 @@ kernel checks that proof for each program. ## Strata changes for this route This branch pins the `integration/lean-route` branch of the fork: Strata main plus the -pull requests below that are still open. The pin returns to strata-org/Strata when they -merge. +pull requests below that are still open, strata-org/Strata#1493 and +strata-org/Strata#1483. The pin returns to strata-org/Strata when they merge. | Change | State | Used by | | --- | --- | --- | | strata-org/Strata#1498: rules `init_nondet`, `havoc`, `assume`, `assert`, and the forms of the last two that read a condition by evaluation | merged | step 1 | | strata-org/Strata#1492: public unfolding lemmas for quantifiers and binders | merged | quantifier lifting in step 2 | -| strata-org/Strata#1493: datatypes in the SMT denotation, with the generic carrier | open, not reviewed | the SMT path now, the model of step 4 later | +| strata-org/Strata#1499: the contract triple assumes the axioms declared before the procedure, and a proved triple gives the contract of Strata's notion of correctness | merged | step 1 | +| strata-org/Strata#1493: datatypes in the SMT denotation, with the generic carrier | open, in review | the SMT path now, the model of step 4 later | | strata-org/Strata#1496: `Map` and `Sequence` statements had no execution, and models did not have to satisfy their axioms | closed, fixed upstream by the denotational evaluation | step 2 | | strata-org/Strata#1490: the SMT path refuses the VCs its denotation does not cover | merged | Goal | diff --git a/lake-manifest.json b/lake-manifest.json index c0b5ef2..38321a9 100644 --- a/lake-manifest.json +++ b/lake-manifest.json @@ -15,10 +15,10 @@ "type": "git", "subDir": null, "scope": "", - "rev": "d68fdcb6e50051d511f2327f259d4e9da0dee7b4", + "rev": "07dfdf5c8eb98b36ae0189a086ed271ff3a2be45", "name": "Strata", "manifestFile": "lake-manifest.json", - "inputRev": "d68fdcb6e", + "inputRev": "07dfdf5c8", "inherited": false, "configFile": "lakefile.toml"}, {"url": "https://github.com/leanprover-community/mathlib4.git", diff --git a/lakefile.toml b/lakefile.toml index e2a5dd0..e4e92ae 100644 --- a/lakefile.toml +++ b/lakefile.toml @@ -12,7 +12,7 @@ name = "Strata" # pass). It moves back to strata-org/Strata when they merge. A fixed commit, not a branch # name, so `lake update` cannot move it. git = "https://github.com/kondylidou/Strata" -rev = "d68fdcb6e" +rev = "07dfdf5c8" [[require]] name = "smt" From 2187eba752fd6a42c93e2621ca2d1bc31e97e84d Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:17:35 +0100 Subject: [PATCH 42/64] Give the trusted callee of sum_of_slice a body that assumes its contract Scalar_add had the body assume false, after which no run continues: on the Hoare route every obligation of the caller after the first call would hold vacuously. The translator now emits a body that havocs the result and assumes each ensures. The program is regenerated; five obligation labels shift and cvc5 still passes all 36 obligations. The Hoare document describes the body. Co-Authored-By: Claude Fable 5.2 --- StrataBooleTest/dalek_sum_of_slice.lean | 15 +++++++++------ docs/HoareLogic.md | 9 +++++---- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/StrataBooleTest/dalek_sum_of_slice.lean b/StrataBooleTest/dalek_sum_of_slice.lean index 5381bd9..c5afdda 100644 --- a/StrataBooleTest/dalek_sum_of_slice.lean +++ b/StrataBooleTest/dalek_sum_of_slice.lean @@ -152,7 +152,10 @@ spec { ensures is_canonical_scalar(result); } { - assume false; + havoc result; + assume [trusted_0]: Scalar_obeys_add_spec ==> result == Scalar_add_spec(self, _rhs); + assume [trusted_1]: nat_toInt(scalar_as_nat(result)) == nat_toInt(group_canonical(nat_add(scalar_as_nat(self), scalar_as_nat(_rhs)))); + assume [trusted_2]: is_canonical_scalar(result); }; procedure sum_of_slice (scalars : Sequence Scalar) returns (result : Scalar) spec { @@ -243,11 +246,11 @@ Obligation: Scalar_add_ensures_4_9637 Property: assert Result: ✅ pass -Obligation: sum_of_slice_pre_sum_of_slice_requires_6_9783_calls_Sequence.select_0 +Obligation: sum_of_slice_pre_sum_of_slice_requires_5_10058_calls_Sequence.select_0 Property: out-of-bounds access check Result: ✅ pass -Obligation: sum_of_slice_post_sum_of_slice_ensures_9_9995_calls_sum_of_scalars_0 +Obligation: sum_of_slice_post_sum_of_slice_ensures_8_10270_calls_sum_of_scalars_0 Property: assert Result: ✅ pass @@ -315,15 +318,15 @@ Obligation: insertLoopInvAssert_arbitrary_iter_maintain_invariant_loop_7_5 Property: assert Result: ✅ pass -Obligation: sum_of_slice_ensures_7_9902 +Obligation: sum_of_slice_ensures_6_10177 Property: assert Result: ✅ pass -Obligation: sum_of_slice_ensures_8_9956 +Obligation: sum_of_slice_ensures_7_10231 Property: assert Result: ✅ pass -Obligation: sum_of_slice_ensures_9_9995 +Obligation: sum_of_slice_ensures_8_10270 Property: assert Result: ✅ pass -/ diff --git a/docs/HoareLogic.md b/docs/HoareLogic.md index 3a29d96..06bb68b 100644 --- a/docs/HoareLogic.md +++ b/docs/HoareLogic.md @@ -156,10 +156,11 @@ contracts pass `contractChecksTyped`, and caller and callee see the same factory - `nat` is used only through its library and those axioms, so the proof should need no datatype reasoning and does not wait on step 4. -- The callee is trusted, with body `assume false`. A call runs the callee's body, so - every obligation of the caller after the first call holds vacuously. The benchmark - needs a body that can run, such as assigning an arbitrary value and assuming the - `ensures`: a change to the benchmark and its translation, not to Strata. +- The callee is trusted. Its body gives the result an arbitrary value and assumes each + `ensures` (`assume [trusted_k]`), so a call can run and what the callee promises is + its contract. A body `assume false` would also meet the contract, but a call runs the + callee's body, and every obligation of the caller after the first call would hold + vacuously. - Lifted goals stay within what lean-smt closes (`Int`, `Bool`, `BitVec`): sequences as a length and an index function, `nat` through `nat.toInt`. From 5b6a3fca1bd76d21ff8bd596f93e15268a67987e Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:25:00 +0100 Subject: [PATCH 43/64] Record the call-site lemma pull request in the Hoare document Co-Authored-By: Claude Fable 5.2 --- docs/HoareLogic.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/HoareLogic.md b/docs/HoareLogic.md index 06bb68b..188408c 100644 --- a/docs/HoareLogic.md +++ b/docs/HoareLogic.md @@ -92,8 +92,10 @@ build, on a stable target. (Decisions). This rules out a vacuous triple, and proves the `nat` bridge axioms of the intended `nat` instead of assuming them. - At a call, the callee's axioms are shown in the callee's entry store - (`call_of_contract` asks for them). For closed axioms this follows from the caller's - entry; that lemma is to write. + (`call_of_contract` asks for them). For axioms that read no variable and a callee + declared no later than the caller, they follow from the caller's entry + (`AxiomsBeforeProcedureDecl.callee`, strata-org/Strata#1501), and + `Hoare.frame_factory` carries the caller's entry assumption to each call. - Function preconditions and termination of recursive functions, which the solver path checks, stated beside the triple. - Rules for nondeterministic `if` and `while`. @@ -207,6 +209,7 @@ strata-org/Strata#1483. The pin returns to strata-org/Strata when they merge. | strata-org/Strata#1498: rules `init_nondet`, `havoc`, `assume`, `assert`, and the forms of the last two that read a condition by evaluation | merged | step 1 | | strata-org/Strata#1492: public unfolding lemmas for quantifiers and binders | merged | quantifier lifting in step 2 | | strata-org/Strata#1499: the contract triple assumes the axioms declared before the procedure, and a proved triple gives the contract of Strata's notion of correctness | merged | step 1 | +| strata-org/Strata#1501: the callee's axioms at a call from the caller's entry, and a frame rule for facts about the factory | open | calls in step 1 | | strata-org/Strata#1493: datatypes in the SMT denotation, with the generic carrier | open, in review | the SMT path now, the model of step 4 later | | strata-org/Strata#1496: `Map` and `Sequence` statements had no execution, and models did not have to satisfy their axioms | closed, fixed upstream by the denotational evaluation | step 2 | | strata-org/Strata#1490: the SMT path refuses the VCs its denotation does not cover | merged | Goal | From 126c4b45613a1d89f8a8b6a42570fa704d47d1f5 Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:49:32 +0100 Subject: [PATCH 44/64] Decide termination as a separate proof in the Hoare document --- docs/HoareLogic.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/HoareLogic.md b/docs/HoareLogic.md index 188408c..852a100 100644 --- a/docs/HoareLogic.md +++ b/docs/HoareLogic.md @@ -119,6 +119,13 @@ then the benchmark below. - Goals over Lean values come from lifting, not from a monadic encoding, so `Std.Do`/`mvcgen` is off the path. - Failure is never vacuous: a construct the tactic cannot handle leaves its goal open. +- Termination is a separate proof. The tactic proves the partial triple. Strata main has + total-correctness triples since November 2026 (`Core.Logic.HoareTotal`, + `Procedure.contractTripleTotal`, a `while_rule` with a natural-number measure), and + `TripleWith.of_partial_of_true` gives the total triple from the partial one and a total + triple with postcondition `True`. So termination needs only a measure per loop, reuses + the partial proof unchanged, and follows the benchmark. It needs a pin that includes + these triples. - Datatypes: keep Strata's approach of stating their laws as conditions on every model, and supply the model from one generic carrier, a single inductive of constructor applications with a well-sortedness predicate (`DT.Carrier`, strata-org/Strata#1493, @@ -219,9 +226,6 @@ only. Nothing of step 4 has a pull request yet; its shape is the last two open q ## Open questions -- Termination: `while_rule` is partial correctness, while Strata's notion of correctness - also covers runs that never finish. Add a total-correctness rule, or check `decreases` - separately? - `cover` is a reachability check, not a Hoare fact. How to state it? - Goal names: carry the program's clause names into the goals the tactic leaves. - Datatypes and program models in the Hoare logic (step 4): no upstream test uses either, From 82a2a6fc3c37b18d5df7ec10cd8df2e03bba70dc Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:14:03 +0100 Subject: [PATCH 45/64] Record the datatype factory pull request in the Hoare document --- docs/HoareLogic.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/HoareLogic.md b/docs/HoareLogic.md index 852a100..225e5d0 100644 --- a/docs/HoareLogic.md +++ b/docs/HoareLogic.md @@ -86,8 +86,9 @@ build, on a stable target. procedures, as in `hoare_max2.lean`. A reflection command on a fork branch wraps this. 4. **The model, in Strata.** Not needed to prove a triple, needed to trust one. - Datatypes: constructors, testers and destructors enter the visible factory - (`Lambda.genBlockFactory` generates them), and the model's datatype laws, today - disjointness and injectivity, gain inversion and induction. + (`Program.factoryBeforeProcedure` folds with `Decl.addToRuntimeFactory`, + strata-org/Strata#1502), and the model's datatype laws, today disjointness and + injectivity, gain inversion and induction. - A model exists for a program's factory with its axioms, built on the carrier (Decisions). This rules out a vacuous triple, and proves the `nat` bridge axioms of the intended `nat` instead of assuming them. @@ -217,6 +218,7 @@ strata-org/Strata#1483. The pin returns to strata-org/Strata when they merge. | strata-org/Strata#1492: public unfolding lemmas for quantifiers and binders | merged | quantifier lifting in step 2 | | strata-org/Strata#1499: the contract triple assumes the axioms declared before the procedure, and a proved triple gives the contract of Strata's notion of correctness | merged | step 1 | | strata-org/Strata#1501: the callee's axioms at a call from the caller's entry, and a frame rule for facts about the factory | open | calls in step 1 | +| strata-org/Strata#1502: the constructors, testers and destructors of a datatype in the factory visible to a procedure | open | datatypes in step 4 | | strata-org/Strata#1493: datatypes in the SMT denotation, with the generic carrier | open, in review | the SMT path now, the model of step 4 later | | strata-org/Strata#1496: `Map` and `Sequence` statements had no execution, and models did not have to satisfy their axioms | closed, fixed upstream by the denotational evaluation | step 2 | | strata-org/Strata#1490: the SMT path refuses the VCs its denotation does not cover | merged | Goal | From f198ed1d771a771cbb7b5e92f086804b4be96ba2 Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:45:31 +0100 Subject: [PATCH 46/64] more --- docs/HoareLogic.md | 55 ++++++++++++++++++++++++++++------------------ 1 file changed, 34 insertions(+), 21 deletions(-) diff --git a/docs/HoareLogic.md b/docs/HoareLogic.md index 225e5d0..34c527f 100644 --- a/docs/HoareLogic.md +++ b/docs/HoareLogic.md @@ -39,22 +39,25 @@ semantics: - `Procedure.contractTriple`: `requires` and `ensures` as the triple to prove, with `old` snapshots and typed parameters and clauses. Its factory is Core's operators plus the functions declared before the procedure, with or without body - (`Program.factoryBeforeProcedure`). Datatype declarations add nothing to it. Its + (`Program.factoryBeforeProcedure`). Datatype declarations add their constructors, + testers and destructors on Strata main (strata-org/Strata#1502), nothing on this pin. Its precondition assumes the axioms declared before the procedure (`AxiomsBeforeProcedureDecl`), since strata-org/Strata#1499. - Strata's notion of correctness, `ProcedureAssertsValidOnTraces.denote`: every assertion on every run is valid and the postconditions hold, from entry environments satisfying the axioms declared before the procedure (`AxiomsBeforeProcedureDecl`). - `Strata/Transform/SpecHoareConnection.lean` takes a triple to assertion validity on - every run, given termination. + On Strata main the partial triple also asks that the assertions of every finite + execution hold, finished or not, so a proved contract triple gives all of this notion + (`procedureAssertsValidOnTraces_of_contractTriple`) without a termination premise. The + rules kept their signatures; only proofs that unfold the triple change. - Denotational evaluation (since November 2026): `Expression.eval` is `LExpr.denoteEval` over the factory and a model of it, and stores hold semantic values. Lifting lemmas exist for `+`, `-`, `*` and the comparisons on `int`, three `bv16` operators, free variables, `==` and `if` (`IntEvalProps.lean`, `BitVecEvalProps.lean`), with a generic one for any binary operator that has a concrete evaluation (`eval_app2_op`). -Its tests prove some twenty procedures by hand, with `native_decide` for facts about the -AST; none uses axioms, datatypes, maps or sequences. There is no automation and its +Its tests prove procedures by hand, with `native_decide` for facts about the AST, among +them ones with axioms, datatypes, maps and sequences. There is no automation and its authors plan none: the triple is their specification of partial correctness, and generating verification conditions against it is open to others. So the tactic is ours to build, on a stable target. @@ -62,9 +65,10 @@ build, on a stable target. ## Plan 1. **Tactic.** Prove Strata's contract triple. Its precondition has the axioms declared - before the procedure, as Strata's notion of correctness assumes them, and - `contract_of_contractTriple` takes a proved triple to the part of that notion about - runs that finish; the part about runs that do not also needs termination. Apply the rules + before the procedure, as Strata's notion of correctness assumes them, and a proved + triple gives all of that notion (`procedureAssertsValidOnTraces_of_contractTriple`, on + Strata main; on this pin `contract_of_contractTriple` gives the part about runs that + finish). Apply the rules backwards and discharge their side conditions: `exitsCoveredByBlocks`, and `PostWF` for a block that declares nothing, by evaluation on the concrete AST; `PostWF` for a block with declarations from `denoteEval_congr`, since a postcondition does not read the @@ -91,14 +95,17 @@ build, on a stable target. injectivity, gain inversion and induction. - A model exists for a program's factory with its axioms, built on the carrier (Decisions). This rules out a vacuous triple, and proves the `nat` bridge axioms of - the intended `nat` instead of assuming them. + the intended `nat` instead of assuming them. A model holds every function to its + body, so termination of recursive functions belongs here: a terminating definition + always has a solution, a non-terminating one may have none. - At a call, the callee's axioms are shown in the callee's entry store (`call_of_contract` asks for them). For axioms that read no variable and a callee declared no later than the caller, they follow from the caller's entry (`AxiomsBeforeProcedureDecl.callee`, strata-org/Strata#1501), and `Hoare.frame_factory` carries the caller's entry assumption to each call. - - Function preconditions and termination of recursive functions, which the solver path - checks, stated beside the triple. + - Function preconditions, stated beside the triple. A precondition is an annotation and + a function stays total, so the triple holds without it; the checks the solver path + makes, such as sequence bounds, are a separate property. - Rules for nondeterministic `if` and `while`. 5. **Boole semantics.** A Boole interpreter proved to agree with `toCoreProgram`, so that Boole has a meaning in its own terms and the lowering is proved, not trusted. It @@ -147,7 +154,7 @@ then the benchmark below. | `Map`, `Sequence`, `Set`, `string` | constrained in every model; lifting to add (step 2) | | functions, with or without body | in the model | | `axiom` | through `AxiomsBeforeProcedureDecl` (step 1); assumed until step 4 | -| datatypes, `nat` | not in the model: constructors are unconstrained symbols (step 4) | +| datatypes, `nat` | not in the model on this pin: constructors are unconstrained symbols. Strata main adds constructors, testers and destructors to the visible factory (strata-org/Strata#1502); inversion and induction to add (step 4) | ## Target: `dalek_sum_of_slice` @@ -182,10 +189,12 @@ written: | Trusted today | Removed by | | --- | --- | | the Boole to Core lowering | step 5 | -| the program's axioms, and that a model of the program with them exists | step 4 | -| function preconditions and termination, which the triple does not state | step 4 | +| the program's axioms, and that a model of the program with them exists, which for recursive functions includes their termination | step 4 | | the Lean compiler, through `native_decide` on facts about the AST | kernel-checked facts in the tactic | +Function preconditions and the termination of loops are not assumed: the partial triple +does not claim them, and each is a separate proof (step 4 and Decisions). + The solver path trusts the lowering and the axioms too, and in addition Strata's transformation pipeline, the SMT encoding and the solver. The tactic needs no adequacy theorem: it builds a proof from rules that are theorems about the semantics, and the @@ -210,7 +219,9 @@ kernel checks that proof for each program. This branch pins the `integration/lean-route` branch of the fork: Strata main plus the pull requests below that are still open, strata-org/Strata#1493 and -strata-org/Strata#1483. The pin returns to strata-org/Strata when they merge. +strata-org/Strata#1483. The pin returns to strata-org/Strata when they merge. Changes +merged after the pin, among them strata-org/Strata#1502 and the total-correctness triples, +arrive with that bump. | Change | State | Used by | | --- | --- | --- | @@ -218,22 +229,24 @@ strata-org/Strata#1483. The pin returns to strata-org/Strata when they merge. | strata-org/Strata#1492: public unfolding lemmas for quantifiers and binders | merged | quantifier lifting in step 2 | | strata-org/Strata#1499: the contract triple assumes the axioms declared before the procedure, and a proved triple gives the contract of Strata's notion of correctness | merged | step 1 | | strata-org/Strata#1501: the callee's axioms at a call from the caller's entry, and a frame rule for facts about the factory | open | calls in step 1 | -| strata-org/Strata#1502: the constructors, testers and destructors of a datatype in the factory visible to a procedure | open | datatypes in step 4 | +| strata-org/Strata#1502: the constructors, testers and destructors of a datatype in the factory visible to a procedure | merged | datatypes in step 4 | | strata-org/Strata#1493: datatypes in the SMT denotation, with the generic carrier | open, in review | the SMT path now, the model of step 4 later | | strata-org/Strata#1496: `Map` and `Sequence` statements had no execution, and models did not have to satisfy their axioms | closed, fixed upstream by the denotational evaluation | step 2 | | strata-org/Strata#1490: the SMT path refuses the VCs its denotation does not cover | merged | Goal | The integration branch also carries strata-org/Strata#1483, which concerns the solver path -only. Nothing of step 4 has a pull request yet; its shape is the last two open questions. +only. Of step 4, the datatype functions are merged (strata-org/Strata#1502); the rest has +no pull request yet. ## Open questions - `cover` is a reachability check, not a Hoare fact. How to state it? - Goal names: carry the program's clause names into the goals the tactic leaves. -- Datatypes and program models in the Hoare logic (step 4): no upstream test uses either, - so agree the shape with Strata before building. -- Trusted procedures: `Triple` runs a callee's body, while Strata also has a - contract-based call semantics (`EvalCmdExtContractE`). Should a triple over it exist? +- Program models (step 4): how to show that a model of a program's factory and axioms + exists. Agree the shape with Strata before building. +- Trusted procedures: `Triple` runs a callee's body, so a trusted callee needs a body that + assumes its contract (Target). That body can go once Core's semantics gives a bodyless + procedure a meaning. ## Sources From ebba716cbaea71094a6ddfe52b510dee66b4a726 Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:16:06 +0100 Subject: [PATCH 47/64] Pin Strata main with the open Lean-route pull requests, on Lean 4.35 The pin moves to integration/lean-route 869920098: Strata main (ce946780c) with strata-org/Strata#1483, #1493 and #1501. lean-smt moves to cbec5bd22, its last commit on Lean 4.35. - Procedure bodies carry Core's opaque flag; a Core procedure's opaque mark is kept. - Calls pass no explicit type arguments, which the type checker infers. - The nat model check accepts a model when the obligation has the value its query asks for, which Core's model validation now names. - hoare_max2 follows the new contract precondition (typed outputs) and passes hmono. - Pinned outputs follow Core's new label numbering and Lean's report of native_decide. - docs/HoareLogic.md describes the new pin. Co-Authored-By: Claude Opus 5.5 --- StrataBoole/Verify.lean | 38 +++++---- .../sha256_compact_indexed.lean | 84 ++++++++++--------- StrataBooleTest/demo.lean | 9 +- StrataBooleTest/global_readonly_call.lean | 36 ++++---- StrataBooleTest/hoare_max2.lean | 8 +- docs/HoareLogic.md | 24 +++--- lake-manifest.json | 42 +++++----- lakefile.toml | 8 +- lean-toolchain | 2 +- 9 files changed, 127 insertions(+), 124 deletions(-) diff --git a/StrataBoole/Verify.lean b/StrataBoole/Verify.lean index 06bdb68..14a1e4f 100644 --- a/StrataBoole/Verify.lean +++ b/StrataBoole/Verify.lean @@ -775,7 +775,7 @@ private def toCoreStmt (s : BooleDDM.Statement SourceRange) : TranslateM Core.St let globalsPrefix ← constructProcArgsPrefix n let userIn := (← args.toList.mapM toCoreExpr).map Imperative.CallArg.inArg let userOut := (lhs.toList.map (mkIdent ·.val)).map Imperative.CallArg.outArg - return Core.Statement.call n (globalsPrefix ++ userIn ++ userOut) (← toCoreMetaData m) + return Core.Statement.call n none (globalsPrefix ++ userIn ++ userOut) (← toCoreMetaData m) | .call_statement m _ ⟨_, n⟩ ⟨_, callArgs⟩ => do -- Reject Core-only out/inout call argument syntax in Boole. -- Boole uses `call lhs := f(args)` for calls with outputs. @@ -791,7 +791,7 @@ private def toCoreStmt (s : BooleDDM.Statement SourceRange) : TranslateM Core.St match ca with | .callArgExpr _ e => return some (Imperative.CallArg.inArg (← toCoreExpr e)) | _ => return none -- unreachable: out/inout rejected above - return Core.Statement.call n (globalsPrefix ++ userIn) (← toCoreMetaData m) + return Core.Statement.call n none (globalsPrefix ++ userIn) (← toCoreMetaData m) | .block_statement m _ ⟨_, l⟩ b => return .block l (← withBVars [] (toCoreBlock b)) (← toCoreMetaData m) | .exit_statement m _ ⟨_, l⟩ => @@ -1004,6 +1004,7 @@ private def translateProcedureDecl (outputs : ListMap Core.CoreIdent Lambda.LMonoTy) (spec? : Option (BooleDDM.Spec SourceRange)) (body? : Option (BooleDDM.Block SourceRange)) + (isOpaque : Bool := false) : TranslateM (List Core.Decl) := do let (modifiesTyped, readOnlyGlobals) ← getGlobalParamPrefix n let allInputs := modifiesTyped ++ readOnlyGlobals ++ inputs @@ -1027,7 +1028,7 @@ private def translateProcedureDecl return [.proc { header := { name := mkIdent n, typeArgs := tys, inputs := allInputs, outputs := allOutputs } spec := spec - body := .structured body + body := .structured body isOpaque } .empty] private def toCoreDecls (cmd : BooleDDM.Command SourceRange) : TranslateM (List Core.Decl) := do @@ -1041,15 +1042,15 @@ private def toCoreDecls (cmd : BooleDDM.Command SourceRange) : TranslateM (List | none => pure [] | some os => (monoDeclListToList os).mapM toCoreMonoBind translateProcedureDecl m n tys inputs outputs specAnn.val bodyAnn.val - | .command_procedure m _ nameAnn targsAnn ins specAnn bodyAnn => + | .command_procedure m _ nameAnn targsAnn ins specAnn opqAnn bodyAnn => let n := nameAnn.val if let some (param, kind) := hasOutOrInoutBinding ins then throwAt m s!"Boole procedure '{n}': '{kind}' modifier on parameter '{param}' is not supported. Use 'returns' syntax instead, e.g. 'procedure {n}(...) returns ({param} : T)'." let tys := match targsAnn.val with | none => [] | some ts => typeArgsToList ts withTypeBVars tys do let inputs ← (bindingsToList ins).mapM toCoreBinding - translateProcedureDecl m n tys inputs [] specAnn.val bodyAnn.val - | .command_cfg_procedure m _ nameAnn _ _ _ _ => + translateProcedureDecl m n tys inputs [] specAnn.val bodyAnn.val opqAnn.val.isSome + | .command_cfg_procedure m _ nameAnn _ _ _ _ _ => throwAt m s!"Boole procedure '{nameAnn.val}': CFG-form procedure bodies (`cfg ENTRY \{ ... }`) are not supported in Boole; use a structured body." | .command_typedecl _ _ ⟨_, n⟩ ⟨_, args?⟩ => let params := match args? with @@ -1164,7 +1165,7 @@ private def toCoreDecls (cmd : BooleDDM.Command SourceRange) : TranslateM (List return [.proc { header := { name := mkIdent topLevelBlockProcedureName, typeArgs := [], inputs := [], outputs := [] } spec := { preconditions := [], postconditions := [] } - body := .structured (← toCoreBlock b) + body := .structured (← toCoreBlock b) false } .empty] | .command_datatypes _ _ ⟨_, decls⟩ => let datatypes ← decls.toList.mapM toCoreDatatypeDecl @@ -1199,7 +1200,7 @@ def toCoreProgram (p : Boole.Program) (gctx : GlobalContext := {}) (fileName : S | .boole_procedure _ nameAnn _ _ _ _ specAnn _ => let mods ← collectModifiesFromSpec fileName nameAnn.val specAnn.val varTypes if !mods.isEmpty then modMap := modMap.insert nameAnn.val mods - | .command_procedure _ _ nameAnn _ _ specAnn _ => + | .command_procedure _ _ nameAnn _ _ specAnn _ _ => let mods ← collectModifiesFromSpec fileName nameAnn.val specAnn.val varTypes if !mods.isEmpty then modMap := modMap.insert nameAnn.val mods | _ => pure () @@ -1294,8 +1295,8 @@ private def coreProgUsesNatOrPos (cp : Core.Program) : Bool := | .proc p _ => p.header.inputs.values.any lMonoTyHasNatOrPos || p.header.outputs.values.any lMonoTyHasNatOrPos || (match p.body with - | .structured ss => stmtListHasNatOrPos ss - | .cfg _ => false) + | .structured ss _ => stmtListHasNatOrPos ss + | .cfg _ _ | .abstract => false) || p.spec.preconditions.values.any (fun c => lExprUsesNatOrPos c.expr) || p.spec.postconditions.values.any (fun c => lExprUsesNatOrPos c.expr) | .type (.data block) _ => block.any fun dt => @@ -1716,22 +1717,22 @@ private partial def evalExpr | _ => none | _ => none --- Returns `true` when (1) the obligation expression evaluates to any value and +-- Returns `true` when (1) the obligation evaluates to the value the query asks for and -- (2) no ground path-condition assumption evaluates to `false`. -- Condition (2) rejects broken candidates: partial assignments from a timed-out -- solver where e.g. `toInt(a) = 73` is asserted but the candidate has `a = N0`. -- Quantified assumptions (bridge axioms) can't be evaluated and are skipped. private def validateNatModel - (obligation : Imperative.ProofObligation Core.Expression) + (obligation : Imperative.ProofObligation Core.Expression) (holds : Bool) (m : Imperative.SMT.Model Core.Expression.Ident) : Bool := let model := buildEvalModel m let defMap := buildDefMap obligation.assumptions - -- Require the obligation to evaluate to false: obligation.obligation is P (the - -- assertion being checked). The SMT query asserts NOT(P) looking for a model - -- where P fails. A valid counterexample has P = false in the candidate model. - -- Accepting VBool true (P holds) would promote a non-counterexample to .sat. + -- Require the obligation P (the assertion being checked) to evaluate to what the + -- query asks: false for the validity query, which asserts NOT(P) looking for a + -- counterexample, true for the satisfiability query (`holds`). Accepting the other + -- value would promote a candidate that is no model of the query. let obligationOk := match evalExpr model defMap obligation.obligation with - | some (EvalVal.VBool false) => true + | some (EvalVal.VBool b) => b == holds | _ => false let groundAssumptionsHold := obligation.assumptions.all fun path => path.all fun entry => @@ -1748,7 +1749,8 @@ private def validateNatModel -- AbstractedPhase that promotes concrete-nat unknown candidates to counterexamples. private def natCandidatePhase : Core.AbstractedPhase where name := "natCandidateValidation" - getValidation := fun obligation => .modelToValidate (validateNatModel obligation) + getValidation := fun obligation => .modelToValidate fun holds m => + if validateNatModel obligation holds m then some m else none open Lean.Parser in def verify diff --git a/StrataBooleTest/FeatureRequests/sha256_compact_indexed.lean b/StrataBooleTest/FeatureRequests/sha256_compact_indexed.lean index 692c03b..463cb62 100644 --- a/StrataBooleTest/FeatureRequests/sha256_compact_indexed.lean +++ b/StrataBooleTest/FeatureRequests/sha256_compact_indexed.lean @@ -223,7 +223,8 @@ spec { }; #end -/-- info: +/-- +info: Obligation: Seq_lib_insert_bv32_body_calls_Sequence.take_0 Property: out-of-bounds access check Result: ✅ pass @@ -240,11 +241,11 @@ Obligation: assert_3_3867 Property: assert Result: ✅ pass -Obligation: insertLoopInvAssert_entry_invariant_loop_49_0 +Obligation: insertLoopInvAssert_entry_invariant_loop_59_0 Property: assert Result: ✅ pass -Obligation: insertLoopInvAssert_entry_invariant_loop_49_1 +Obligation: insertLoopInvAssert_entry_invariant_loop_59_1 Property: assert Result: ✅ pass @@ -280,11 +281,11 @@ Obligation: set_res_calls_Sequence.update_4 Property: out-of-bounds access check Result: ✅ pass -Obligation: insertLoopInvAssert_arbitrary_iter_maintain_invariant_loop_49_0 +Obligation: insertLoopInvAssert_arbitrary_iter_maintain_invariant_loop_59_0 Property: assert Result: ✅ pass -Obligation: insertLoopInvAssert_arbitrary_iter_maintain_invariant_loop_49_1 +Obligation: insertLoopInvAssert_arbitrary_iter_maintain_invariant_loop_59_1 Property: assert Result: ✅ pass @@ -324,15 +325,15 @@ Obligation: set_h_calls_Sequence.select_0 Property: out-of-bounds access check Result: ✅ pass -Obligation: insertLoopInvAssert_entry_invariant_loop_50_0 +Obligation: insertLoopInvAssert_entry_invariant_loop_60_0 Property: assert Result: ✅ pass -Obligation: insertLoopInvAssert_entry_invariant_loop_50_1 +Obligation: insertLoopInvAssert_entry_invariant_loop_60_1 Property: assert Result: ✅ pass -Obligation: insertLoopInvAssert_entry_invariant_loop_50_2 +Obligation: insertLoopInvAssert_entry_invariant_loop_60_2 Property: assert Result: ✅ pass @@ -348,7 +349,7 @@ Obligation: callElimAssert_rotate_right_requires_1_3773_3 Property: assert Result: ✅ pass -Obligation: callElimAssert_rotate_right_requires_1_3773_7 +Obligation: callElimAssert_rotate_right_requires_1_3773_8 Property: assert Result: ✅ pass @@ -360,11 +361,11 @@ Obligation: set_w2_calls_Sequence.select_0 Property: out-of-bounds access check Result: ✅ pass -Obligation: callElimAssert_rotate_right_requires_1_3773_11 +Obligation: callElimAssert_rotate_right_requires_1_3773_13 Property: assert Result: ✅ pass -Obligation: callElimAssert_rotate_right_requires_1_3773_15 +Obligation: callElimAssert_rotate_right_requires_1_3773_18 Property: assert Result: ✅ pass @@ -384,15 +385,15 @@ Obligation: set_block_local_calls_Sequence.update_0 Property: out-of-bounds access check Result: ✅ pass -Obligation: callElimAssert_rotate_right_requires_1_3773_19 +Obligation: callElimAssert_rotate_right_requires_1_3773_23 Property: assert Result: ✅ pass -Obligation: callElimAssert_rotate_right_requires_1_3773_23 +Obligation: callElimAssert_rotate_right_requires_1_3773_28 Property: assert Result: ✅ pass -Obligation: callElimAssert_rotate_right_requires_1_3773_27 +Obligation: callElimAssert_rotate_right_requires_1_3773_33 Property: assert Result: ✅ pass @@ -400,27 +401,27 @@ Obligation: set_t1_calls_Sequence.select_0 Property: out-of-bounds access check Result: ✅ pass -Obligation: callElimAssert_rotate_right_requires_1_3773_31 +Obligation: callElimAssert_rotate_right_requires_1_3773_38 Property: assert Result: ✅ pass -Obligation: callElimAssert_rotate_right_requires_1_3773_35 +Obligation: callElimAssert_rotate_right_requires_1_3773_43 Property: assert Result: ✅ pass -Obligation: callElimAssert_rotate_right_requires_1_3773_39 +Obligation: callElimAssert_rotate_right_requires_1_3773_48 Property: assert Result: ✅ pass -Obligation: insertLoopInvAssert_arbitrary_iter_maintain_invariant_loop_50_0 +Obligation: insertLoopInvAssert_arbitrary_iter_maintain_invariant_loop_60_0 Property: assert Result: ✅ pass -Obligation: insertLoopInvAssert_arbitrary_iter_maintain_invariant_loop_50_1 +Obligation: insertLoopInvAssert_arbitrary_iter_maintain_invariant_loop_60_1 Property: assert Result: ✅ pass -Obligation: insertLoopInvAssert_arbitrary_iter_maintain_invariant_loop_50_2 +Obligation: insertLoopInvAssert_arbitrary_iter_maintain_invariant_loop_60_2 Property: assert Result: ✅ pass @@ -432,59 +433,59 @@ Obligation: set_state_out_calls_Sequence.update_1 Property: out-of-bounds access check Result: ✅ pass -Obligation: set_state_out_calls_Sequence.select_0 +Obligation: set_state_out_calls_Sequence.select_0_1 Property: out-of-bounds access check Result: ✅ pass -Obligation: set_state_out_calls_Sequence.update_1 +Obligation: set_state_out_calls_Sequence.update_1_1 Property: out-of-bounds access check Result: ✅ pass -Obligation: set_state_out_calls_Sequence.select_0 +Obligation: set_state_out_calls_Sequence.select_0_2 Property: out-of-bounds access check Result: ✅ pass -Obligation: set_state_out_calls_Sequence.update_1 +Obligation: set_state_out_calls_Sequence.update_1_2 Property: out-of-bounds access check Result: ✅ pass -Obligation: set_state_out_calls_Sequence.select_0 +Obligation: set_state_out_calls_Sequence.select_0_3 Property: out-of-bounds access check Result: ✅ pass -Obligation: set_state_out_calls_Sequence.update_1 +Obligation: set_state_out_calls_Sequence.update_1_3 Property: out-of-bounds access check Result: ✅ pass -Obligation: set_state_out_calls_Sequence.select_0 +Obligation: set_state_out_calls_Sequence.select_0_4 Property: out-of-bounds access check Result: ✅ pass -Obligation: set_state_out_calls_Sequence.update_1 +Obligation: set_state_out_calls_Sequence.update_1_4 Property: out-of-bounds access check Result: ✅ pass -Obligation: set_state_out_calls_Sequence.select_0 +Obligation: set_state_out_calls_Sequence.select_0_5 Property: out-of-bounds access check Result: ✅ pass -Obligation: set_state_out_calls_Sequence.update_1 +Obligation: set_state_out_calls_Sequence.update_1_5 Property: out-of-bounds access check Result: ✅ pass -Obligation: set_state_out_calls_Sequence.select_0 +Obligation: set_state_out_calls_Sequence.select_0_6 Property: out-of-bounds access check Result: ✅ pass -Obligation: set_state_out_calls_Sequence.update_1 +Obligation: set_state_out_calls_Sequence.update_1_6 Property: out-of-bounds access check Result: ✅ pass -Obligation: set_state_out_calls_Sequence.select_0 +Obligation: set_state_out_calls_Sequence.select_0_7 Property: out-of-bounds access check Result: ✅ pass -Obligation: set_state_out_calls_Sequence.update_1 +Obligation: set_state_out_calls_Sequence.update_1_7 Property: out-of-bounds access check Result: ✅ pass @@ -496,11 +497,11 @@ Obligation: compress_pre_compress_requires_16_8638_calls_Sequence.select_0 Property: out-of-bounds access check Result: ✅ pass -Obligation: insertLoopInvAssert_entry_invariant_loop_51_0 +Obligation: insertLoopInvAssert_entry_invariant_loop_61_0 Property: assert Result: ✅ pass -Obligation: insertLoopInvAssert_entry_invariant_loop_51_1 +Obligation: insertLoopInvAssert_entry_invariant_loop_61_1 Property: assert Result: ✅ pass @@ -508,20 +509,21 @@ Obligation: init_calls_Sequence.select_0 Property: out-of-bounds access check Result: ✅ pass -Obligation: callElimAssert_to_u32s_requires_4_4106_42 +Obligation: callElimAssert_to_u32s_requires_4_4106_52 Property: assert Result: ✅ pass -Obligation: callElimAssert_compress_u32_requires_10_5085_47 +Obligation: callElimAssert_compress_u32_requires_10_5085_57 Property: assert Result: ✅ pass -Obligation: insertLoopInvAssert_arbitrary_iter_maintain_invariant_loop_51_0 +Obligation: insertLoopInvAssert_arbitrary_iter_maintain_invariant_loop_61_0 Property: assert Result: ✅ pass -Obligation: insertLoopInvAssert_arbitrary_iter_maintain_invariant_loop_51_1 +Obligation: insertLoopInvAssert_arbitrary_iter_maintain_invariant_loop_61_1 Property: assert -Result: ✅ pass-/ +Result: ✅ pass +-/ #guard_msgs in #eval Strata.Boole.verify "cvc5" sha256_compact_indexed_program (options := .quiet) diff --git a/StrataBooleTest/demo.lean b/StrataBooleTest/demo.lean index ce9dac3..49e84e6 100644 --- a/StrataBooleTest/demo.lean +++ b/StrataBooleTest/demo.lean @@ -40,11 +40,12 @@ theorem loopSimple_smtVCsCorrectBoole : smtVCsCorrectBoole loopSimple := by gen_smt_vcs_boole all_goals (try grind) -/-- info: 'loopSimple_smtVCsCorrectBoole' depends on axioms: [propext, +/-- +info: 'loopSimple_smtVCsCorrectBoole' depends on axioms: [propext, Classical.choice, - Lean.ofReduceBool, - Lean.trustCompiler, Quot.sound, - loopSimple_smtVCsCorrectBoole._genSMTVCsBoole_tcbBridge_1_3]-/ + loopSimple_smtVCsCorrectBoole._genSMTVCsBoole_tcbBridge_1_2, + loopSimple_smtVCsCorrectBoole._native.native_decide.ax_1_1] +-/ #guard_msgs in #print axioms loopSimple_smtVCsCorrectBoole diff --git a/StrataBooleTest/global_readonly_call.lean b/StrataBooleTest/global_readonly_call.lean index dc45ee9..0200124 100644 --- a/StrataBooleTest/global_readonly_call.lean +++ b/StrataBooleTest/global_readonly_call.lean @@ -67,13 +67,13 @@ private def callHelper (p : StrataDDM.Program) : Except String (List String) := match d with | .proc p _ => -- CFG bodies: call extraction not yet implemented for unstructured programs. - let stmts := match p.body with | .structured ss => ss | .cfg _ => [] + let stmts := match p.body with | .structured ss _ => ss | .cfg _ _ | .abstract => [] stmts.findSome? fun | .block _ stmts _ => stmts.findSome? fun - | .cmd (.call pname args _) => + | .cmd (.call pname _ args _) => some s!"call {pname}({", ".intercalate (args.map fmtCallArg)})" | _ => none - | .cmd (.call pname args _) => + | .cmd (.call pname _ args _) => some s!"call {pname}({", ".intercalate (args.map fmtCallArg)})" | _ => none | _ => none @@ -115,49 +115,51 @@ spec /-- info: Except.ok ["call inc(inout(g), inout(z), in(5))"] -/ #guard_msgs in #eval callHelper callerPgm -/-- info: [Strata.Core] Type checking succeeded. +/-- +info: [Strata.Core] Type checking succeeded. VCs: -Label: inc_ensures_1_2593 +Label: inc_ensures_1_2613 Property: assert Assumptions: -inc_requires_0_2575: int.gt(z@1, 0) +inc_requires_0_2595: int.gt(z@1, 0) Obligation: true -Label: callElimAssert_inc_requires_0_2575_6 +Label: callElimAssert_inc_requires_0_2595_6 Property: assert Assumptions: -main_caller_requires_2_2709: z@2 == 10 -main_caller_requires_3_2729: g@2 == 0 +main_caller_requires_2_2729: z@2 == 10 +main_caller_requires_3_2749: g@2 == 0 Obligation: int.gt(z@2, 0) -Label: main_caller_ensures_4_2748 +Label: main_caller_ensures_4_2768 Property: assert Assumptions: -main_caller_requires_2_2709: z@2 == 10 -main_caller_requires_3_2729: g@2 == 0 -callElimAssume_inc_ensures_1_2593_7: g@3 == int.add(int.add(g@2, 5), z@3) +main_caller_requires_2_2729: z@2 == 10 +main_caller_requires_3_2749: g@2 == 0 +$__callElimAssume_inc_ensures_1_2613_7: g@3 == int.add(int.add(g@2, 5), z@3) Obligation: g@3 == 15 --- info: -Obligation: inc_ensures_1_2593 +Obligation: inc_ensures_1_2613 Property: assert Result: ✅ pass -Obligation: callElimAssert_inc_requires_0_2575_6 +Obligation: callElimAssert_inc_requires_0_2595_6 Property: assert Result: ✅ pass -Obligation: main_caller_ensures_4_2748 +Obligation: main_caller_ensures_4_2768 Property: assert Result: ❓ unknown Model: -(g@3, 5) (g@2, 0) (z@2, 10) (z@3, 0)-/ +(g@3, 5) (g@2, 0) (z@2, 10) (z@3, 0) +-/ #guard_msgs in #eval Strata.Boole.verify "cvc5" callerPgm diff --git a/StrataBooleTest/hoare_max2.lean b/StrataBooleTest/hoare_max2.lean index 32d9d9b..292bd9c 100644 --- a/StrataBooleTest/hoare_max2.lean +++ b/StrataBooleTest/hoare_max2.lean @@ -69,7 +69,7 @@ abbrev cond : E := geE (.fvar Core.valueLoc xV intTy) (.fvar Core.valueLoc yV in /-- Metadata and labels of the statements and clauses, read off the program so the shapes below are exact. -/ def max2Body : Core.Statements := - match max2Proc.body with | .structured ss => ss | _ => [] + match max2Proc.body with | .structured ss _ => ss | _ => [] def md4 : Imperative.MetaData Core.Expression := match max2Body with | [.block _ _ md] => md | _ => #[] def md3 : Imperative.MetaData Core.Expression := @@ -83,7 +83,7 @@ theorem max2_body_eq : max2Proc.body = .structured [.block "max2" [.ite (.det cond) [.cmd (.cmd (.set rV (.det (.fvar Core.valueLoc xV intTy)) md1))] - [.cmd (.cmd (.set rV (.det (.fvar Core.valueLoc yV intTy)) md2))] md3] md4] := by + [.cmd (.cmd (.set rV (.det (.fvar Core.valueLoc yV intTy)) md2))] md3] md4] false := by native_decide def lbl0 : Core.CoreLabel := @@ -133,7 +133,7 @@ theorem inputs_of_cond (ρ : Imperative.Env Core.Expression) {b : Bool} some (SemValue.ofBool ρ.factory.model.tcInterp b)) : ρ.factory.factory = Core.Factory ∧ ∃ a c : Int, ρ.store xV = some (intV ρ.factory a) ∧ ρ.store yV = some (intV ρ.factory c) := by - obtain ⟨-, hfac, -, hin⟩ := hpre + obtain ⟨-, hfac, -, hin, -⟩ := hpre refine ⟨hfac, ?_⟩ obtain ⟨vx, hx, hsx⟩ := hin xV (.tcons "int" []) (by rw [max2_inputs]; simp) obtain ⟨vy, hy, hsy⟩ := hin yV (.tcons "int" []) (by rw [max2_inputs]; simp) @@ -192,7 +192,7 @@ theorem max2_post (ρ : Imperative.Env Core.Expression) (a b c : Int) theorem max2_triple : Core.Logic.Hoare.Procedure.contractTriple max2Core params "max2" := by refine Core.Logic.Hoare.Procedure.contractTriple_of_core_typed max2Core params "max2" max2Proc _ - max2_findProc max2_body_eq max2_checksTyped ?_ + max2_findProc max2_body_eq max2_checksTyped ?_ (hmono := by native_decide) rw [max2_factory] -- the procedure block, then the labelled block refine Core.Logic.Hoare.block max2Core.findProcByString? params ?_ diff --git a/docs/HoareLogic.md b/docs/HoareLogic.md index 34c527f..7251b07 100644 --- a/docs/HoareLogic.md +++ b/docs/HoareLogic.md @@ -40,14 +40,14 @@ semantics: snapshots and typed parameters and clauses. Its factory is Core's operators plus the functions declared before the procedure, with or without body (`Program.factoryBeforeProcedure`). Datatype declarations add their constructors, - testers and destructors on Strata main (strata-org/Strata#1502), nothing on this pin. Its + testers and destructors (strata-org/Strata#1502). Its precondition assumes the axioms declared before the procedure (`AxiomsBeforeProcedureDecl`), since strata-org/Strata#1499. - Strata's notion of correctness, `ProcedureAssertsValidOnTraces.denote`: every assertion on every run is valid and the postconditions hold, from entry environments satisfying the axioms declared before the procedure (`AxiomsBeforeProcedureDecl`). - On Strata main the partial triple also asks that the assertions of every finite - execution hold, finished or not, so a proved contract triple gives all of this notion + The partial triple also asks that the assertions of every finite execution hold, + finished or not, so a proved contract triple gives all of this notion (`procedureAssertsValidOnTraces_of_contractTriple`) without a termination premise. The rules kept their signatures; only proofs that unfold the triple change. - Denotational evaluation (since November 2026): `Expression.eval` is `LExpr.denoteEval` @@ -66,9 +66,8 @@ build, on a stable target. 1. **Tactic.** Prove Strata's contract triple. Its precondition has the axioms declared before the procedure, as Strata's notion of correctness assumes them, and a proved - triple gives all of that notion (`procedureAssertsValidOnTraces_of_contractTriple`, on - Strata main; on this pin `contract_of_contractTriple` gives the part about runs that - finish). Apply the rules + triple gives all of that notion (`procedureAssertsValidOnTraces_of_contractTriple`). + Apply the rules backwards and discharge their side conditions: `exitsCoveredByBlocks`, and `PostWF` for a block that declares nothing, by evaluation on the concrete AST; `PostWF` for a block with declarations from `denoteEval_congr`, since a postcondition does not read the @@ -127,13 +126,12 @@ then the benchmark below. - Goals over Lean values come from lifting, not from a monadic encoding, so `Std.Do`/`mvcgen` is off the path. - Failure is never vacuous: a construct the tactic cannot handle leaves its goal open. -- Termination is a separate proof. The tactic proves the partial triple. Strata main has +- Termination is a separate proof. The tactic proves the partial triple. Strata has total-correctness triples since November 2026 (`Core.Logic.HoareTotal`, `Procedure.contractTripleTotal`, a `while_rule` with a natural-number measure), and `TripleWith.of_partial_of_true` gives the total triple from the partial one and a total triple with postcondition `True`. So termination needs only a measure per loop, reuses - the partial proof unchanged, and follows the benchmark. It needs a pin that includes - these triples. + the partial proof unchanged, and follows the benchmark. - Datatypes: keep Strata's approach of stating their laws as conditions on every model, and supply the model from one generic carrier, a single inductive of constructor applications with a well-sortedness predicate (`DT.Carrier`, strata-org/Strata#1493, @@ -154,7 +152,7 @@ then the benchmark below. | `Map`, `Sequence`, `Set`, `string` | constrained in every model; lifting to add (step 2) | | functions, with or without body | in the model | | `axiom` | through `AxiomsBeforeProcedureDecl` (step 1); assumed until step 4 | -| datatypes, `nat` | not in the model on this pin: constructors are unconstrained symbols. Strata main adds constructors, testers and destructors to the visible factory (strata-org/Strata#1502); inversion and induction to add (step 4) | +| datatypes, `nat` | constructors, testers and destructors in the visible factory (strata-org/Strata#1502), with disjointness and injectivity; inversion and induction to add (step 4) | ## Target: `dalek_sum_of_slice` @@ -218,10 +216,8 @@ kernel checks that proof for each program. ## Strata changes for this route This branch pins the `integration/lean-route` branch of the fork: Strata main plus the -pull requests below that are still open, strata-org/Strata#1493 and -strata-org/Strata#1483. The pin returns to strata-org/Strata when they merge. Changes -merged after the pin, among them strata-org/Strata#1502 and the total-correctness triples, -arrive with that bump. +pull requests below that are still open, strata-org/Strata#1501, strata-org/Strata#1493 +and strata-org/Strata#1483. The pin returns to strata-org/Strata when they merge. | Change | State | Used by | | --- | --- | --- | diff --git a/lake-manifest.json b/lake-manifest.json index 38321a9..64a15d5 100644 --- a/lake-manifest.json +++ b/lake-manifest.json @@ -1,61 +1,61 @@ -{"version": "1.2.0", +{"version": "1.3.0", "packagesDir": ".lake/packages", "packages": [{"url": "https://github.com/ufmg-smite/lean-smt", "type": "git", "subDir": null, "scope": "", - "rev": "db545bebe2de1e06dc2df62a6ff6c20e5736bfc0", + "rev": "cbec5bd226c79d80ce0c2d2ea28e1e6359c5f207", "name": "smt", "manifestFile": "lake-manifest.json", - "inputRev": "db545bebe", + "inputRev": "cbec5bd226c79d80ce0c2d2ea28e1e6359c5f207", "inherited": false, "configFile": "lakefile.lean"}, {"url": "https://github.com/kondylidou/Strata", "type": "git", "subDir": null, "scope": "", - "rev": "07dfdf5c8eb98b36ae0189a086ed271ff3a2be45", + "rev": "8699200985076f3eceb29d9b224c3c90768a95ef", "name": "Strata", "manifestFile": "lake-manifest.json", - "inputRev": "07dfdf5c8", + "inputRev": "8699200985076f3eceb29d9b224c3c90768a95ef", "inherited": false, "configFile": "lakefile.toml"}, {"url": "https://github.com/leanprover-community/mathlib4.git", "type": "git", "subDir": null, "scope": "", - "rev": "5ed2965256430c3649e86755f9576b54eca72435", + "rev": "56a005855ea17e0b0958f73ec801ae140b0a1679", "name": "mathlib", "manifestFile": "lake-manifest.json", - "inputRev": "v4.34.0", + "inputRev": "v4.35.0", "inherited": true, "configFile": "lakefile.lean"}, {"url": "https://github.com/abdoo8080/lean-cvc5.git", "type": "git", "subDir": null, "scope": "", - "rev": "41e47796d4d15712e6064b064ca5d251a1283955", + "rev": "d19a134c237ec7f0cb86c2027062eedeb577a9a9", "name": "cvc5", "manifestFile": "lake-manifest.json", - "inputRev": "41e4779", + "inputRev": "d19a134", "inherited": true, "configFile": "lakefile.lean"}, {"url": "https://github.com/leanprover-community/lean-auto.git", "type": "git", "subDir": null, "scope": "", - "rev": "92d628ba41801bd12c9d81f9be12fde97f0ad177", + "rev": "30f46ddb9a68d6878f5a1337eb2565ba4e70126b", "name": "auto", "manifestFile": "lake-manifest.json", - "inputRev": "v4.34.0", + "inputRev": "v4.35.0", "inherited": true, "configFile": "lakefile.lean"}, {"url": "https://github.com/leanprover-community/plausible", "type": "git", "subDir": null, "scope": "leanprover-community", - "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "rev": "dfa4f38190d07c37e315953e08b90fe2d95b3c24", "name": "plausible", "manifestFile": "lake-manifest.json", "inputRev": "main", @@ -65,7 +65,7 @@ "type": "git", "subDir": null, "scope": "", - "rev": "b70e35961b1c8179d278d44fecc8d4101a2ed46a", + "rev": "08511c15d49117eb6108b06593c4b0cfd15e2449", "name": "StrataDDM", "manifestFile": "lake-manifest.json", "inputRev": "main", @@ -75,7 +75,7 @@ "type": "git", "subDir": null, "scope": "leanprover-community", - "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "rev": "d6b4c7be5be75ec4917c873ac50c756dc1436372", "name": "LeanSearchClient", "manifestFile": "lake-manifest.json", "inputRev": "main", @@ -85,7 +85,7 @@ "type": "git", "subDir": null, "scope": "leanprover-community", - "rev": "e928b72544873815af278d38681b31c0293588e3", + "rev": "a41f0e9a4dea23188ea9cc1c41ac9f8bbafe0b93", "name": "importGraph", "manifestFile": "lake-manifest.json", "inputRev": "main", @@ -95,7 +95,7 @@ "type": "git", "subDir": null, "scope": "leanprover-community", - "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "rev": "df72b022e558978a1c50264cfc4d7fec86fa8e04", "name": "proofwidgets", "manifestFile": "lake-manifest.json", "inputRev": "main", @@ -105,7 +105,7 @@ "type": "git", "subDir": null, "scope": "leanprover-community", - "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "rev": "4a174c490d8707121c4a9290800489f105d85e07", "name": "aesop", "manifestFile": "lake-manifest.json", "inputRev": "master", @@ -115,7 +115,7 @@ "type": "git", "subDir": null, "scope": "leanprover-community", - "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "rev": "dce0ad79c486cb1fb504af04f953c3466b0c6db8", "name": "Qq", "manifestFile": "lake-manifest.json", "inputRev": "master", @@ -125,7 +125,7 @@ "type": "git", "subDir": null, "scope": "leanprover-community", - "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "rev": "66e469188fe07963e5cf666c7d4433f45b8131c5", "name": "batteries", "manifestFile": "lake-manifest.json", "inputRev": "main", @@ -135,10 +135,10 @@ "type": "git", "subDir": null, "scope": "leanprover", - "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "rev": "c24fe6078c630e89b489bffe59b3e20ac30d12c8", "name": "Cli", "manifestFile": "lake-manifest.json", - "inputRev": "v4.34.0", + "inputRev": "v4.35.0", "inherited": true, "configFile": "lakefile.toml"}], "name": "StrataBoole", diff --git a/lakefile.toml b/lakefile.toml index e4e92ae..c043eda 100644 --- a/lakefile.toml +++ b/lakefile.toml @@ -9,15 +9,15 @@ weakLeanArgs = ["--tstack=32768"] name = "Strata" # On this branch Strata is the `integration/lean-route` branch of the fork: Strata main # plus the open PRs the Lean route needs (datatype denotation, checked-to-total sequence -# pass). It moves back to strata-org/Strata when they merge. A fixed commit, not a branch -# name, so `lake update` cannot move it. +# pass, the callee's axioms at a call). It moves back to strata-org/Strata when they merge. +# A fixed commit, not a branch name, so `lake update` cannot move it. git = "https://github.com/kondylidou/Strata" -rev = "07dfdf5c8" +rev = "8699200985076f3eceb29d9b224c3c90768a95ef" [[require]] name = "smt" git = "https://github.com/ufmg-smite/lean-smt" -rev = "db545bebe" +rev = "cbec5bd226c79d80ce0c2d2ea28e1e6359c5f207" [[lean_lib]] diff --git a/lean-toolchain b/lean-toolchain index 12359f9..a6aff06 100644 --- a/lean-toolchain +++ b/lean-toolchain @@ -1 +1 @@ -leanprover/lean4:v4.34.0 +leanprover/lean4:v4.35.0 From 984db330e53834165b88d9267e28058e20b8a0aa Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:35:03 +0100 Subject: [PATCH 48/64] Pin Strata main with the evaluation lemmas; use them in place of local copies The pin moves to integration/lean-route 53a3ff3c4: Strata main (6e123aba4) with strata-org/Strata#1483, #1493, #1501, #1506 and #1507. - HoareLift keeps only what Strata lacks: the Boolean connectives now come from Strata's BoolEvalProps. - docs/HoareLogic.md: step 2 lists what is done, in review and left; the target section says which operators the proof of sum_of_slice needs. Co-Authored-By: Claude Fable 5.2 --- StrataBoole/HoareLift.lean | 96 +++------------------------------ StrataBooleTest/hoare_max2.lean | 4 +- docs/HoareLogic.md | 35 ++++++++---- lake-manifest.json | 4 +- lakefile.toml | 5 +- 5 files changed, 38 insertions(+), 106 deletions(-) diff --git a/StrataBoole/HoareLift.lean b/StrataBoole/HoareLift.lean index 4e2e8cc..c847c22 100644 --- a/StrataBoole/HoareLift.lean +++ b/StrataBoole/HoareLift.lean @@ -9,6 +9,7 @@ public import Strata.Languages.Core.Logic.Hoare public import Strata.Languages.Core.Logic.ContractToHoareTripleProps public import Strata.Languages.Core.Logic.HoareCall public import Strata.Languages.Core.IntEvalProps +public import Strata.Languages.Core.BoolEvalProps public import Strata.Languages.Core.InstWellFormedSemanticsEval import all Strata.Languages.Core.Factory import all Strata.DL.Lambda.IntBoolFactory @@ -20,11 +21,11 @@ import all Strata.DL.Lambda.LExprDenoteEval /-! # Lifting lemmas for the Hoare-logic route -Strata evaluates Core expressions denotationally and provides, in -`Strata.Languages.Core.IntEvalProps`, the evaluation of the integer operators, literals, -variables, equality and conditionals. This module adds what the Boole programs need on -top of it: the Boolean connectives `Bool.And` and `Bool.Or`, which Core builds as -short-circuit operators. Step 2 of `docs/HoareLogic.md`. +Strata evaluates Core expressions denotationally and provides the evaluation of the integer +operators, literals, variables, equality and conditionals +(`Strata.Languages.Core.IntEvalProps`) and of the Boolean connectives +(`Strata.Languages.Core.BoolEvalProps`). This module adds what the Boole programs need on +top of them and Strata does not have yet. Step 2 of `docs/HoareLogic.md`. -/ public section @@ -33,91 +34,6 @@ open Lambda Core namespace HoareLift -/-! ## The connectives in `Core.Factory` -/ - -theorem coreFactory_boolAnd : - (Core.Factory)["Bool.And"]? = some (Lambda.boolAndFunc (T := CoreLParams)).func := by - have hmem : (Lambda.boolAndFunc (T := CoreLParams)).func ∈ Core.WFFactoryArray.map (·.func) := by - refine Array.mem_map.mpr ⟨Lambda.boolAndFunc (T := CoreLParams), ?_, rfl⟩ - rw [Array.mem_def] - unfold Core.WFFactoryArray - simp only [Array.toList_appendList] - repeat (first | exact List.Mem.head _ | apply List.Mem.tail) - have hCore : Core.Factory = Lambda.Factory.ofArray (Core.WFFactoryArray.map (·.func)) := rfl - rw [hCore] - exact Lambda.Factory.get?_ofArray_of_mem hmem Core.WFFactoryArray_func_name_nodup - -theorem coreFactory_boolOr : - (Core.Factory)["Bool.Or"]? = some (Lambda.boolOrFunc (T := CoreLParams)).func := by - have hmem : (Lambda.boolOrFunc (T := CoreLParams)).func ∈ Core.WFFactoryArray.map (·.func) := by - refine Array.mem_map.mpr ⟨Lambda.boolOrFunc (T := CoreLParams), ?_, rfl⟩ - rw [Array.mem_def] - unfold Core.WFFactoryArray - simp only [Array.toList_appendList] - repeat (first | exact List.Mem.head _ | apply List.Mem.tail) - have hCore : Core.Factory = Lambda.Factory.ofArray (Core.WFFactoryArray.map (·.func)) := rfl - rw [hCore] - exact Lambda.Factory.get?_ofArray_of_mem hmem Core.WFFactoryArray_func_name_nodup - -/-! ## Their interpretation in every consistent model - -A short-circuit operator's concrete evaluation on two Boolean literals is its truth -table, so every model that is consistent with the factory interprets it that way. -/ - -theorem boolAnd_opInterp_of_lookup {factory : Lambda.Factory CoreLParams} - (model : Lambda.Interp factory) - (hlookup : factory["Bool.And"]? = some (Lambda.boolAndFunc (T := CoreLParams)).func) - (p q : Bool) : - (model.opInterp "Bool.And" (Lambda.LSort.mkArrow .bool [.bool, .bool]) p q : Bool) - = (p && q) := by - have heval : (Lambda.boolAndFunc (T := CoreLParams)).func.concreteEval.bind - (fun ce => ce Core.coreLoc (some ((Lambda.boolAndFunc (T := CoreLParams)).func.instTy Lambda.Subst.empty)) - [.boolConst Core.coreLoc p, .boolConst Core.coreLoc q]) = - some (.boolConst Core.coreLoc (p && q)) := by - cases p <;> rfl - exact (Core.opInterp_of_concreteEval model hlookup rfl heval (fun _ => .int) (fun _ s => - @default _ (@Lambda.SortDenote.instInhabited model.tcInterp model.allInhabited s)) - (.cons (.const rfl) (.cons (.const rfl) .nil)) (.const rfl)).symm - -theorem boolOr_opInterp_of_lookup {factory : Lambda.Factory CoreLParams} - (model : Lambda.Interp factory) - (hlookup : factory["Bool.Or"]? = some (Lambda.boolOrFunc (T := CoreLParams)).func) - (p q : Bool) : - (model.opInterp "Bool.Or" (Lambda.LSort.mkArrow .bool [.bool, .bool]) p q : Bool) - = (p || q) := by - have heval : (Lambda.boolOrFunc (T := CoreLParams)).func.concreteEval.bind - (fun ce => ce Core.coreLoc (some ((Lambda.boolOrFunc (T := CoreLParams)).func.instTy Lambda.Subst.empty)) - [.boolConst Core.coreLoc p, .boolConst Core.coreLoc q]) = - some (.boolConst Core.coreLoc (p || q)) := by - cases p <;> rfl - exact (Core.opInterp_of_concreteEval model hlookup rfl heval (fun _ => .int) (fun _ s => - @default _ (@Lambda.SortDenote.instInhabited model.tcInterp model.allInhabited s)) - (.cons (.const rfl) (.cons (.const rfl) .nil)) (.const rfl)).symm - -/-! ## Their evaluation -/ - -/-- `a && b` evaluates to the conjunction of the Booleans its operands evaluate to. -/ -theorem eval_boolAnd {f : Core.Expression.Factory} {m m' : Core.ExpressionMetadata} - (hlookup : f.factory["Bool.And"]? = some (Lambda.boolAndFunc (T := CoreLParams)).func) - {σ : Core.CoreStore} {x y : Core.Expression.Expr} {p q : Bool} - (hx : Core.Expression.eval f σ x = some (SemValue.ofBool f.model.tcInterp p)) - (hy : Core.Expression.eval f σ y = some (SemValue.ofBool f.model.tcInterp q)) : - Core.Expression.eval f σ (.app m (.app m' Core.boolAndOp x) y) = - some (SemValue.ofBool f.model.tcInterp (p && q)) := - Core.eval_app2_op "Bool.And" (c := .bool) rfl rfl rfl hx hy - (boolAnd_opInterp_of_lookup f.model hlookup p q) - -/-- `a || b` evaluates to the disjunction of the Booleans its operands evaluate to. -/ -theorem eval_boolOr {f : Core.Expression.Factory} {m m' : Core.ExpressionMetadata} - (hlookup : f.factory["Bool.Or"]? = some (Lambda.boolOrFunc (T := CoreLParams)).func) - {σ : Core.CoreStore} {x y : Core.Expression.Expr} {p q : Bool} - (hx : Core.Expression.eval f σ x = some (SemValue.ofBool f.model.tcInterp p)) - (hy : Core.Expression.eval f σ y = some (SemValue.ofBool f.model.tcInterp q)) : - Core.Expression.eval f σ (.app m (.app m' Core.boolOrOp x) y) = - some (SemValue.ofBool f.model.tcInterp (p || q)) := - Core.eval_app2_op "Bool.Or" (c := .bool) rfl rfl rfl hx hy - (boolOr_opInterp_of_lookup f.model hlookup p q) - /-- `x == y` on two integer-valued variables evaluates to the Boolean of their equality. -/ theorem eval_eq_ints (f : Core.Expression.Factory) {m : Core.ExpressionMetadata} {σ : Core.CoreStore} {x y : Core.Expression.Expr} {a b : Int} diff --git a/StrataBooleTest/hoare_max2.lean b/StrataBooleTest/hoare_max2.lean index 292bd9c..37b1434 100644 --- a/StrataBooleTest/hoare_max2.lean +++ b/StrataBooleTest/hoare_max2.lean @@ -13,8 +13,8 @@ The first procedure proved on the Lean route of `docs/HoareLogic.md`: a Boole bl lowered to Core inside Lean, whose contract is proved by applying Core's Hoare rules. Everything the tactic of step 1 will automate is written out once here. Expressions are evaluated denotationally, so the values of variables are semantic values and the -evaluation lemmas of `Strata.Languages.Core.IntEvalProps` and `StrataBoole.HoareLift` -turn each rule's goal into a fact about integers. +evaluation lemmas of `Strata.Languages.Core.IntEvalProps`, `BoolEvalProps` and +`StrataBoole.HoareLift` turn each rule's goal into a fact about integers. -/ open Strata Lambda Core HoareLift diff --git a/docs/HoareLogic.md b/docs/HoareLogic.md index 17ecb5f..2d963a5 100644 --- a/docs/HoareLogic.md +++ b/docs/HoareLogic.md @@ -78,11 +78,20 @@ build, on a stable target. of the `StrataBoole/Deep/` experiment (fork branch `exp/deep-embedding`), retargeted to Strata's `Triple`. 2. **Lifting.** Turn each goal into a proposition over Lean values: a store slot of type - `int` is an `Int`, and evaluating an operator on values is the Lean operation. Done: - Strata's lemmas, plus `Bool.And`, `Bool.Or` and `==` on integers in - `StrataBoole/HoareLift.lean`. To write: the other Boolean connectives, `div` and `mod`, - the `bv` operators and conversions, `Map` and `Sequence` operators (from the factory - axioms), quantifiers, and user functions (a function equals its body in every model). + `int` is an `Int`, and evaluating an operator on values is the Lean operation. These are + lemmas in Strata, next to its `IntEvalProps`. + - Done: the integer operators and comparisons, equality and conditionals. + - In review: the Boolean connectives, `Sequence.length`, `select` and `select!` with the + facts their axioms give in every model, and that the factory of any procedure + resolves the built-ins as `Core.Factory` does (strata-org/Strata#1506); `div` and + `mod` at a non-zero divisor (strata-org/Strata#1507). + - To write: user functions (a function equals its body in every model), the use of a + quantified hypothesis, and the program's axioms as Lean facts. The `bv` operators and + conversions and `Map` follow when a program needs them. + + `StrataBoole/HoareLift.lean` holds what Strata does not have yet, today the Boolean of + an equality between integers. + This is `core_lift` of the same experiment. 3. **Boole entry.** `Strata.Boole.typeCheck` gives the type-checked Core program of a `#strata program Boole` block as a Lean term, and the triple is stated on its @@ -166,11 +175,14 @@ contracts pass `contractChecksTyped`, and caller and callee see the same factory | It uses | Step | | --- | --- | | a `for` loop with six invariants and a `call`, `exit`, `assume`, two declarations without initialiser | 1 | -| integer arithmetic with `div` and `mod`, `&&`, `==>`, `<=` and `as_uint` on `bv W8`, `Sequence` `select`, `select!` and `length`, quantifiers, thirteen functions | 2 | +| `&&`, `==>`, `<=`, `<`, `Sequence` `select` and `length`, a quantified `requires` and invariant, functions to unfold (`Scalar_add_req`, `scalar_congruent_nat` and those they call) | 2 | | 19 axioms, 12 of them the `nat` library's | assumed until 4 | - `nat` is used only through its library and those axioms, so the proof should need no datatype reasoning and does not wait on step 4. +- `as_uint`, `select!` and the byte arithmetic occur only in the body of `u8_32_as_nat`, + which the proof does not open. `Int.Mod` enters through the `nat` library's axiom for + `nat.mod`, not through the procedure. - The callee is trusted. Its body gives the result an arbitrary value and assumes each `ensures` (`assume [trusted_k]`), so a call can run and what the callee promises is its contract. A body `assume false` would also meet the contract, but a call runs the @@ -202,8 +214,8 @@ kernel checks that proof for each program. - `max2` is proved against Strata's triple by hand (`StrataBooleTest/hoare_max2.lean`): `contractTriple_of_core_typed`, then `block`, `block`, `ite` and `set`, side conditions - by `native_decide`, operators lifted with Strata's lemmas and - `StrataBoole/HoareLift.lean`. It is the specification of the tactic for straight-line + by `native_decide`, operators lifted with Strata's lemmas (`IntEvalProps`, + `BoolEvalProps`) and `StrataBoole/HoareLift.lean`. It is the specification of the tactic for straight-line bodies with `if`. The tactic is not started; `Deep/` has one against its own semantics, with `max2` and a counting loop. - What the hand proof settled: under the module system, facts about factory entries need @@ -216,8 +228,9 @@ kernel checks that proof for each program. ## Strata changes for this route This branch pins the `integration/lean-route` branch of the fork: Strata main plus the -pull requests below that are still open, strata-org/Strata#1501, strata-org/Strata#1493 -and strata-org/Strata#1483. The pin returns to strata-org/Strata when they merge. +pull requests below that are still open, strata-org/Strata#1501, strata-org/Strata#1493, +strata-org/Strata#1506, strata-org/Strata#1507 and strata-org/Strata#1483. The pin returns +to strata-org/Strata when they merge. | Change | State | Used by | | --- | --- | --- | @@ -227,6 +240,8 @@ and strata-org/Strata#1483. The pin returns to strata-org/Strata when they merge | strata-org/Strata#1501: the callee's axioms at a call from the caller's entry, and a frame rule for facts about the factory | open | calls in step 1 | | strata-org/Strata#1502: the constructors, testers and destructors of a datatype in the factory visible to a procedure | merged | datatypes in step 4 | | strata-org/Strata#1493: datatypes in the SMT denotation, with the generic carrier | open, in review | the SMT path now, the model of step 4 later | +| strata-org/Strata#1506: evaluation lemmas for sequences and the Boolean connectives, and the built-ins in the factory of any procedure | open | step 2 | +| strata-org/Strata#1507: evaluation lemmas for integer division and remainder | open | step 2 | | strata-org/Strata#1496: `Map` and `Sequence` statements had no execution, and models did not have to satisfy their axioms | closed, fixed upstream by the denotational evaluation | step 2 | | strata-org/Strata#1490: the SMT path refuses the VCs its denotation does not cover | merged | Goal | diff --git a/lake-manifest.json b/lake-manifest.json index 64a15d5..e06e3cf 100644 --- a/lake-manifest.json +++ b/lake-manifest.json @@ -15,10 +15,10 @@ "type": "git", "subDir": null, "scope": "", - "rev": "8699200985076f3eceb29d9b224c3c90768a95ef", + "rev": "53a3ff3c404da9de3cafc24d19082cd3ecce8673", "name": "Strata", "manifestFile": "lake-manifest.json", - "inputRev": "8699200985076f3eceb29d9b224c3c90768a95ef", + "inputRev": "53a3ff3c404da9de3cafc24d19082cd3ecce8673", "inherited": false, "configFile": "lakefile.toml"}, {"url": "https://github.com/leanprover-community/mathlib4.git", diff --git a/lakefile.toml b/lakefile.toml index c043eda..5b48470 100644 --- a/lakefile.toml +++ b/lakefile.toml @@ -9,10 +9,11 @@ weakLeanArgs = ["--tstack=32768"] name = "Strata" # On this branch Strata is the `integration/lean-route` branch of the fork: Strata main # plus the open PRs the Lean route needs (datatype denotation, checked-to-total sequence -# pass, the callee's axioms at a call). It moves back to strata-org/Strata when they merge. +# pass, the callee's axioms at a call, evaluation lemmas). It moves back to +# strata-org/Strata when they merge. # A fixed commit, not a branch name, so `lake update` cannot move it. git = "https://github.com/kondylidou/Strata" -rev = "8699200985076f3eceb29d9b224c3c90768a95ef" +rev = "53a3ff3c404da9de3cafc24d19082cd3ecce8673" [[require]] name = "smt" From 40d7628d58454aba52dfc4be1165f40f97a407fb Mon Sep 17 00:00:00 2001 From: Lydia Kondylidou <33327056+kondylidou@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:56:27 +0100 Subject: [PATCH 49/64] Lift a quantified clause by hand, as the recipe for the lifting tactic --- StrataBoole/HoareLift.lean | 24 ++++- StrataBooleTest.lean | 1 + StrataBooleTest/hoare_lift_forall.lean | 132 +++++++++++++++++++++++++ docs/HoareLogic.md | 30 ++++-- 4 files changed, 180 insertions(+), 7 deletions(-) create mode 100644 StrataBooleTest/hoare_lift_forall.lean diff --git a/StrataBoole/HoareLift.lean b/StrataBoole/HoareLift.lean index c847c22..837aa29 100644 --- a/StrataBoole/HoareLift.lean +++ b/StrataBoole/HoareLift.lean @@ -25,7 +25,10 @@ Strata evaluates Core expressions denotationally and provides the evaluation of operators, literals, variables, equality and conditionals (`Strata.Languages.Core.IntEvalProps`) and of the Boolean connectives (`Strata.Languages.Core.BoolEvalProps`). This module adds what the Boole programs need on -top of them and Strata does not have yet. Step 2 of `docs/HoareLogic.md`. +top of them and Strata does not have yet: the Boolean of an integer equality +(`eval_eq_ints`), reading a variable of the store inside a denotation (`fvarVal_of_store`), +and a function as its body from a factory lookup (`opInterp_of_body`). Step 2 of +`docs/HoareLogic.md`; `StrataBooleTest/hoare_lift_forall.lean` is a worked example. -/ public section @@ -45,6 +48,25 @@ theorem eval_eq_ints (f : Core.Expression.Factory) {m : Core.ExpressionMetadata} simpa using Core.eval_eq_true f hx hy · simpa [hab] using Core.eval_eq_false f hx hy rfl (fun h => hab (SemValue.ofInt_injective h)) +/-- **Reading the store.** The valuation a store gives reads a variable as the value the + store binds it to. -/ +theorem fvarVal_of_store {tc : TyConstrInterp} [TyConstrInterp.AllInhabited tc] + {σ : Core.CoreStore} {x : Core.Expression.Ident} {s : LSort} {v : SortDenote tc s} + (hx : σ x = some ⟨tc, s, v⟩) : + ValStore.fvarVal (T := Core.CoreLParams) tc σ x s = v := by + simp [ValStore.fvarVal, hx, SemValue.read] + +/-- **A function is its body.** In every model of a factory that resolves `n` to a function + with body `body`, the function's interpretation at any arguments is the denotation of the + body with the parameters bound to those arguments (`LFunc.InterpConsistentBody`). -/ +theorem opInterp_of_body {F : Lambda.Factory Core.CoreLParams} (model : Lambda.Interp F) + {n : String} {fn : LFunc Core.CoreLParams} (hlookup : F[n]? = some fn) + {body : LExpr Core.CoreLParams.mono} (hbody : fn.body = some body) : + LFunc.InterpConsistentBody model.tcInterp model.opInterp fn body := by + have h := model.interpConsistent.1 n (Factory.getElem?_some_implies_mem hlookup) body + (by rw [Factory.getElem?_some_getElem hlookup]; exact hbody) + rwa [Factory.getElem?_some_getElem hlookup] at h + end HoareLift end -- public section diff --git a/StrataBooleTest.lean b/StrataBooleTest.lean index 76c3f5a..5e0e9e7 100644 --- a/StrataBooleTest.lean +++ b/StrataBooleTest.lean @@ -64,6 +64,7 @@ import StrataBooleTest.FeatureRequests.scalar_reduce import StrataBooleTest.FeatureRequests.seq_empty_literal import StrataBooleTest.FeatureRequests.sha256_compact_indexed import StrataBooleTest.CoreTests.DefineFunRecTests +import StrataBooleTest.hoare_lift_forall import StrataBooleTest.hoare_max2 import StrataBooleTest.dalek_sum_of_slice import StrataBooleTest.generic_datatypes diff --git a/StrataBooleTest/hoare_lift_forall.lean b/StrataBooleTest/hoare_lift_forall.lean new file mode 100644 index 0000000..07fbf5c --- /dev/null +++ b/StrataBooleTest/hoare_lift_forall.lean @@ -0,0 +1,132 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +module + +public import StrataBoole.HoareLift +public import Strata.Languages.Core.SeqEvalProps +public import Strata.DL.Lambda.LExprDenoteEvalProps +import all Strata.DL.Lambda.Denote.LExprDenote +import all Strata.DL.Lambda.Denote.LExprDenoteCompute +import all Strata.DL.Lambda.Denote.LExprAnnotated +import all Strata.DL.Lambda.LExprDenoteEval +import all Strata.DL.Lambda.LExprWF + +/-! # Lifting a quantified clause: a worked example + +A contract clause of the Hoare-logic route is a Core expression that evaluates to `true` +in a store. Lifting turns that fact into a proposition over Lean values. This file does it +by hand, once, for the clause + + forall j : int :: 0 <= j && j < Sequence.length(s) ==> ok(Sequence.select(s, j)) + +which has the shape of the quantified `requires` and loop invariant of +`dalek_sum_of_slice`, with a user function `ok` in the place of `is_canonical_scalar`. +`all_lift` concludes that `ok` holds of every element of the sequence in range. + +The five steps of its proof are the ones a lifting tactic has to automate +(step 2 of `docs/HoareLogic.md`): + +1. evaluation to `true` is the denotation being `true` (`LExpr.denoteEval_eq_ofBool_iff`); +2. the store types the variables as the clause does, so annotating changes nothing + (`LExpr.annotateFvars_eq_self`); +3. the `denotes` tactic computes the denotation: a quantifier becomes a Lean `∀`, and the + body a term in the model's operators (`denote_true_iff_of_Denotes`); +4. a variable read from the store is the value the store holds + (`HoareLift.fvarVal_of_store`); +5. the built-in operators are their Lean operations (the `_opInterp_of_lookup` lemmas of + Strata's `IntEvalProps` and `BoolEvalProps`). + +A user function stays an operator of the model here. `HoareLift.opInterp_of_body` replaces +it by its body where a proof needs that. + +The `denotes` tactic and its lemmas are internal to Strata's denotation modules, so lifting +code has to live in a module that imports them with `import all`, as this file does. +-/ + +public section + +namespace HoareLiftForall + +open Lambda + +abbrev L := Core.valueLoc +abbrev seqInt : LMonoTy := .tcons "Sequence" [LMonoTy.int] +abbrev sId : Core.Expression.Ident := ⟨"s", ()⟩ +abbrev sV : Core.Expression.Expr := .fvar L sId (some seqInt) +abbrev b0 : Core.Expression.Expr := .bvar L 0 +abbrev opE (n : String) (ty : LMonoTy) : Core.Expression.Expr := .op L ⟨n, ()⟩ (some ty) +abbrev bool2 : LMonoTy := .arrow .bool (.arrow .bool .bool) +abbrev int2b : LMonoTy := .arrow LMonoTy.int (.arrow LMonoTy.int .bool) + +/-- `0 <= j && j < length(s) ==> ok(select(s, j))`, under the binder of `j`. -/ +abbrev allBody : Core.Expression.Expr := + .app L (.app L (opE "Bool.Implies" bool2) + (.app L (.app L (opE "Bool.And" bool2) + (.app L (.app L (opE "Int.Le" int2b) (.intConst L 0)) b0)) + (.app L (.app L (opE "Int.Lt" int2b) b0) + (.app L (opE "Sequence.length" (.arrow seqInt LMonoTy.int)) sV)))) + (.app L (opE "ok" (.arrow LMonoTy.int .bool)) + (.app L (.app L (opE "Sequence.select" (.arrow seqInt (.arrow LMonoTy.int LMonoTy.int))) sV) b0)) + +abbrev allE : Core.Expression.Expr := .quant L .all "j" (some LMonoTy.int) b0 allBody + +/-- **A quantified clause as a Lean `∀`.** If the clause evaluates to `true` in a store that + binds `s` to the sequence `sv`, then `ok` holds of every element of `sv` in range. -/ +theorem all_lift (Fm : Core.Expression.Factory) (σ : Core.CoreStore) + (himp : Fm.factory["Bool.Implies"]? = some (Lambda.boolImpliesFunc (T := Core.CoreLParams)).func) + (hand : Fm.factory["Bool.And"]? = some (Lambda.boolAndFunc (T := Core.CoreLParams)).func) + (hle : Fm.factory["Int.Le"]? = some (Lambda.intLeFunc (T := Core.CoreLParams)).func) + (hlt : Fm.factory["Int.Lt"]? = some (Lambda.intLtFunc (T := Core.CoreLParams)).func) + (sv : SortDenote Fm.model.tcInterp (.tcons "Sequence" [.int])) + (hs : σ sId = some ⟨Fm.model.tcInterp, .tcons "Sequence" [.int], sv⟩) + (h : Core.Expression.eval Fm σ allE = some (SemValue.ofBool Fm.model.tcInterp true)) : + ∀ j : Int, 0 ≤ j → j < Core.seqLengthOf Fm.model .int sv → + (Fm.model.opInterp "ok" (LSort.mkArrow .bool [.int]) + (Core.seqSelectOf Fm.model .int sv j) : Bool) = true := by + -- 1. Evaluation to `true` is the denotation being `true`. + obtain ⟨hdef, hty, hden⟩ := (LExpr.denoteEval_eq_ofBool_iff (T := Core.CoreLParams)).mp h + -- 2. The store types `s` as the clause does, so its annotation changes nothing. + have hann : allE.annotateFvars (ValStore.ann σ) = allE := + LExpr.annotateFvars_eq_self allE (by + intro x ty hx + simp only [LExpr.freeVars, List.mem_append, List.mem_cons, List.not_mem_nil, or_false, + Prod.mk.injEq, or_self, List.nil_append] at hx + obtain ⟨rfl, rfl⟩ := hx + exact ⟨seqInt, rfl, by simp only [ValStore.ann, hs, Option.map_some]; rfl⟩) + revert hty hden + rw [hann] + intro hty hden + letI := Fm.model.allInhabited + -- 3. The quantifier is a Lean `∀`; its body is a term in the model's operators. + have hv := Eq.mp (denote_true_iff_of_Denotes (by denotes)) hden + rw [classical_decide_eq_true] at hv + intro j h0 hj + have hb := Eq.mp (denote_true_iff_of_Denotes (by denotes)) (hv j) + -- 4. The store read of `s` is the sequence it holds. + have hfv : ValStore.fvarVal (T := Core.CoreLParams) Fm.model.tcInterp σ sId + (LSort.tcons "Sequence" [LSort.int]) = sv := HoareLift.fvarVal_of_store hs + dsimp only [LMonoTy.substTyVars, LMonoTy.substTyVars.map, denoteConst, LConst.ty] at hb + rw [hfv] at hb + -- 5. The built-in operators are their Lean operations. + have e1 := Core.intLe_opInterp_of_lookup Fm.model hle 0 j + have e2 := Core.intLt_opInterp_of_lookup Fm.model hlt j (Core.seqLengthOf Fm.model .int sv) + have e3 := Core.boolAnd_opInterp_of_lookup Fm.model hand (decide (0 ≤ j)) + (decide (j < Core.seqLengthOf Fm.model .int sv)) + have e4 := Core.boolImplies_opInterp_of_lookup Fm.model himp + (decide (0 ≤ j) && decide (j < Core.seqLengthOf Fm.model .int sv)) + (Fm.model.opInterp "ok" (LSort.mkArrow .bool [.int]) (Core.seqSelectOf Fm.model .int sv j)) + dsimp only [LSort.mkArrow, List.foldr, Core.seqLengthOf, Core.seqSelectOf, LSort.int, + LSort.bool] at e1 e2 e3 e4 hb ⊢ + rw [e1, e2, e3, e4] at hb + have h0' : decide (0 ≤ j) = true := decide_eq_true h0 + have hj' := decide_eq_true hj + dsimp only [Core.seqLengthOf, LSort.mkArrow, List.foldr, LSort.int] at hj' + rw [h0', hj'] at hb + exact hb + +end HoareLiftForall + +end -- public section diff --git a/docs/HoareLogic.md b/docs/HoareLogic.md index 2d963a5..c03a3f7 100644 --- a/docs/HoareLogic.md +++ b/docs/HoareLogic.md @@ -85,12 +85,30 @@ build, on a stable target. facts their axioms give in every model, and that the factory of any procedure resolves the built-ins as `Core.Factory` does (strata-org/Strata#1506); `div` and `mod` at a non-zero divisor (strata-org/Strata#1507). - - To write: user functions (a function equals its body in every model), the use of a - quantified hypothesis, and the program's axioms as Lean facts. The `bv` operators and - conversions and `Map` follow when a program needs them. - - `StrataBoole/HoareLift.lean` holds what Strata does not have yet, today the Boolean of - an equality between integers. + - In `StrataBoole/HoareLift.lean`, until Strata has them: the Boolean of an integer + equality, reading a variable of the store inside a denotation, and a function as its + body from a factory lookup. + - The `bv` operators and conversions and `Map` follow when a program needs them. + + Lifting a clause takes five steps, done by hand once in + `StrataBooleTest/hoare_lift_forall.lean` for a quantified clause of the shape + `dalek_sum_of_slice` has: + 1. evaluation to `true` is the denotation being `true` + (`LExpr.denoteEval_eq_ofBool_iff`); + 2. the store types the variables as the clause does, so annotating changes nothing + (`LExpr.annotateFvars_eq_self`); + 3. Strata's `denotes` tactic computes the denotation: a quantifier becomes a Lean `∀`, + the body a term in the model's operators; + 4. a variable read from the store is the value the store holds + (`HoareLift.fvarVal_of_store`); + 5. the built-in operators are their Lean operations (the `_opInterp_of_lookup` lemmas), + and a user function is its body where the proof needs it + (`HoareLift.opInterp_of_body`). + + So the lemmas for the benchmark are there once the two pull requests merge, and what is + left of this step is the tactic that runs the five steps. Its code has to live in a + module that imports Strata's denotation modules with `import all`, since `denotes` and + its lemmas are internal to them. This is `core_lift` of the same experiment. 3. **Boole entry.** `Strata.Boole.typeCheck` gives the type-checked Core program of a From 08502b59d92137a808dbcb5bc4cd31a500b5f3c0 Mon Sep 17 00:00:00 2001 From: Stephanie Ma Date: Mon, 30 Nov 2026 07:10:59 -0800 Subject: [PATCH 50/64] Hoare route: follow the denotational Core semantics; boole_reflect and core_reflect; remove the Deep prototype The merge of feat/hoare-logic moved Strata to d68fdcb6e, where a statement evaluates its expressions denotationally, in the model of the runtime factory. - Hoare/Lift: the evaluation lemmas are restated over that factory (Eval.lean), with a bridge from an evaluation to `LExpr.denote` (Denote.lean). Contract, Rules, WP and Tactic follow. - Boolean parameters and the value of a `havoc` are read: hoare_havoc_core replaces hoare_havoc_gap. - `shallow_reflect` becomes `boole_reflect`; `core_reflect` does the same for a program in Core syntax. The delaborators move to HoareLogic/Delab.lean. - The Deep prototype (HoareLogic/Deep and its tests) is removed. --- StrataBoole.lean | 19 +- StrataBoole/HoareLogic/Deep/Exec.lean | 254 --- StrataBoole/HoareLogic/Deep/Lang.lean | 238 --- StrataBoole/HoareLogic/Deep/Spec.lean | 257 --- StrataBoole/HoareLogic/Deep/Tactic.lean | 279 ---- StrataBoole/HoareLogic/Deep/Triple.lean | 90 -- StrataBoole/HoareLogic/{Deep => }/Delab.lean | 13 +- StrataBoole/HoareLogic/Hoare/Contract.lean | 411 +++-- StrataBoole/HoareLogic/Hoare/Lift/Denote.lean | 1382 +++++++---------- StrataBoole/HoareLogic/Hoare/Lift/Eval.lean | 1262 ++++++--------- StrataBoole/HoareLogic/Hoare/Proj.lean | 60 +- StrataBoole/HoareLogic/Hoare/Rules.lean | 261 +--- StrataBoole/HoareLogic/Hoare/Tactic.lean | 659 ++++---- StrataBoole/HoareLogic/Hoare/WP.lean | 260 ++-- StrataBoole/HoareLogic/Lift/Names.lean | 15 +- StrataBoole/HoareLogic/Pipeline.lean | 60 +- StrataBoole/HoareLogic/Reflect/Boole.lean | 21 +- StrataBoole/HoareLogic/Reflect/Core.lean | 112 +- StrataBoole/HoareLogic/Reflect/ToExpr.lean | 102 +- StrataBoole/HoareLogic/Reflect/TypeCheck.lean | 27 +- StrataBooleTest.lean | 8 +- StrataBooleTest/HoareLogic/boole_globals.lean | 22 +- ...hallow_reflect.lean => boole_reflect.lean} | 42 +- StrataBooleTest/HoareLogic/deep_count_up.lean | 72 - StrataBooleTest/HoareLogic/deep_max2.lean | 116 -- StrataBooleTest/HoareLogic/deep_nondet.lean | 77 - StrataBooleTest/HoareLogic/deep_quant.lean | 117 -- StrataBooleTest/HoareLogic/demo_pipeline.lean | 77 +- .../HoareLogic/hoare_find_max_core.lean | 38 +- .../HoareLogic/hoare_frame_core.lean | 22 +- .../HoareLogic/hoare_havoc_core.lean | 168 ++ .../HoareLogic/hoare_havoc_gap.lean | 46 - .../HoareLogic/hoare_locals_core.lean | 4 +- .../HoareLogic/hoare_nondet_core.lean | 16 +- .../HoareLogic/hoare_ops_core.lean | 78 +- .../HoareLogic/hoare_quant_core.lean | 28 +- docs/HoareLogic.md | 2 - 37 files changed, 2269 insertions(+), 4446 deletions(-) delete mode 100644 StrataBoole/HoareLogic/Deep/Exec.lean delete mode 100644 StrataBoole/HoareLogic/Deep/Lang.lean delete mode 100644 StrataBoole/HoareLogic/Deep/Spec.lean delete mode 100644 StrataBoole/HoareLogic/Deep/Tactic.lean delete mode 100644 StrataBoole/HoareLogic/Deep/Triple.lean rename StrataBoole/HoareLogic/{Deep => }/Delab.lean (98%) rename StrataBooleTest/HoareLogic/{shallow_reflect.lean => boole_reflect.lean} (80%) delete mode 100644 StrataBooleTest/HoareLogic/deep_count_up.lean delete mode 100644 StrataBooleTest/HoareLogic/deep_max2.lean delete mode 100644 StrataBooleTest/HoareLogic/deep_nondet.lean delete mode 100644 StrataBooleTest/HoareLogic/deep_quant.lean create mode 100644 StrataBooleTest/HoareLogic/hoare_havoc_core.lean delete mode 100644 StrataBooleTest/HoareLogic/hoare_havoc_gap.lean diff --git a/StrataBoole.lean b/StrataBoole.lean index 2037080..0d505b3 100644 --- a/StrataBoole.lean +++ b/StrataBoole.lean @@ -39,11 +39,9 @@ The Hoare-logic route in `docs/HoareLogic.md` does not build on it. ### `import StrataBoole.HoareLogic.Pipeline` `boole_prove pgm proc` proves in Lean the contract of the procedure `proc` of the Boole program -`pgm`: it binds the program's Core AST (`shallow_reflect`), then states and proves -`proc_contract : Core.Logic.Hoare.Procedure.contractTriple pgm_ast params "proc"` and -`proc_correct : Strata.Deep.Procedure.Correct proc_ast`, closing each verification condition -with `omega`, then `grind`. `boole_prove pgm proc strata` or `… deep` proves one of the two, and -`… with tac` closes the conditions with `tac`. +`pgm`: it binds the program's Core AST (`boole_reflect`), then states and proves +`proc_contract : Core.Logic.Hoare.Procedure.contractTriple pgm_ast params "proc"`, closing each +verification condition with `omega`, then `grind`. `… with tac` closes the conditions with `tac`. ### `import StrataBoole.HoareLogic.Hoare.Tactic` @@ -53,18 +51,11 @@ weakest-precondition rules proved from Strata's (`Hoare/Rules.lean`, `Proj.lean` tactics `hoare_contract`, `hoare_vcs` and `hoare_lift`, which turn `Procedure.contractTriple` into verification conditions over `Int` and `Bool`, named after the program's clauses. -### `import StrataBoole.HoareLogic.Deep.Tactic` - -A deep embedding of Core's structured statements with a big-step semantics of its own -(`Deep/Exec.lean`), rules proved about it, and the tactics `core_vcgen` and `core_lift`. It leaves -the same conditions as the Hoare-logic route and serves as a cross-check; nothing connects it to -Core's semantics. - ### `import StrataBoole.HoareLogic.Reflect.Boole` -`shallow_reflect p` binds the type-checked Core program of the Boole program `p` to +`boole_reflect p` binds the type-checked Core program of the Boole program `p` to `

_ast : Core.Program` and each of its procedures to `_ast : Core.Procedure`, as terms -the kernel can reduce. `#core_reflect` (`StrataBoole.HoareLogic.Reflect.Core`) does the same +the kernel can reduce. `core_reflect` (`StrataBoole.HoareLogic.Reflect.Core`) does the same for a program written in Core syntax. ### `import StrataBoole.MetaVerifier` diff --git a/StrataBoole/HoareLogic/Deep/Exec.lean b/StrataBoole/HoareLogic/Deep/Exec.lean deleted file mode 100644 index 02c73f4..0000000 --- a/StrataBoole/HoareLogic/Deep/Exec.lean +++ /dev/null @@ -1,254 +0,0 @@ -/- - Copyright Strata Contributors - - SPDX-License-Identifier: Apache-2.0 OR MIT --/ -module - -public import StrataBoole.HoareLogic.Deep.Lang - -/-! # Deep embedding of Core: big-step semantics - -`Exec ss σ o` says that running the statement list `ss` from `σ` can end with outcome -`o`. It is the ground truth of the deep embedding: the triple (`Deep/Triple.lean`) is -defined from it, and every proof rule (`Deep/Spec.lean`) is a theorem about it. - -* **Failure is an outcome.** A run ends in `.failure` when a check fails: an `assert`, - a loop invariant, or a `decreases` obligation. It also fails when it meets an - expression or a statement outside the fragment. A triple rules out failure, so it - covers every assertion in the program. -* **`assume` discards runs.** `assume e` has no outcome when `e` is false. -* **Loops are checked the way Core checks them.** Each time control reaches the loop - head, every invariant must hold and the measure must be a non-negative integer. - After each iteration of the body, the measure must have decreased. -* **Only terminating runs are described**, so the triple is partial correctness. The - `decreases` checks are still enforced on every iteration a run makes. -* **Nondeterministic control is every choice.** `if (*)` runs either branch and `while (*)` - any number of iterations, with the same head checks as a guarded loop; `cover` is a skip. --/ - -@[expose] public section - -namespace Strata.Deep - -open Imperative - -/-! ## Outcomes -/ - -/-- How a run ends: normally in a state, or with a failed check. -/ -inductive Outcome where - | normal (σ : State) - | failure - -/-- `Q` holds of a normal outcome. A failure satisfies no postcondition. -/ -def Outcome.Sat (Q : State → Prop) : Outcome → Prop - | .normal σ => Q σ - | .failure => False - -/-! ## The fragment -/ - -/-- The statement forms the semantics covers. Every other form (calls, `cover`, `exit`, -nondeterministic guards, type declarations) fails, so a triple about a program that -uses one cannot be proved. -/ -def Supported : Core.Statement → Prop - | .cmd (.cmd (.init _ _ _ _)) => True - | .cmd (.cmd (.set _ _ _)) => True - | .cmd (.cmd (.assert _ _ _)) => True - | .cmd (.cmd (.assume _ _ _)) => True - | .cmd (.cmd (.cover _ _ _)) => True - | .ite _ _ _ _ => True - | .block _ _ _ => True - | .loop _ _ _ _ _ => True - | _ => False - -mutual -/-- The variables a statement may assign: the targets of `var`, `:=` and `havoc`, -including those in nested blocks. -/ -def Stmt.mods : Core.Statement → List String - | .cmd (.cmd (.init x _ _ _)) => [x.name] - | .cmd (.cmd (.set x _ _)) => [x.name] - | .ite _ t f _ => Block.mods t ++ Block.mods f - | .block _ b _ => Block.mods b - | .loop _ _ _ b _ => Block.mods b - | _ => [] - -/-- The variables a statement list may assign. -/ -def Block.mods : List Core.Statement → List String - | [] => [] - | s :: ss => Stmt.mods s ++ Block.mods ss -end - -/-- `σ` with each variable of `xs` replaced by its value in `τ`. A loop's head states are -of this form, with `xs` the variables its body may assign. -/ -def State.havoc (σ : State) (xs : List String) (τ : State) : State := - fun y => if y ∈ xs then τ y else σ y - -/-! ## Loop checks -/ - -/-- `P`, carrying the label `l` of the program clause it comes from. The label is only a name -for the reader of a verification condition: `Labeled l P` unfolds to `P`. -/ -def Labeled (_l : String) (P : Prop) : Prop := P - -/-- Every invariant holds, each under its label. -/ -def InvsHold : List (String × Expr) → State → Prop - | [], _ => True - | (l, e) :: invs, σ => Labeled l (Holds σ e) ∧ InvsHold invs σ - -/-- The measure, if there is one, is a non-negative integer. -/ -def MeasureNonneg : Option Expr → State → Prop - | none, _ => True - | some e, σ => - match evalInt σ e with - | some k => 0 ≤ k - | none => False - -/-- The measure, if there is one, is smaller in `σ'` (after an iteration) than in `σ` -(before it). -/ -def MeasureDecreased : Option Expr → State → State → Prop - | none, _, _ => True - | some e, σ, σ' => - match evalInt σ e, evalInt σ' e with - | some k, some k' => k' < k - | _, _ => False - -/-- What Core checks whenever control reaches a loop head (`loop_entry` in the CFG Core -lowers loops to): the invariants, then the lower bound of the measure. -/ -def LoopHead (invs : List (String × Expr)) (m : Option Expr) (σ : State) : Prop := - InvsHold invs σ ∧ MeasureNonneg m σ - -/-! ## Execution -/ - -/-- `Exec ss σ o`: running `ss` from `σ` can end with outcome `o`. Each compound -statement has one constructor for a normal run of its body, followed by the rest of the -list, and one for a body that fails. -/ -inductive Exec : List Core.Statement → State → Outcome → Prop where - | nil : Exec [] σ (.normal σ) - -- `x := e` - | set (he : eval σ e = some v) (k : Exec ss (σ.update x.name v) o) : - Exec (.cmd (.cmd (.set x (.det e) md)) :: ss) σ o - | set_fail (he : eval σ e = none) : - Exec (.cmd (.cmd (.set x (.det e) md)) :: ss) σ .failure - -- `havoc x` - | havoc (k : Exec ss (σ.update x.name v) o) : - Exec (.cmd (.cmd (.set x .nondet md)) :: ss) σ o - -- `var x : T := e` - | init (he : eval σ e = some v) (k : Exec ss (σ.update x.name v) o) : - Exec (.cmd (.cmd (.init x ty (.det e) md)) :: ss) σ o - | init_fail (he : eval σ e = none) : - Exec (.cmd (.cmd (.init x ty (.det e) md)) :: ss) σ .failure - -- `var x : T` - | init_havoc (k : Exec ss (σ.update x.name v) o) : - Exec (.cmd (.cmd (.init x ty .nondet md)) :: ss) σ o - -- `assert e` - | assert (he : Holds σ e) (k : Exec ss σ o) : - Exec (.cmd (.cmd (.assert l e md)) :: ss) σ o - | assert_fail (he : ¬ Holds σ e) : - Exec (.cmd (.cmd (.assert l e md)) :: ss) σ .failure - -- `assume e` - | assume (he : MayHold σ e) (k : Exec ss σ o) : - Exec (.cmd (.cmd (.assume l e md)) :: ss) σ o - -- `cover e`: a skip - | cover (k : Exec ss σ o) : - Exec (.cmd (.cmd (.cover l e md)) :: ss) σ o - -- `if (c) { t } else { f }` - | ite_true (hc : evalBool σ c = some true) (ht : Exec t σ (.normal σ')) (k : Exec ss σ' o) : - Exec (.ite (.det c) t f md :: ss) σ o - | ite_true_fail (hc : evalBool σ c = some true) (ht : Exec t σ .failure) : - Exec (.ite (.det c) t f md :: ss) σ .failure - | ite_false (hc : evalBool σ c = some false) (hf : Exec f σ (.normal σ')) (k : Exec ss σ' o) : - Exec (.ite (.det c) t f md :: ss) σ o - | ite_false_fail (hc : evalBool σ c = some false) (hf : Exec f σ .failure) : - Exec (.ite (.det c) t f md :: ss) σ .failure - | ite_fail (hc : evalBool σ c = none) : - Exec (.ite (.det c) t f md :: ss) σ .failure - -- `if (*) { t } else { f }`: either branch - | ite_nondet_true (ht : Exec t σ (.normal σ')) (k : Exec ss σ' o) : - Exec (.ite .nondet t f md :: ss) σ o - | ite_nondet_true_fail (ht : Exec t σ .failure) : - Exec (.ite .nondet t f md :: ss) σ .failure - | ite_nondet_false (hf : Exec f σ (.normal σ')) (k : Exec ss σ' o) : - Exec (.ite .nondet t f md :: ss) σ o - | ite_nondet_false_fail (hf : Exec f σ .failure) : - Exec (.ite .nondet t f md :: ss) σ .failure - -- `{ b }`; variables declared in `b` stay visible after it - | block (hb : Exec b σ (.normal σ')) (k : Exec ss σ' o) : - Exec (.block l b md :: ss) σ o - | block_fail (hb : Exec b σ .failure) : - Exec (.block l b md :: ss) σ .failure - -- `while (g) decreases m invariant invs { b }` - | loop_head_fail (hh : ¬ LoopHead invs m σ) : - Exec (.loop (.det g) m invs b md :: ss) σ .failure - | loop_guard_fail (hh : LoopHead invs m σ) (hg : evalBool σ g = none) : - Exec (.loop (.det g) m invs b md :: ss) σ .failure - | loop_exit (hh : LoopHead invs m σ) (hg : evalBool σ g = some false) - (k : Exec ss σ o) : - Exec (.loop (.det g) m invs b md :: ss) σ o - | loop_body_fail (hh : LoopHead invs m σ) (hg : evalBool σ g = some true) - (hb : Exec b σ .failure) : - Exec (.loop (.det g) m invs b md :: ss) σ .failure - | loop_measure_fail (hh : LoopHead invs m σ) (hg : evalBool σ g = some true) - (hb : Exec b σ (.normal σ')) (hd : ¬ MeasureDecreased m σ σ') : - Exec (.loop (.det g) m invs b md :: ss) σ .failure - | loop_iter (hh : LoopHead invs m σ) (hg : evalBool σ g = some true) - (hb : Exec b σ (.normal σ')) (hd : MeasureDecreased m σ σ') - (k : Exec (.loop (.det g) m invs b md :: ss) σ' o) : - Exec (.loop (.det g) m invs b md :: ss) σ o - -- `while (*) decreases m invariant invs { b }`: any number of iterations - | loopN_head_fail (hh : ¬ LoopHead invs m σ) : - Exec (.loop .nondet m invs b md :: ss) σ .failure - | loopN_exit (hh : LoopHead invs m σ) (k : Exec ss σ o) : - Exec (.loop .nondet m invs b md :: ss) σ o - | loopN_body_fail (hh : LoopHead invs m σ) (hb : Exec b σ .failure) : - Exec (.loop .nondet m invs b md :: ss) σ .failure - | loopN_measure_fail (hh : LoopHead invs m σ) (hb : Exec b σ (.normal σ')) - (hd : ¬ MeasureDecreased m σ σ') : - Exec (.loop .nondet m invs b md :: ss) σ .failure - | loopN_iter (hh : LoopHead invs m σ) (hb : Exec b σ (.normal σ')) - (hd : MeasureDecreased m σ σ') (k : Exec (.loop .nondet m invs b md :: ss) σ' o) : - Exec (.loop .nondet m invs b md :: ss) σ o - -- everything outside the fragment - | unsupported (hs : ¬ Supported s) : Exec (s :: ss) σ .failure - -/-- The weakest liberal precondition read off `Exec`: no run of `ss` from `σ` fails, -and every run that ends normally ends in `Q`. -/ -def semWP (ss : List Core.Statement) (Q : State → Prop) (σ : State) : Prop := - ∀ o, Exec ss σ o → o.Sat Q - -/-! ## Framing -/ - -/-- A run changes only the variables the statements may assign. -/ -theorem Exec.frame {ss : List Core.Statement} {σ : State} {o : Outcome} (h : Exec ss σ o) : - ∀ σ', o = .normal σ' → ∀ y, y ∉ Block.mods ss → σ' y = σ y := by - induction h with - | nil => intro _ h _ _; cases h; rfl - | set _ _ ih | havoc _ ih | init _ _ ih | init_havoc _ ih => - intro σ' h y hy - simp only [Block.mods, Stmt.mods, List.cons_append, List.nil_append, List.mem_cons, - not_or] at hy - rw [ih σ' h y hy.2] - simp [State.update, hy.1] - | assert _ _ ih | assume _ _ ih | cover _ ih => - intro σ' h y hy - exact ih σ' h y (by simpa [Block.mods, Stmt.mods] using hy) - | ite_true _ _ _ iht ihk | ite_false _ _ _ iht ihk | block _ _ iht ihk - | ite_nondet_true _ _ iht ihk | ite_nondet_false _ _ iht ihk => - intro σ' h y hy - simp only [Block.mods, Stmt.mods, List.mem_append, not_or] at hy - rw [ihk σ' h y (by simp_all), iht _ rfl y (by simp_all)] - | loop_exit _ _ _ ih | loopN_exit _ _ ih => - intro σ' h y hy - exact ih σ' h y (by simp_all [Block.mods, Stmt.mods]) - | loop_iter _ _ _ _ _ ihb ihk | loopN_iter _ _ _ _ ihb ihk => - intro σ' h y hy - rw [ihk σ' h y hy, ihb _ rfl y (by simp_all [Block.mods, Stmt.mods])] - | _ => intro _ h; cases h - -/-- A state that agrees with `σ` outside `xs` is `σ` havocked at `xs`. -/ -theorem State.havoc_self {σ σ' : State} {xs : List String} - (h : ∀ y, y ∉ xs → σ' y = σ y) : σ.havoc xs σ' = σ' := by - funext y - by_cases hy : y ∈ xs <;> simp [State.havoc, hy, h] - -end Strata.Deep - -end diff --git a/StrataBoole/HoareLogic/Deep/Lang.lean b/StrataBoole/HoareLogic/Deep/Lang.lean deleted file mode 100644 index a6f7cf8..0000000 --- a/StrataBoole/HoareLogic/Deep/Lang.lean +++ /dev/null @@ -1,238 +0,0 @@ -/- - Copyright Strata Contributors - - SPDX-License-Identifier: Apache-2.0 OR MIT --/ -module - -public import Strata.Languages.Core.Statement - -/-! # Deep embedding of Core: values, states, expressions - -A deep embedding of Strata Core in the style of the `lean-vcgen-tutorial`: Core -programs stay ASTs (`Core.Statement`), and their meaning is a relation (`Exec`, in -`Deep/Exec.lean`). This file fixes the value model and gives the expression fragment its -meaning. - -**Values are tagged, projections are total.** `Val` has an `int` and a `bool` -constructor. Every read goes through `Val.toInt` / `Val.toBool`, which are total, so an -operator never fails on a mistyped operand. Core programs are type checked before -verification, so a well-typed program never reaches the defaults. Equality is the one -operator whose meaning depends on a type: `==` compares integers as integers and -booleans as booleans, at the type the translator annotated its operands with. A -well-typed state therefore never has to be assumed: no verification condition mentions -a value's tag. - -**Expressions outside the fragment are undefined.** `eval` returns `none` for any -expression it does not cover (maps, unknown operators, ...). Statements treat an undefined -expression as a failure (`Deep/Exec.lean`), so a program outside the fragment cannot be -verified, rather than verified vacuously. - -**Clauses are propositions.** An `assert`, a `requires`, an `ensures` or an `invariant` may -quantify over integers and booleans, which no evaluator computes. `SatT`/`SatF` read a clause -as a Lean proposition: quantifiers become Lean quantifiers over the values of the bound type, -connectives become connectives, and an atom is true when it evaluates to `true`, with the bound -values in scope. --/ - -@[expose] public section - -namespace Strata.Deep - -/-! ## Values and states -/ - -inductive Val where - | int (i : Int) - | bool (b : Bool) - deriving DecidableEq, Repr, Inhabited - -namespace Val - -/-- Read a value as an integer; a boolean reads as `0`. -/ -def toInt : Val → Int - | int i => i - | bool _ => 0 - -/-- Read a value as a boolean; an integer reads as `false`. -/ -def toBool : Val → Bool - | bool b => b - | int _ => false - -/-- Stated as rewrite lemmas rather than by `rfl`, so that `simp` applies them through -congruence and re-synthesizes a `Decidable` instance whose proposition they change. -/ -@[simp] theorem toInt_int (i : Int) : (int i).toInt = i := by simp [toInt] -@[simp] theorem toBool_bool (b : Bool) : (bool b).toBool = b := by simp [toBool] - -/-- The type a value's tag says it has; a bound variable is typed by its value. -/ -def ty : Val → Lambda.LMonoTy - | int _ => .tcons "int" [] - | bool _ => .tcons "bool" [] - -end Val - -/-- A state maps each variable name to its value. Every name has a value, so a state -never needs to be checked for definedness. -/ -abbrev State := String → Val - -def State.update (σ : State) (x : String) (v : Val) : State := - fun y => if y = x then v else σ y - -/-! ## Expressions -/ - -abbrev Expr := Core.Expression.Expr - -/-- Core's unary built-ins, by their factory names (`Strata/DL/Lambda/IntBoolFactory.lean`). -/ -def unop : String → Val → Option Val - | "Int.Neg", v => some (.int (- v.toInt)) - | "Bool.Not", v => some (.bool (! v.toBool)) - | _, _ => none - -/-- Core's binary built-ins. `Int.Div` and `Int.Mod` are undefined on a zero divisor, -matching the factory, which only evaluates them for a nonzero divisor. -/ -def binop : String → Val → Val → Option Val - | "Int.Add", v, w => some (.int (v.toInt + w.toInt)) - | "Int.Sub", v, w => some (.int (v.toInt - w.toInt)) - | "Int.Mul", v, w => some (.int (v.toInt * w.toInt)) - | "Int.Div", v, w => if w.toInt = 0 then none else some (.int (v.toInt / w.toInt)) - | "Int.Mod", v, w => if w.toInt = 0 then none else some (.int (v.toInt % w.toInt)) - | "Int.Lt", v, w => some (.bool (decide (v.toInt < w.toInt))) - | "Int.Le", v, w => some (.bool (decide (v.toInt ≤ w.toInt))) - | "Int.Gt", v, w => some (.bool (decide (v.toInt > w.toInt))) - | "Int.Ge", v, w => some (.bool (decide (v.toInt ≥ w.toInt))) - | "Bool.And", v, w => some (.bool (v.toBool && w.toBool)) - | "Bool.Or", v, w => some (.bool (v.toBool || w.toBool)) - | "Bool.Implies", v, w => some (.bool (!v.toBool || w.toBool)) - | "Bool.Equiv", v, w => some (.bool (v.toBool == w.toBool)) - | _, _, _ => none - -/-- The type of `e`, read off the annotations the Core translator leaves on variables -and operators (an operator's annotation is its arrow type), with `bs` the values of the -bound variables in scope, innermost first, whose tags give their types. -/ -def typeOf (bs : List Val) : Expr → Option Lambda.LMonoTy - | .const _ (.intConst _) => some (.tcons "int" []) - | .const _ (.boolConst _) => some (.tcons "bool" []) - | .fvar _ _ ty => ty - | .bvar _ i => (bs[i]?).map Val.ty - | .app _ (.app _ (.op _ _ (some (.tcons "arrow" [_, .tcons "arrow" [_, r]]))) _) _ => some r - | .app _ (.op _ _ (some (.tcons "arrow" [_, r]))) _ => some r - | .ite _ _ t _ => typeOf bs t - | .eq _ _ _ => some (.tcons "bool" []) - | _ => none - -/-- Equality at a type: integers compare as integers, booleans as booleans. It is -undefined at any other type. -/ -def eqAt : Option Lambda.LMonoTy → Val → Val → Option Val - | some (.tcons "int" []), v, w => some (.bool (decide (v.toInt = w.toInt))) - | some (.tcons "bool" []), v, w => some (.bool (decide (v.toBool = w.toBool))) - | _, _, _ => none - -/-- The value of a Core expression in `σ`, with `bs` the values of the bound variables in -scope, innermost first; `none` outside the fragment. Built-ins are applied curried, -`app (app (op o) a) b`, as the Core translator produces them. -/ -def evalIn (σ : State) (bs : List Val) : Expr → Option Val - | .const _ (.intConst i) => some (.int i) - | .const _ (.boolConst b) => some (.bool b) - | .fvar _ x _ => some (σ x.name) - | .bvar _ i => bs[i]? - | .app _ (.app _ (.op _ o _) a) b => - match evalIn σ bs a, evalIn σ bs b with - | some va, some vb => binop o.name va vb - | _, _ => none - | .app _ (.op _ o _) a => - match evalIn σ bs a with - | some va => unop o.name va - | none => none - | .ite _ c t e => - match evalIn σ bs c with - | some vc => if vc.toBool then evalIn σ bs t else evalIn σ bs e - | none => none - | .eq _ a b => - match evalIn σ bs a, evalIn σ bs b with - | some va, some vb => eqAt (typeOf bs a) va vb - | _, _ => none - | _ => none - -/-- The value of a closed Core expression in `σ`, or `none` outside the fragment. -/ -def eval (σ : State) (e : Expr) : Option Val := evalIn σ [] e - -/-- The value of `e` read as a boolean, with bound values `bs`; `none` if `e` is undefined. -/ -def evalBoolIn (σ : State) (bs : List Val) (e : Expr) : Option Bool := - (evalIn σ bs e).map Val.toBool - -/-- The value of `e` read as a boolean; `none` if `e` is undefined. -/ -def evalBool (σ : State) (e : Expr) : Option Bool := (eval σ e).map Val.toBool - -/-- The value of `e` read as an integer; `none` if `e` is undefined. -/ -def evalInt (σ : State) (e : Expr) : Option Int := (eval σ e).map Val.toInt - -/-! ## Clauses - -A clause may quantify; its meaning is a proposition. `SatT σ bs e` says `e` is true at `σ` -with the bound values `bs` in scope, `SatF` that it is false. A quantifier over `int` or -`bool` is the Lean quantifier over `Int` or `Bool`, the body read with the bound value pushed -on `bs`; a connective is the Lean connective (`==>` an implication, `<==>` an equivalence); -anything else is an atom, true or false according to its value. An atom outside the fragment -is neither true nor false. -/ - -mutual -/-- `e` is true at `σ`, with bound values `bs`. The shape is matched first and the operator -name second, so that `simp` can reduce the match on a concrete expression. -/ -def SatT (σ : State) (bs : List Val) : Expr → Prop - | .quant _ .all _ ty _ body => - if ty = some (.tcons "int" []) then ∀ i : Int, SatT σ (.int i :: bs) body - else if ty = some (.tcons "bool" []) then ∀ b : Bool, SatT σ (.bool b :: bs) body - else False - | .quant _ .exist _ ty _ body => - if ty = some (.tcons "int" []) then ∃ i : Int, SatT σ (.int i :: bs) body - else if ty = some (.tcons "bool" []) then ∃ b : Bool, SatT σ (.bool b :: bs) body - else False - | e@(.app _ (.app _ (.op _ o _) a) b) => - match o.name with - | "Bool.And" => SatT σ bs a ∧ SatT σ bs b - | "Bool.Or" => SatT σ bs a ∨ SatT σ bs b - | "Bool.Implies" => SatT σ bs a → SatT σ bs b - | "Bool.Equiv" => SatT σ bs a ↔ SatT σ bs b - | _ => evalBoolIn σ bs e = some true - | e@(.app _ (.op _ o _) a) => - match o.name with - | "Bool.Not" => SatF σ bs a - | _ => evalBoolIn σ bs e = some true - | e => evalBoolIn σ bs e = some true - -/-- `e` is false at `σ`, with bound values `bs`. -/ -def SatF (σ : State) (bs : List Val) : Expr → Prop - | .quant _ .all _ ty _ body => - if ty = some (.tcons "int" []) then ∃ i : Int, SatF σ (.int i :: bs) body - else if ty = some (.tcons "bool" []) then ∃ b : Bool, SatF σ (.bool b :: bs) body - else False - | .quant _ .exist _ ty _ body => - if ty = some (.tcons "int" []) then ∀ i : Int, SatF σ (.int i :: bs) body - else if ty = some (.tcons "bool" []) then ∀ b : Bool, SatF σ (.bool b :: bs) body - else False - | e@(.app _ (.app _ (.op _ o _) a) b) => - match o.name with - | "Bool.And" => SatF σ bs a ∨ SatF σ bs b - | "Bool.Or" => SatF σ bs a ∧ SatF σ bs b - | "Bool.Implies" => SatT σ bs a ∧ SatF σ bs b - | "Bool.Equiv" => ¬ (SatT σ bs a ↔ SatT σ bs b) - | _ => evalBoolIn σ bs e = some false - | e@(.app _ (.op _ o _) a) => - match o.name with - | "Bool.Not" => SatT σ bs a - | _ => evalBoolIn σ bs e = some false - | e => evalBoolIn σ bs e = some false -end - -/-- `e` is true at `σ`. This is what a program must establish: asserts, postconditions, -loop invariants. -/ -def Holds (σ : State) (e : Expr) : Prop := SatT σ [] e - -/-- `e` is not false at `σ`: it is true, or it is outside the fragment. This is what a -program may assume (`assume`, `requires`). Dropping an assumption that cannot be -evaluated over-approximates the runs, so it is sound, and it keeps such an assumption -from making a triple hold vacuously. -/ -def MayHold (σ : State) (e : Expr) : Prop := ¬ SatF σ [] e - -end Strata.Deep - -end diff --git a/StrataBoole/HoareLogic/Deep/Spec.lean b/StrataBoole/HoareLogic/Deep/Spec.lean deleted file mode 100644 index 6e4ef81..0000000 --- a/StrataBoole/HoareLogic/Deep/Spec.lean +++ /dev/null @@ -1,257 +0,0 @@ -/- - Copyright Strata Contributors - - SPDX-License-Identifier: Apache-2.0 OR MIT --/ -module - -public import StrataBoole.HoareLogic.Deep.Triple - -/-! # Deep embedding of Core: proof rules - -One rule per statement form, each a theorem about `Exec`. A rule concludes -`semWP (s :: ss) Q σ` for a statement `s` and reduces it to premises about the rest of -the list: either smaller `semWP` goals, or *verification conditions* (VCs) that mention -no program. `core_vcgen` (`Deep/Tactic.lean`) applies the rules backwards until only VCs -are left, the way `vcgen` applies `@[spec]` lemmas in the `lean-vcgen-tutorial`. - -The premises of a rule are ordered so that a VC comes first and the continuation last. -Their names (`defined`, `assertion`, `entry`, `step`, `ifTrue`, `rest`, …) become the -case tags of the goals `core_vcgen` leaves, so a tag such as `rest.step.rest` reads as -the path to the obligation: -* a definedness VC `(eval σ e).isSome`: the expression is in the fragment; -* a check VC: an assertion, or a loop invariant or measure obligation, wrapped in `Labeled` - with the clause's label where the program has one; -* a continuation: `semWP` of what runs next, possibly under binders (a fresh value, a - guard hypothesis, a loop head state). - -`Exec.unsupported` gives every list one extra run, which fails unless the head statement -is supported. Each proof dismisses that run with `absurd trivial`: `Supported s` reduces -to `True` for the statement forms that have a rule. --/ - -@[expose] public section - -namespace Strata.Deep - -open Imperative - -variable {Q : State → Prop} {σ : State} {ss : List Core.Statement} - {e c g : Expr} {x : Core.CoreIdent} {l : String} {md : MetaData Core.Expression} - -/-- The empty list: the postcondition must hold now. -/ -theorem wp_nil (h : Q σ) : semWP [] Q σ := by - intro o ho - cases ho with - | nil => exact h - -/-- `x := e`: Hoare's assignment rule. The new value is a fresh `v`, with the hypothesis -`some v = eval σ e`, so the VCs stay readable until `core_lift` evaluates `e`. The -variable is on the left so that `simp_all` substitutes it once `e` is evaluated. -/ -theorem wp_set (defined : (eval σ e).isSome) - (rest : ∀ v, some v = eval σ e → semWP ss Q (σ.update x.name v)) : - semWP (.cmd (.cmd (.set x (.det e) md)) :: ss) Q σ := by - intro o ho - cases ho with - | set he k => exact rest _ he.symm _ k - | set_fail he => simp [he] at defined - | unsupported hs => exact absurd trivial hs - -/-- `havoc x`: the rest must work for every value of `x`. -/ -theorem wp_havoc (rest : ∀ v, semWP ss Q (σ.update x.name v)) : - semWP (.cmd (.cmd (.set x .nondet md)) :: ss) Q σ := by - intro o ho - cases ho with - | havoc k => exact rest _ _ k - | unsupported hs => exact absurd trivial hs - -/-- `var x : T := e`: as `x := e`. -/ -theorem wp_init {ty : Core.Expression.Ty} (defined : (eval σ e).isSome) - (rest : ∀ v, some v = eval σ e → semWP ss Q (σ.update x.name v)) : - semWP (.cmd (.cmd (.init x ty (.det e) md)) :: ss) Q σ := by - intro o ho - cases ho with - | init he k => exact rest _ he.symm _ k - | init_fail he => simp [he] at defined - | unsupported hs => exact absurd trivial hs - -/-- `var x : T`: as `havoc x`. -/ -theorem wp_init_havoc {ty : Core.Expression.Ty} (rest : ∀ v, semWP ss Q (σ.update x.name v)) : - semWP (.cmd (.cmd (.init x ty .nondet md)) :: ss) Q σ := by - intro o ho - cases ho with - | init_havoc k => exact rest _ _ k - | unsupported hs => exact absurd trivial hs - -/-- `assert e`: a VC that `e` holds, under the statement's label, then the rest. -/ -theorem wp_assert (assertion : Labeled l (Holds σ e)) (rest : semWP ss Q σ) : - semWP (.cmd (.cmd (.assert l e md)) :: ss) Q σ := by - intro o ho - cases ho with - | assert _ k => exact rest _ k - | assert_fail hne => exact absurd assertion hne - | unsupported hs => exact absurd trivial hs - -/-- `assume e`: the rest, under the hypothesis, labeled like the statement, that `e` may -hold. -/ -theorem wp_assume (rest : Labeled l (MayHold σ e) → semWP ss Q σ) : - semWP (.cmd (.cmd (.assume l e md)) :: ss) Q σ := by - intro o ho - cases ho with - | assume he k => exact rest he _ k - | unsupported hs => exact absurd trivial hs - -/-- `cover e`: a skip. -/ -theorem wp_cover (rest : semWP ss Q σ) : semWP (.cmd (.cmd (.cover l e md)) :: ss) Q σ := by - intro o ho - cases ho with - | cover k => exact rest _ k - | unsupported hs => exact absurd trivial hs - -/-- `if (*) { t } else { f }`: both branches, followed by the rest. -/ -theorem wp_ite_nondet {t f : List Core.Statement} - (ifTrue : semWP t (semWP ss Q) σ) (ifFalse : semWP f (semWP ss Q) σ) : - semWP (.ite .nondet t f md :: ss) Q σ := by - intro o ho - cases ho with - | ite_nondet_true h k => exact ifTrue _ h _ k - | ite_nondet_true_fail h => exact False.elim (ifTrue _ h) - | ite_nondet_false h k => exact ifFalse _ h _ k - | ite_nondet_false_fail h => exact False.elim (ifFalse _ h) - | unsupported hs => exact absurd trivial hs - -/-- `if (c) { t } else { f }`: each branch, under its value of the guard, followed by -the rest. -/ -theorem wp_ite {t f : List Core.Statement} (defined : (evalBool σ c).isSome) - (ifTrue : evalBool σ c = some true → semWP t (semWP ss Q) σ) - (ifFalse : evalBool σ c = some false → semWP f (semWP ss Q) σ) : - semWP (.ite (.det c) t f md :: ss) Q σ := by - intro o ho - cases ho with - | ite_true hc h k => exact ifTrue hc _ h _ k - | ite_true_fail hc h => exact False.elim (ifTrue hc _ h) - | ite_false hc h k => exact ifFalse hc _ h _ k - | ite_false_fail hc h => exact False.elim (ifFalse hc _ h) - | ite_fail hc => simp [hc] at defined - | unsupported hs => exact absurd trivial hs - -/-- `{ b }`: the block, followed by the rest. -/ -theorem wp_block {b : List Core.Statement} (hb : semWP b (semWP ss Q) σ) : - semWP (.block l b md :: ss) Q σ := by - intro o ho - cases ho with - | block h k => exact hb _ h _ k - | block_fail h => exact False.elim (hb _ h) - | unsupported hs => exact absurd trivial hs - -/-- `while (g) decreases m invariant invs { b }`, with the annotations the program -carries. The head states are `σ.havoc (Block.mods b) τ` for an arbitrary `τ`: the body -can change only the variables it assigns, so every other variable keeps its value from -`σ`. This is the frame Core's verifier gets by havocking just the modified variables. -* `entry`: the invariants and the measure bound hold on entry. -* `guardDefined`: the guard is defined at every head state. -* `step`: an iteration from a head state, with the guard true, re-establishes the - invariants and the bound, and decreases the measure. -* `exit`: from a head state with the guard false, the rest of the list runs. - -The proof inducts on the runs of the loop. -/ -theorem wp_loop {m : Option Expr} {invs : List (String × Expr)} {b : List Core.Statement} - (entry : LoopHead invs m σ) - (guardDefined : ∀ τ, LoopHead invs m (σ.havoc (Block.mods b) τ) → - (evalBool (σ.havoc (Block.mods b) τ) g).isSome) - (step : ∀ τ, LoopHead invs m (σ.havoc (Block.mods b) τ) → - evalBool (σ.havoc (Block.mods b) τ) g = some true → - semWP b (fun σ' => LoopHead invs m σ' ∧ - MeasureDecreased m (σ.havoc (Block.mods b) τ) σ') (σ.havoc (Block.mods b) τ)) - (exit : ∀ τ, LoopHead invs m (σ.havoc (Block.mods b) τ) → - evalBool (σ.havoc (Block.mods b) τ) g = some false → - semWP ss Q (σ.havoc (Block.mods b) τ)) : - semWP (.loop (.det g) m invs b md :: ss) Q σ := by - -- Strengthen to an arbitrary head state `σ₁`: one that agrees with `σ` outside the - -- body's variables and passes the head checks. - suffices key : ∀ l σ₁ o, Exec l σ₁ o → l = .loop (.det g) m invs b md :: ss → - (∀ y, y ∉ Block.mods b → σ₁ y = σ y) → LoopHead invs m σ₁ → o.Sat Q from - fun o ho => key _ _ _ ho rfl (fun _ _ => rfl) entry - intro l σ₁ o h - induction h with - | loop_head_fail hh => intro hl _ hh₁; cases hl; exact absurd hh₁ hh - | loop_guard_fail hh hg => - intro hl hfr _ - cases hl - have := guardDefined _ (by rwa [State.havoc_self hfr]); rw [State.havoc_self hfr] at this - simp [hg] at this - | loop_exit hh hg k _ => - intro hl hfr _ - cases hl - have := exit _ (by rwa [State.havoc_self hfr]) (by rwa [State.havoc_self hfr]) - rw [State.havoc_self hfr] at this - exact this _ k - | loop_body_fail hh hg hb => - intro hl hfr _ - cases hl - have := step _ (by rwa [State.havoc_self hfr]) (by rwa [State.havoc_self hfr]) - rw [State.havoc_self hfr] at this - exact False.elim (this _ hb) - | loop_measure_fail hh hg hb hd => - intro hl hfr _ - cases hl - have := step _ (by rwa [State.havoc_self hfr]) (by rwa [State.havoc_self hfr]) - rw [State.havoc_self hfr] at this - exact absurd (this _ hb).2 hd - | loop_iter hh hg hb hd k _ ih => - intro hl hfr _ - cases hl - have := step _ (by rwa [State.havoc_self hfr]) (by rwa [State.havoc_self hfr]) - rw [State.havoc_self hfr] at this - refine ih rfl (fun y hy => ?_) (this _ hb).1 - rw [hb.frame _ rfl y hy, hfr y hy] - | unsupported hs => intro hl _ _; cases hl; exact absurd trivial hs - | _ => intro hl; cases hl - -/-- `while (*) decreases m invariant invs { b }`: the loop rule with nothing learned from a -guard. The head states are `σ.havoc (Block.mods b) τ` as for `wp_loop`. -/ -theorem wp_loop_nondet {m : Option Expr} {invs : List (String × Expr)} {b : List Core.Statement} - (entry : LoopHead invs m σ) - (step : ∀ τ, LoopHead invs m (σ.havoc (Block.mods b) τ) → - semWP b (fun σ' => LoopHead invs m σ' ∧ - MeasureDecreased m (σ.havoc (Block.mods b) τ) σ') (σ.havoc (Block.mods b) τ)) - (exit : ∀ τ, LoopHead invs m (σ.havoc (Block.mods b) τ) → - semWP ss Q (σ.havoc (Block.mods b) τ)) : - semWP (.loop .nondet m invs b md :: ss) Q σ := by - suffices key : ∀ l σ₁ o, Exec l σ₁ o → l = .loop .nondet m invs b md :: ss → - (∀ y, y ∉ Block.mods b → σ₁ y = σ y) → LoopHead invs m σ₁ → o.Sat Q from - fun o ho => key _ _ _ ho rfl (fun _ _ => rfl) entry - intro l σ₁ o h - induction h with - | loopN_head_fail hh => intro hl _ hh₁; cases hl; exact absurd hh₁ hh - | loopN_exit hh k _ => - intro hl hfr _ - cases hl - have := exit _ (by rwa [State.havoc_self hfr]) - rw [State.havoc_self hfr] at this - exact this _ k - | loopN_body_fail hh hb => - intro hl hfr _ - cases hl - have := step _ (by rwa [State.havoc_self hfr]) - rw [State.havoc_self hfr] at this - exact False.elim (this _ hb) - | loopN_measure_fail hh hb hd => - intro hl hfr _ - cases hl - have := step _ (by rwa [State.havoc_self hfr]) - rw [State.havoc_self hfr] at this - exact absurd (this _ hb).2 hd - | loopN_iter hh hb hd k _ ih => - intro hl hfr _ - cases hl - have := step _ (by rwa [State.havoc_self hfr]) - rw [State.havoc_self hfr] at this - refine ih rfl (fun y hy => ?_) (this _ hb).1 - rw [hb.frame _ rfl y hy, hfr y hy] - | unsupported hs => intro hl _ _; cases hl; exact absurd trivial hs - | _ => intro hl; cases hl - -end Strata.Deep - -end diff --git a/StrataBoole/HoareLogic/Deep/Tactic.lean b/StrataBoole/HoareLogic/Deep/Tactic.lean deleted file mode 100644 index a1a0253..0000000 --- a/StrataBoole/HoareLogic/Deep/Tactic.lean +++ /dev/null @@ -1,279 +0,0 @@ -/- - Copyright Strata Contributors - - SPDX-License-Identifier: Apache-2.0 OR MIT --/ -import Lean -import StrataBoole.HoareLogic.Deep.Spec -import StrataBoole.HoareLogic.Lift.Names - -/-! # Deep embedding of Core: tactics - -* `core_vcgen` turns a goal `Procedure.Correct p` (or `Triple P ss Q`) into verification - conditions. It applies the rules of `Deep/Spec.lean` backwards, statement by statement, - as `vcgen` applies `@[spec]` lemmas in the `lean-vcgen-tutorial`. -* `core_lift` names the conditions and evaluates the embedding away in every hypothesis and - the goal (`eval`, `State.update`, the loop and contract predicates), leaving propositions - about `Int` and `Bool`, like the tutorial's `imp_lift`. - -Typical use, after unfolding the procedure: `core_vcgen <;> core_lift <;> omega`. - -The VCs `core_vcgen` leaves still mention the program: they say which Core formulas -must hold in which states, as in `σ.update "m" v ⊨ ⟪m >= x⟫` (with the notation of -`Deep/Delab.lean`), each under the label of its clause (`Labeled "max2_ensures_0" …`). -The binders it introduces have names: `σ` for the initial state and `pre` for the -precondition, `v`/`hv` for an assigned value, `hguard` for a branch condition, -`hassume` for an `assume`, and `τ`/`hhead`/`hguard` for a loop head state. - -`core_lift` then reads like the Strata route's goals: one goal per condition, named -`then.

_ast : Core.Program` when `p` is an identifier, and -every procedure as `_ast : Core.Procedure`. Statements about a procedure, such as its -contract triple, are made on these definitions; the program literal carries the functions, -axioms and type declarations the procedure's names refer to. -/ +`boole_reflect p` type-checks the Boole program `p` and erases the source locations of its +procedures' expressions (`TypeCheck.lean`), then binds the resulting Core AST (`ToExpr.lean`): +the whole program as `

_ast : Core.Program` when `p` is an identifier, and every procedure as +`_ast : Core.Procedure`. Statements about a procedure, such as its contract triple, are +made on these definitions; the program literal carries the functions, axioms and type +declarations the procedure's names refer to. -/ open Lean Elab Command namespace Strata.Reflect -syntax (name := shallowReflect) "shallow_reflect " term : command +syntax (name := booleReflect) "boole_reflect " term : command -@[command_elab shallowReflect] def elabShallowReflect : CommandElab := fun stx => do - let `(shallow_reflect $t:term) := stx | throwUnsupportedSyntax +@[command_elab booleReflect] def elabBooleReflect : CommandElab := fun stx => do + let `(boole_reflect $t:term) := stx | throwUnsupportedSyntax let prog ← liftTermElabM (evalProgram t) let ns ← getCurrNamespace if let `($x:ident) := t then let pgmName := ns ++ Name.mkSimple s!"{x.getId.eraseMacroScopes.getString!}_ast" liftTermElabM (addProgramAst pgmName prog) else - logWarning "shallow_reflect: the program is bound as a whole only when the argument is an \ + logWarning "boole_reflect: the program is bound as a whole only when the argument is an \ identifier; its procedures are bound either way" for d in prog.decls do if let .proc p _ := d then diff --git a/StrataBoole/HoareLogic/Reflect/Core.lean b/StrataBoole/HoareLogic/Reflect/Core.lean index 6f2c3da..c4f52eb 100644 --- a/StrataBoole/HoareLogic/Reflect/Core.lean +++ b/StrataBoole/HoareLogic/Reflect/Core.lean @@ -9,7 +9,7 @@ import Strata.Languages.Core.Verifier /-! # Core programs as Lean terms -`#core_reflect prog` takes a program `prog` written in Core syntax +`core_reflect prog` takes a program `prog` written in Core syntax (`def prog := #strata program Core; … #end`). At elaboration time it runs Strata's Core translator and type checker on it, and defines ` : Core.Procedure` in the current namespace for each procedure ``. The value of that definition is the translated AST, @@ -22,11 +22,12 @@ The AST is the *type-checked* program, the one Core's verifier works on. Type ch annotates every variable and operator with its type, which the typing witnesses of the denotational reading require. -Metadata (source locations) is replaced by `MetaData.empty`: the semantics never reads it. -Type declarations and CFG bodies are rejected. +Statement metadata is replaced by `MetaData.empty` and the source location of every expression +by `Core.valueLoc`: evaluation reads neither (`Core.Expression.eval_eraseLocs`). Type +declarations and CFG bodies are rejected. This file is not a `module`, so its elaborator needs no `meta` phase annotations. A file that -uses `#core_reflect` imports it as an ordinary file. -/ +uses `core_reflect` imports it as an ordinary file. -/ namespace Strata.CoreReflect @@ -54,9 +55,9 @@ structure Ctx where def mkCtx : MetaM Ctx := do let P := mkConst ``Core.Expression - let exprTy ← whnfR (mkApp (mkConst ``Imperative.PureExpr.Expr) P) + let exprTy ← whnfR (mkApp (mkConst ``Imperative.PureExpr.Expr [Level.one]) P) let some T := exprTy.app1? ``Lambda.LExpr - | throwError "#core_reflect: unexpected shape of Core.Expression.Expr: {exprTy}" + | throwError "core_reflect: unexpected shape of Core.Expression.Expr: {exprTy}" return { T, P, C := mkConst ``Core.Command } def mkList (ty : Lean.Expr) (xs : List Lean.Expr) : Lean.Expr := @@ -72,6 +73,8 @@ def mkPair (α β a b : Lean.Expr) : Lean.Expr := mkApp4 (mkConst ``Prod.mk [0, def mkProd (α β : Lean.Expr) : Lean.Expr := mkApp2 (mkConst ``Prod [0, 0]) α β def unitE : Lean.Expr := mkConst ``Unit.unit +/-- The location every reflected expression gets. -/ +def locE : Lean.Expr := mkConst ``Core.valueLoc def stringTy : Lean.Expr := mkConst ``String def monoTyTy : Lean.Expr := mkConst ``Lambda.LMonoTy def identTy : Lean.Expr := mkApp (mkConst ``Lambda.Identifier) (mkConst ``Unit) @@ -89,7 +92,15 @@ def lTyE : Lambda.LTy → Lean.Expr | .forAll vs ty => mkApp2 (mkConst ``Lambda.LTy.forAll) (mkList stringTy (vs.map toExpr)) (monoTyE ty) -def constE : Lambda.LConst → Lean.Expr +partial def sortE : Lambda.LSort → Lean.Expr + | .tcons n args => + mkApp2 (mkConst ``Lambda.LSort.tcons) (toExpr n) (mkList (mkConst ``Lambda.LSort) (args.map sortE)) + | .bitvec n => mkApp (mkConst ``Lambda.LSort.bitvec) (toExpr n) + +def mkArray (ty : Lean.Expr) (xs : List Lean.Expr) : Lean.Expr := + mkApp2 (mkConst ``List.toArray [0]) ty (mkList ty xs) + +partial def constE : Lambda.LConst → Lean.Expr | .intConst i => mkApp (mkConst ``Lambda.LConst.intConst) (toExpr i) | .strConst s => mkApp (mkConst ``Lambda.LConst.strConst) (toExpr s) | .rationalConst r => @@ -97,6 +108,13 @@ def constE : Lambda.LConst → Lean.Expr (mkApp2 (mkConst ``Rat.divInt) (toExpr r.num) (toExpr (r.den : Int))) | .bitvecConst n b => mkApp2 (mkConst ``Lambda.LConst.bitvecConst) (toExpr n) (toExpr b) | .boolConst b => mkApp (mkConst ``Lambda.LConst.boolConst) (toExpr b) + | .mapConst k v d es => + let cTy := mkConst ``Lambda.LConst + mkApp4 (mkConst ``Lambda.LConst.mapConst) (sortE k) (sortE v) (constE d) + (mkArray (mkProd cTy cTy) (es.toList.map fun (a, b) => mkPair cTy cTy (constE a) (constE b))) + | .sequenceConst s es => + mkApp2 (mkConst ``Lambda.LConst.sequenceConst) (sortE s) + (mkArray (mkConst ``Lambda.LConst) (es.toList.map constE)) def quantE : Lambda.QuantifierKind → Lean.Expr | .all => mkConst ``Lambda.QuantifierKind.all @@ -105,82 +123,82 @@ def quantE : Lambda.QuantifierKind → Lean.Expr def optTyE (ty : Option Lambda.LMonoTy) : Lean.Expr := mkOption monoTyTy (ty.map monoTyE) partial def exprE (c : Ctx) : Core.Expression.Expr → Lean.Expr - | .const _ k => mkApp3 (mkConst ``Lambda.LExpr.const) c.T unitE (constE k) - | .op _ o ty => mkApp4 (mkConst ``Lambda.LExpr.op) c.T unitE (identE o) (optTyE ty) - | .bvar _ i => mkApp3 (mkConst ``Lambda.LExpr.bvar) c.T unitE (toExpr i) - | .fvar _ x ty => mkApp4 (mkConst ``Lambda.LExpr.fvar) c.T unitE (identE x) (optTyE ty) + | .const _ k => mkApp3 (mkConst ``Lambda.LExpr.const) c.T locE (constE k) + | .op _ o ty => mkApp4 (mkConst ``Lambda.LExpr.op) c.T locE (identE o) (optTyE ty) + | .bvar _ i => mkApp3 (mkConst ``Lambda.LExpr.bvar) c.T locE (toExpr i) + | .fvar _ x ty => mkApp4 (mkConst ``Lambda.LExpr.fvar) c.T locE (identE x) (optTyE ty) | .abs _ n ty e => - mkApp5 (mkConst ``Lambda.LExpr.abs) c.T unitE (toExpr n) (optTyE ty) (exprE c e) + mkApp5 (mkConst ``Lambda.LExpr.abs) c.T locE (toExpr n) (optTyE ty) (exprE c e) | .quant _ k n ty tr e => mkAppN (mkConst ``Lambda.LExpr.quant) - #[c.T, unitE, quantE k, toExpr n, optTyE ty, exprE c tr, exprE c e] - | .app _ f a => mkApp4 (mkConst ``Lambda.LExpr.app) c.T unitE (exprE c f) (exprE c a) + #[c.T, locE, quantE k, toExpr n, optTyE ty, exprE c tr, exprE c e] + | .app _ f a => mkApp4 (mkConst ``Lambda.LExpr.app) c.T locE (exprE c f) (exprE c a) | .ite _ x y z => - mkApp5 (mkConst ``Lambda.LExpr.ite) c.T unitE (exprE c x) (exprE c y) (exprE c z) - | .eq _ a b => mkApp4 (mkConst ``Lambda.LExpr.eq) c.T unitE (exprE c a) (exprE c b) + mkApp5 (mkConst ``Lambda.LExpr.ite) c.T locE (exprE c x) (exprE c y) (exprE c z) + | .eq _ a b => mkApp4 (mkConst ``Lambda.LExpr.eq) c.T locE (exprE c a) (exprE c b) -def exprTy (c : Ctx) : Lean.Expr := mkApp (mkConst ``Imperative.PureExpr.Expr) c.P +def exprTy (c : Ctx) : Lean.Expr := mkApp (mkConst ``Imperative.PureExpr.Expr [Level.one]) c.P -def mdE (c : Ctx) : Lean.Expr := mkApp (mkConst ``Imperative.MetaData.empty) c.P +def mdE (c : Ctx) : Lean.Expr := mkApp (mkConst ``Imperative.MetaData.empty [Level.one]) c.P def eonE (c : Ctx) : Imperative.ExprOrNondet Core.Expression → Lean.Expr - | .det e => mkApp2 (mkConst ``Imperative.ExprOrNondet.det) c.P (exprE c e) - | .nondet => mkApp (mkConst ``Imperative.ExprOrNondet.nondet) c.P + | .det e => mkApp2 (mkConst ``Imperative.ExprOrNondet.det [Level.one]) c.P (exprE c e) + | .nondet => mkApp (mkConst ``Imperative.ExprOrNondet.nondet [Level.one]) c.P def cmdE (c : Ctx) : Imperative.Cmd Core.Expression → Lean.Expr | .init x ty e _ => - mkApp5 (mkConst ``Imperative.Cmd.init) c.P (identE x) (lTyE ty) (eonE c e) (mdE c) - | .set x e _ => mkApp4 (mkConst ``Imperative.Cmd.set) c.P (identE x) (eonE c e) (mdE c) + mkApp5 (mkConst ``Imperative.Cmd.init [Level.one]) c.P (identE x) (lTyE ty) (eonE c e) (mdE c) + | .set x e _ => mkApp4 (mkConst ``Imperative.Cmd.set [Level.one]) c.P (identE x) (eonE c e) (mdE c) | .assert l e _ => - mkApp4 (mkConst ``Imperative.Cmd.assert) c.P (toExpr l) (exprE c e) (mdE c) + mkApp4 (mkConst ``Imperative.Cmd.assert [Level.one]) c.P (toExpr l) (exprE c e) (mdE c) | .assume l e _ => - mkApp4 (mkConst ``Imperative.Cmd.assume) c.P (toExpr l) (exprE c e) (mdE c) + mkApp4 (mkConst ``Imperative.Cmd.assume [Level.one]) c.P (toExpr l) (exprE c e) (mdE c) | .cover l e _ => - mkApp4 (mkConst ``Imperative.Cmd.cover) c.P (toExpr l) (exprE c e) (mdE c) + mkApp4 (mkConst ``Imperative.Cmd.cover [Level.one]) c.P (toExpr l) (exprE c e) (mdE c) def callArgE (c : Ctx) : Imperative.CallArg Core.Expression → Lean.Expr - | .inArg e => mkApp2 (mkConst ``Imperative.CallArg.inArg) c.P (exprE c e) - | .inoutArg x => mkApp2 (mkConst ``Imperative.CallArg.inoutArg) c.P (identE x) - | .outArg x => mkApp2 (mkConst ``Imperative.CallArg.outArg) c.P (identE x) + | .inArg e => mkApp2 (mkConst ``Imperative.CallArg.inArg [Level.one]) c.P (exprE c e) + | .inoutArg x => mkApp2 (mkConst ``Imperative.CallArg.inoutArg [Level.one]) c.P (identE x) + | .outArg x => mkApp2 (mkConst ``Imperative.CallArg.outArg [Level.one]) c.P (identE x) def commandE (c : Ctx) : Core.Command → Lean.Expr - | .cmd k => mkApp2 (mkConst ``Imperative.CmdExt.cmd) c.P (cmdE c k) + | .cmd k => mkApp2 (mkConst ``Imperative.CmdExt.cmd [Level.one]) c.P (cmdE c k) | .call p args _ => - mkApp4 (mkConst ``Imperative.CmdExt.call) c.P (toExpr p) - (mkList (mkApp (mkConst ``Imperative.CallArg) c.P) (args.map (callArgE c))) (mdE c) + mkApp4 (mkConst ``Imperative.CmdExt.call [Level.one]) c.P (toExpr p) + (mkList (mkApp (mkConst ``Imperative.CallArg [Level.one]) c.P) (args.map (callArgE c))) (mdE c) mutual partial def stmtE (c : Ctx) : Core.Statement → Except String Lean.Expr - | .cmd k => pure <| mkApp3 (mkConst ``Imperative.Stmt.cmd) c.P c.C (commandE c k) + | .cmd k => pure <| mkApp3 (mkConst ``Imperative.Stmt.cmd [Level.one]) c.P c.C (commandE c k) | .block l b _ => do - pure <| mkApp5 (mkConst ``Imperative.Stmt.block) c.P c.C (toExpr l) (← stmtsE c b) (mdE c) + pure <| mkApp5 (mkConst ``Imperative.Stmt.block [Level.one]) c.P c.C (toExpr l) (← stmtsE c b) (mdE c) | .ite g t f _ => do - pure <| mkAppN (mkConst ``Imperative.Stmt.ite) + pure <| mkAppN (mkConst ``Imperative.Stmt.ite [Level.one]) #[c.P, c.C, eonE c g, ← stmtsE c t, ← stmtsE c f, mdE c] | .loop g m invs b _ => do let invTy := mkProd stringTy (exprTy c) let invsE := mkList invTy (invs.map fun (l, e) => mkPair stringTy (exprTy c) (toExpr l) (exprE c e)) - pure <| mkAppN (mkConst ``Imperative.Stmt.loop) + pure <| mkAppN (mkConst ``Imperative.Stmt.loop [Level.one]) #[c.P, c.C, eonE c g, mkOption (exprTy c) (m.map (exprE c)), invsE, ← stmtsE c b, mdE c] - | .exit l _ => pure <| mkApp4 (mkConst ``Imperative.Stmt.exit) c.P c.C (toExpr l) (mdE c) + | .exit l _ => pure <| mkApp4 (mkConst ``Imperative.Stmt.exit [Level.one]) c.P c.C (toExpr l) (mdE c) | .typeDecl _ _ => throw "type declarations are not supported" partial def stmtsE (c : Ctx) (ss : List Core.Statement) : Except String Lean.Expr := do - return mkList (mkApp2 (mkConst ``Imperative.Stmt) c.P c.C) (← ss.mapM (stmtE c)) + return mkList (mkApp2 (mkConst ``Imperative.Stmt [Level.one]) c.P c.C) (← ss.mapM (stmtE c)) end def checkE (c : Ctx) (ch : Imperative.Check Core.Expression) : Lean.Expr := let attr := match ch.attr with | .Free => mkConst ``Imperative.CheckAttr.Free | .Default => mkConst ``Imperative.CheckAttr.Default - mkApp4 (mkConst ``Imperative.Check.mk) c.P (exprE c ch.expr) attr (mdE c) + mkApp4 (mkConst ``Imperative.Check.mk [Level.one]) c.P (exprE c ch.expr) attr (mdE c) def specE (c : Ctx) (s : Imperative.Spec Core.Expression) : Lean.Expr := - let checkTy := mkApp (mkConst ``Imperative.Check) c.P + let checkTy := mkApp (mkConst ``Imperative.Check [Level.one]) c.P let clauses (cs : ListMap String (Imperative.Check Core.Expression)) := mkList (mkProd stringTy checkTy) (cs.toList.map fun (l, ch) => mkPair stringTy checkTy (toExpr l) (checkE c ch)) - mkApp3 (mkConst ``Imperative.Spec.mk) c.P (clauses s.preconditions) (clauses s.postconditions) + mkApp3 (mkConst ``Imperative.Spec.mk [Level.one]) c.P (clauses s.preconditions) (clauses s.postconditions) def sigE (sig : @Lambda.LMonoTySignature Unit) : Lean.Expr := mkList (mkProd identTy monoTyTy) @@ -194,12 +212,12 @@ def headerE (h : Core.Procedure.Header) : Lean.Expr := def procedureE (c : Ctx) (p : Core.Procedure) : MetaM Lean.Expr := do let ss ← match p.body with | .structured ss => pure ss - | .cfg _ => throwError "#core_reflect: procedure {p.header.name.name} has a CFG body" + | .cfg _ => throwError "core_reflect: procedure {p.header.name.name} has a CFG body" let body ← match stmtsE c ss with | .ok e => pure e - | .error msg => throwError "#core_reflect: procedure {p.header.name.name}: {msg}" + | .error msg => throwError "core_reflect: procedure {p.header.name.name}: {msg}" mkAppM ``Imperative.Procedure.mk - #[headerE p.header, specE c p.spec, mkApp3 (mkConst ``Imperative.Body.structured) c.P c.C body] + #[headerE p.header, specE c p.spec, mkApp3 (mkConst ``Imperative.Body.structured [Level.one]) c.P c.C body] /-! ## The command -/ @@ -214,16 +232,16 @@ unsafe def evalTranslateUnsafe (prog : Name) : TermElabM (Except String Core.Pro @[implemented_by evalTranslateUnsafe] opaque evalTranslate (prog : Name) : TermElabM (Except String Core.Program) -/-- `#core_reflect prog` defines ` : Core.Procedure` in the current namespace for +/-- `core_reflect prog` defines ` : Core.Procedure` in the current namespace for each procedure `` of the Core program `prog`, with the translated AST as its value. -/ -syntax (name := coreReflect) "#core_reflect " ident : command +syntax (name := coreReflect) "core_reflect " ident : command @[command_elab coreReflect] def elabCoreReflect : CommandElab := fun stx => do let prog ← liftCoreM <| realizeGlobalConstNoOverloadWithInfo stx[1] let pgm ← match ← liftTermElabM (evalTranslate prog) with | .ok pgm => pure pgm - | .error msg => throwError "#core_reflect: {msg}" + | .error msg => throwError "core_reflect: {msg}" let ctx ← liftTermElabM mkCtx for d in pgm.decls do let .proc p _ := d | continue @@ -233,7 +251,7 @@ syntax (name := coreReflect) "#core_reflect " ident : command let type := mkConst ``Core.Procedure check value unless ← isDefEq (← inferType value) type do - throwError "#core_reflect: the term for {name} does not have type Core.Procedure" + throwError "core_reflect: the term for {name} does not have type Core.Procedure" liftCoreM <| addDecl <| .defnDecl { name, levelParams := [], type := mkConst ``Core.Procedure, value, hints := .abbrev, safety := .safe } diff --git a/StrataBoole/HoareLogic/Reflect/ToExpr.lean b/StrataBoole/HoareLogic/Reflect/ToExpr.lean index 6d88e1c..78558f2 100644 --- a/StrataBoole/HoareLogic/Reflect/ToExpr.lean +++ b/StrataBoole/HoareLogic/Reflect/ToExpr.lean @@ -7,7 +7,7 @@ import StrataBoole.Verify /-! # Reflection: a type-checked Core procedure as a Lean term -`shallow_reflect` obtains the Core program by *running* `Strata.Boole.typeCheck` at elaboration +`boole_reflect` obtains the Core program by *running* `Strata.Boole.typeCheck` at elaboration time. That result is a value in the elaborator's memory, not a term the kernel can compute with: the lowering is built from `partial` definitions, so `typeCheck p` never reduces. To state and prove anything about the program, each procedure is turned back into a closed term @@ -30,6 +30,7 @@ namespace Strata.Reflect deriving instance ToExpr for Lambda.QuantifierKind deriving instance ToExpr for Lambda.LMonoTy deriving instance ToExpr for Lambda.LTy +deriving instance ToExpr for Lambda.LSort deriving instance ToExpr for Lambda.LConst deriving instance ToExpr for Lambda.Identifier deriving instance ToExpr for Imperative.CheckAttr @@ -39,6 +40,7 @@ deriving instance ToExpr for Strata.SynthesizedOrigin deriving instance ToExpr for Strata.Uri deriving instance ToExpr for StrataDDM.SourceRange deriving instance ToExpr for Strata.Provenance +deriving instance ToExpr for ExprSourceLoc /-- `ListMap` is a definition, not an abbreviation, so the `List` instance is not found through it. -/ @@ -58,25 +60,27 @@ def cmdE : Expr := mkConst ``Core.Command /-- `Core.CoreLParams.mono : LExprParamsT`, the parameters of Core's `LExpr`. -/ def lparamsE : Expr := mkApp (mkConst ``Lambda.LExprParams.mono) (mkConst ``Core.CoreLParams) -/-- Metadata on Core expressions is `Unit`. -/ -def unitE (u : Unit) : Expr := toExpr u +/-- The source location of an expression. `Core.valueLoc`, the location every expression has +once its locations are erased, is written as that constant, which keeps the terms small. -/ +def locE (m : Core.ExpressionMetadata) : Expr := + if m = Core.valueLoc then mkConst ``Core.valueLoc else toExpr m /-- Core identifiers (`Lambda.Identifier Unit`). -/ def identE (x : Core.CoreIdent) : Expr := toExpr x /-- Expressions. -/ def exprE : Core.Expression.Expr → Expr - | .const m c => mkApp3 (mkConst ``LExpr.const) lparamsE (unitE m) (toExpr c) - | .op m o ty => mkApp4 (mkConst ``LExpr.op) lparamsE (unitE m) (identE o) (toExpr ty) - | .bvar m i => mkApp3 (mkConst ``LExpr.bvar) lparamsE (unitE m) (toExpr i) - | .fvar m x ty => mkApp4 (mkConst ``LExpr.fvar) lparamsE (unitE m) (identE x) (toExpr ty) - | .abs m n ty e => mkApp5 (mkConst ``LExpr.abs) lparamsE (unitE m) (toExpr n) (toExpr ty) (exprE e) + | .const m c => mkApp3 (mkConst ``LExpr.const) lparamsE (locE m) (toExpr c) + | .op m o ty => mkApp4 (mkConst ``LExpr.op) lparamsE (locE m) (identE o) (toExpr ty) + | .bvar m i => mkApp3 (mkConst ``LExpr.bvar) lparamsE (locE m) (toExpr i) + | .fvar m x ty => mkApp4 (mkConst ``LExpr.fvar) lparamsE (locE m) (identE x) (toExpr ty) + | .abs m n ty e => mkApp5 (mkConst ``LExpr.abs) lparamsE (locE m) (toExpr n) (toExpr ty) (exprE e) | .quant m k n ty tr e => - mkApp7 (mkConst ``LExpr.quant) lparamsE (unitE m) (toExpr k) (toExpr n) (toExpr ty) (exprE tr) + mkApp7 (mkConst ``LExpr.quant) lparamsE (locE m) (toExpr k) (toExpr n) (toExpr ty) (exprE tr) (exprE e) - | .app m f a => mkApp4 (mkConst ``LExpr.app) lparamsE (unitE m) (exprE f) (exprE a) - | .ite m c t e => mkApp5 (mkConst ``LExpr.ite) lparamsE (unitE m) (exprE c) (exprE t) (exprE e) - | .eq m a b => mkApp4 (mkConst ``LExpr.eq) lparamsE (unitE m) (exprE a) (exprE b) + | .app m f a => mkApp4 (mkConst ``LExpr.app) lparamsE (locE m) (exprE f) (exprE a) + | .ite m c t e => mkApp5 (mkConst ``LExpr.ite) lparamsE (locE m) (exprE c) (exprE t) (exprE e) + | .eq m a b => mkApp4 (mkConst ``LExpr.eq) lparamsE (locE m) (exprE a) (exprE b) instance : ToExpr Core.Expression.Expr where toExpr := exprE @@ -84,27 +88,27 @@ instance : ToExpr Core.Expression.Expr where instance : ToExpr (ExprOrNondet Core.Expression) where toExpr - | .det e => mkApp2 (mkConst ``ExprOrNondet.det) pureExprE (toExpr e) - | .nondet => mkApp (mkConst ``ExprOrNondet.nondet) pureExprE - toTypeExpr := mkApp (mkConst ``ExprOrNondet) pureExprE + | .det e => mkApp2 (mkConst ``ExprOrNondet.det [Level.one]) pureExprE (toExpr e) + | .nondet => mkApp (mkConst ``ExprOrNondet.nondet [Level.one]) pureExprE + toTypeExpr := mkApp (mkConst ``ExprOrNondet [Level.one]) pureExprE instance : ToExpr (MetaDataElem.Field Core.Expression) where toExpr - | .var v => mkApp2 (mkConst ``MetaDataElem.Field.var) pureExprE (identE v) - | .label l => mkApp2 (mkConst ``MetaDataElem.Field.label) pureExprE (toExpr l) - toTypeExpr := mkApp (mkConst ``MetaDataElem.Field) pureExprE + | .var v => mkApp2 (mkConst ``MetaDataElem.Field.var [Level.one]) pureExprE (identE v) + | .label l => mkApp2 (mkConst ``MetaDataElem.Field.label [Level.one]) pureExprE (toExpr l) + toTypeExpr := mkApp (mkConst ``MetaDataElem.Field [Level.one]) pureExprE instance : ToExpr (MetaDataElem.Value Core.Expression) where toExpr - | .expr e => mkApp2 (mkConst ``MetaDataElem.Value.expr) pureExprE (toExpr e) - | .msg s => mkApp2 (mkConst ``MetaDataElem.Value.msg) pureExprE (toExpr s) - | .switch b => mkApp2 (mkConst ``MetaDataElem.Value.switch) pureExprE (toExpr b) - | .provenance p => mkApp2 (mkConst ``MetaDataElem.Value.provenance) pureExprE (toExpr p) - toTypeExpr := mkApp (mkConst ``MetaDataElem.Value) pureExprE + | .expr e => mkApp2 (mkConst ``MetaDataElem.Value.expr [Level.one]) pureExprE (toExpr e) + | .msg s => mkApp2 (mkConst ``MetaDataElem.Value.msg [Level.one]) pureExprE (toExpr s) + | .switch b => mkApp2 (mkConst ``MetaDataElem.Value.switch [Level.one]) pureExprE (toExpr b) + | .provenance p => mkApp2 (mkConst ``MetaDataElem.Value.provenance [Level.one]) pureExprE (toExpr p) + toTypeExpr := mkApp (mkConst ``MetaDataElem.Value [Level.one]) pureExprE instance : ToExpr (MetaDataElem Core.Expression) where - toExpr e := mkApp3 (mkConst ``MetaDataElem.mk) pureExprE (toExpr e.fld) (toExpr e.value) - toTypeExpr := mkApp (mkConst ``MetaDataElem) pureExprE + toExpr e := mkApp3 (mkConst ``MetaDataElem.mk [Level.one]) pureExprE (toExpr e.fld) (toExpr e.value) + toTypeExpr := mkApp (mkConst ``MetaDataElem [Level.one]) pureExprE /-- Statement metadata. -/ def mdE (md : Imperative.MetaData Core.Expression) : Expr := toExpr md @@ -112,39 +116,39 @@ def mdE (md : Imperative.MetaData Core.Expression) : Expr := toExpr md instance : ToExpr (Cmd Core.Expression) where toExpr | .init x ty e md => - mkApp5 (mkConst ``Cmd.init) pureExprE (identE x) (toExpr ty) (toExpr e) (mdE md) - | .set x e md => mkApp4 (mkConst ``Cmd.set) pureExprE (identE x) (toExpr e) (mdE md) - | .assert l b md => mkApp4 (mkConst ``Cmd.assert) pureExprE (toExpr l) (toExpr b) (mdE md) - | .assume l b md => mkApp4 (mkConst ``Cmd.assume) pureExprE (toExpr l) (toExpr b) (mdE md) - | .cover l b md => mkApp4 (mkConst ``Cmd.cover) pureExprE (toExpr l) (toExpr b) (mdE md) - toTypeExpr := mkApp (mkConst ``Cmd) pureExprE + mkApp5 (mkConst ``Cmd.init [Level.one]) pureExprE (identE x) (toExpr ty) (toExpr e) (mdE md) + | .set x e md => mkApp4 (mkConst ``Cmd.set [Level.one]) pureExprE (identE x) (toExpr e) (mdE md) + | .assert l b md => mkApp4 (mkConst ``Cmd.assert [Level.one]) pureExprE (toExpr l) (toExpr b) (mdE md) + | .assume l b md => mkApp4 (mkConst ``Cmd.assume [Level.one]) pureExprE (toExpr l) (toExpr b) (mdE md) + | .cover l b md => mkApp4 (mkConst ``Cmd.cover [Level.one]) pureExprE (toExpr l) (toExpr b) (mdE md) + toTypeExpr := mkApp (mkConst ``Cmd [Level.one]) pureExprE instance : ToExpr (CallArg Core.Expression) where toExpr - | .inArg e => mkApp2 (mkConst ``CallArg.inArg) pureExprE (toExpr e) - | .inoutArg x => mkApp2 (mkConst ``CallArg.inoutArg) pureExprE (identE x) - | .outArg x => mkApp2 (mkConst ``CallArg.outArg) pureExprE (identE x) - toTypeExpr := mkApp (mkConst ``CallArg) pureExprE + | .inArg e => mkApp2 (mkConst ``CallArg.inArg [Level.one]) pureExprE (toExpr e) + | .inoutArg x => mkApp2 (mkConst ``CallArg.inoutArg [Level.one]) pureExprE (identE x) + | .outArg x => mkApp2 (mkConst ``CallArg.outArg [Level.one]) pureExprE (identE x) + toTypeExpr := mkApp (mkConst ``CallArg [Level.one]) pureExprE instance : ToExpr Core.Command where toExpr - | .cmd c => mkApp2 (mkConst ``CmdExt.cmd) pureExprE (toExpr c) - | .call n args md => mkApp4 (mkConst ``CmdExt.call) pureExprE (toExpr n) (toExpr args) (mdE md) + | .cmd c => mkApp2 (mkConst ``CmdExt.cmd [Level.one]) pureExprE (toExpr c) + | .call n args md => mkApp4 (mkConst ``CmdExt.call [Level.one]) pureExprE (toExpr n) (toExpr args) (mdE md) toTypeExpr := cmdE mutual /-- Statements. -/ partial def stmtE : Core.Statement → Expr - | .cmd c => mkApp3 (mkConst ``Stmt.cmd) pureExprE cmdE (toExpr c) - | .block l b md => mkApp5 (mkConst ``Stmt.block) pureExprE cmdE (toExpr l) (stmtsE b) (mdE md) + | .cmd c => mkApp3 (mkConst ``Stmt.cmd [Level.one]) pureExprE cmdE (toExpr c) + | .block l b md => mkApp5 (mkConst ``Stmt.block [Level.one]) pureExprE cmdE (toExpr l) (stmtsE b) (mdE md) | .ite c t e md => - mkApp6 (mkConst ``Stmt.ite) pureExprE cmdE (toExpr c) (stmtsE t) (stmtsE e) (mdE md) + mkApp6 (mkConst ``Stmt.ite [Level.one]) pureExprE cmdE (toExpr c) (stmtsE t) (stmtsE e) (mdE md) | .loop g m invs b md => - mkApp7 (mkConst ``Stmt.loop) pureExprE cmdE (toExpr g) (toExpr m) (toExpr invs) (stmtsE b) + mkApp7 (mkConst ``Stmt.loop [Level.one]) pureExprE cmdE (toExpr g) (toExpr m) (toExpr invs) (stmtsE b) (mdE md) - | .exit l md => mkApp4 (mkConst ``Stmt.exit) pureExprE cmdE (toExpr l) (mdE md) - | .typeDecl tc md => mkApp4 (mkConst ``Stmt.typeDecl) pureExprE cmdE (toExpr tc) (mdE md) + | .exit l md => mkApp4 (mkConst ``Stmt.exit [Level.one]) pureExprE cmdE (toExpr l) (mdE md) + | .typeDecl tc md => mkApp4 (mkConst ``Stmt.typeDecl [Level.one]) pureExprE cmdE (toExpr tc) (mdE md) /-- Statement lists, as `List Core.Statement` literals. -/ partial def stmtsE : List Core.Statement → Expr @@ -158,20 +162,20 @@ instance : ToExpr Core.Statement where toTypeExpr := mkConst ``Core.Statement instance : ToExpr (Check Core.Expression) where - toExpr c := mkApp4 (mkConst ``Check.mk) pureExprE (toExpr c.expr) (toExpr c.attr) (mdE c.md) - toTypeExpr := mkApp (mkConst ``Check) pureExprE + toExpr c := mkApp4 (mkConst ``Check.mk [Level.one]) pureExprE (toExpr c.expr) (toExpr c.attr) (mdE c.md) + toTypeExpr := mkApp (mkConst ``Check [Level.one]) pureExprE instance : ToExpr (Spec Core.Expression) where toExpr s := - mkApp3 (mkConst ``Spec.mk) pureExprE (toExpr s.preconditions) (toExpr s.postconditions) - toTypeExpr := mkApp (mkConst ``Spec) pureExprE + mkApp3 (mkConst ``Spec.mk [Level.one]) pureExprE (toExpr s.preconditions) (toExpr s.postconditions) + toTypeExpr := mkApp (mkConst ``Spec [Level.one]) pureExprE /-! ## Procedures -/ /-- A procedure body. Only structured bodies are supported; the lowering never produces a CFG. -/ def bodyE : Core.Procedure.Body → MetaM Expr - | .structured ss => pure (mkApp3 (mkConst ``Body.structured) pureExprE cmdE (stmtsE ss)) - | .cfg _ => throwError "shallow_reflect: a procedure body given as a CFG cannot be reflected" + | .structured ss => pure (mkApp3 (mkConst ``Body.structured [Level.one]) pureExprE cmdE (stmtsE ss)) + | .cfg _ => throwError "boole_reflect: a procedure body given as a CFG cannot be reflected" /-- The procedure `p` as a closed term of type `Core.Procedure`. -/ def procedureE (p : Core.Procedure) : MetaM Expr := do diff --git a/StrataBoole/HoareLogic/Reflect/TypeCheck.lean b/StrataBoole/HoareLogic/Reflect/TypeCheck.lean index 6bc0a2f..76da1aa 100644 --- a/StrataBoole/HoareLogic/Reflect/TypeCheck.lean +++ b/StrataBoole/HoareLogic/Reflect/TypeCheck.lean @@ -7,11 +7,18 @@ import StrataBoole.Verify /-! # From Boole source to a type-checked Core program, at elaboration time -`shallow_reflect` (`Boole.lean`) starts from the Core program obtained by +`boole_reflect` (`Boole.lean`) starts from the Core program obtained by `Strata.Boole.typeCheck`, that is `getProgram → toCoreProgram → Core.typeCheck`, before any Core transform phase: the program Core's verifier works on. This file computes it. The computation runs compiled code (`Term.evalTerm`): its result is a value in the elaborator, not a term the -kernel can reduce. -/ +kernel can reduce. + +The expressions of that program carry their source locations. `coreProgram` replaces the +location of every expression of a procedure by `Core.valueLoc` (`Core.eraseLocs`), as Strata's +own tests of its Hoare logic do: the terms stay small and do not change when the source text +moves. Typing has been checked before, and evaluation ignores locations +(`Core.Expression.eval_eraseLocs`). What is bound, and what every statement about a reflected +procedure is about, is the program with the locations erased. -/ open Lean Elab Term Meta @@ -24,15 +31,27 @@ def typeCheckStr (p : StrataDDM.Program) : Except String Core.Program := | .ok cp => .ok cp | .error m => .error (toString (m.format none)) +/-- `p` with the source location of every expression of its procedures replaced by +`Core.valueLoc`. Declarations other than procedures are left as they are. -/ +def eraseProcedureLocs (p : Core.Program) : Core.Program := + { p with decls := p.decls.map fun + | .proc proc md => .proc (Core.Procedure.mapExprs Core.eraseLocs proc) md + | d => d } + +/-- The program `boole_reflect` binds: lowered, type-checked, locations erased. -/ +def coreProgram (p : StrataDDM.Program) : Except String Core.Program := + (typeCheckStr p).map eraseProcedureLocs + unsafe def evalProgramUnsafe (t : Term) : TermElabM Core.Program := do let ty := mkApp2 (mkConst ``Except [.zero, .zero]) (mkConst ``String) (mkConst ``Core.Program) let r ← Term.evalTerm (Except String Core.Program) ty - (← `(Strata.Reflect.typeCheckStr $t)) + (← `(Strata.Reflect.coreProgram $t)) match r with | .ok p => pure p | .error m => throwError m!"Core type checking failed: {m}" -/-- The type-checked Core program denoted by the term `t : StrataDDM.Program`. -/ +/-- The type-checked Core program denoted by the term `t : StrataDDM.Program`, with the +locations of its procedures' expressions erased (`coreProgram`). -/ @[implemented_by evalProgramUnsafe] opaque evalProgram (t : Term) : TermElabM Core.Program diff --git a/StrataBooleTest.lean b/StrataBooleTest.lean index 03bade0..34218fd 100644 --- a/StrataBooleTest.lean +++ b/StrataBooleTest.lean @@ -64,17 +64,13 @@ import StrataBooleTest.CoreTests.DefineFunRecTests import StrataBooleTest.HoareLogic.shallow_find_max import StrataBooleTest.HoareLogic.hoare_max2 import StrataBooleTest.HoareLogic.generic_datatypes -import StrataBooleTest.HoareLogic.shallow_reflect +import StrataBooleTest.HoareLogic.boole_reflect import StrataBooleTest.HoareLogic.hoare_find_max_core import StrataBooleTest.HoareLogic.hoare_locals_core import StrataBooleTest.HoareLogic.hoare_ops_core import StrataBooleTest.HoareLogic.hoare_frame_core import StrataBooleTest.HoareLogic.hoare_quant_core -import StrataBooleTest.HoareLogic.hoare_havoc_gap +import StrataBooleTest.HoareLogic.hoare_havoc_core import StrataBooleTest.HoareLogic.hoare_nondet_core -import StrataBooleTest.HoareLogic.deep_max2 -import StrataBooleTest.HoareLogic.deep_count_up -import StrataBooleTest.HoareLogic.deep_quant -import StrataBooleTest.HoareLogic.deep_nondet import StrataBooleTest.HoareLogic.boole_globals import StrataBooleTest.HoareLogic.demo_pipeline diff --git a/StrataBooleTest/HoareLogic/boole_globals.lean b/StrataBooleTest/HoareLogic/boole_globals.lean index 10b20dd..3cf3c62 100644 --- a/StrataBooleTest/HoareLogic/boole_globals.lean +++ b/StrataBooleTest/HoareLogic/boole_globals.lean @@ -5,11 +5,10 @@ -/ import StrataBoole.MetaVerifier import StrataBoole.HoareLogic.Reflect.Boole -import StrataBoole.HoareLogic.Deep.Delab +import StrataBoole.HoareLogic.Delab import StrataBoole.HoareLogic.Hoare.Tactic -import StrataBoole.HoareLogic.Deep.Tactic -/-! # Two results, a modified global and `old` across a loop, from Boole, on both routes +/-! # Two results, a modified global and `old` across a loop, from Boole `returns (count: int, last: int)` gives two `out` parameters, `modifies total` makes the global an `inout` parameter with an `old total` snapshot, and the loop writes the global. The frame @@ -46,9 +45,8 @@ spec { }; #end -shallow_reflect globalsPgm +boole_reflect globalsPgm -set_option maxHeartbeats 400000 in theorem addAll_contract (params : Core.Logic.InitEnvWFParams) : Core.Logic.Hoare.Procedure.contractTriple globalsPgm_ast params "addAll" := by hoare_contract @@ -56,20 +54,8 @@ theorem addAll_contract (params : Core.Logic.InitEnvWFParams) : all_goals hoare_lift all_goals omega -theorem addAll_correct : Strata.Deep.Procedure.Correct addAll_ast := by - unfold addAll_ast - core_vcgen <;> core_lift <;> omega - -/-- info: 'Strata.BooleTest.addAll_contract' depends on axioms: [propext, - Classical.choice, - Quot.sound, - Core.WFFactory._native.native_decide.ax_1✝, - Core.WFFactoryArray_func_name_nodup._native.native_decide.ax_1_1✝] -/ +/-- info: 'Strata.BooleTest.addAll_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ #guard_msgs in #print axioms addAll_contract -/-- info: 'Strata.BooleTest.addAll_correct' depends on axioms: [propext, Classical.choice, Quot.sound] -/ -#guard_msgs in -#print axioms addAll_correct - end Strata.BooleTest diff --git a/StrataBooleTest/HoareLogic/shallow_reflect.lean b/StrataBooleTest/HoareLogic/boole_reflect.lean similarity index 80% rename from StrataBooleTest/HoareLogic/shallow_reflect.lean rename to StrataBooleTest/HoareLogic/boole_reflect.lean index 7c9cc79..d7a060d 100644 --- a/StrataBooleTest/HoareLogic/shallow_reflect.lean +++ b/StrataBooleTest/HoareLogic/boole_reflect.lean @@ -8,10 +8,11 @@ import StrataBoole.HoareLogic.Reflect.Boole /-! # Reflection of the type-checked Core procedure -`shallow_reflect` binds the type-checked Core program to `

_ast` and each of its procedures to -`_ast`. The literals must be the very values the type checker produced (both are computed -and compared here), and they must compute by kernel reduction. The programs cover `havoc` and -`assume`, `Map` types, quantifiers, nested loops, metadata and provenance. -/ +`boole_reflect` binds the type-checked Core program to `

_ast` and each of its procedures to +`_ast`, with the source locations of the procedures' expressions erased. The literals must +be the very values the type checker produced, up to that erasure (both are computed and compared +here), and they must compute by kernel reduction. The programs cover `havoc` and `assume`, `Map` +types, quantifiers, nested loops, metadata and provenance. -/ namespace Strata.ReflectTest @@ -131,26 +132,28 @@ spec { requires n >= 0; ensures s >= 0; } #end #guard_msgs in -shallow_reflect pickNatPgm +boole_reflect pickNatPgm #guard_msgs in -shallow_reflect sumToPgm +boole_reflect sumToPgm #guard_msgs in -shallow_reflect findMaxPgm +boole_reflect findMaxPgm #guard_msgs in -shallow_reflect loopNoStatePgm +boole_reflect loopNoStatePgm #guard_msgs in -shallow_reflect loopOneVarPgm +boole_reflect loopOneVarPgm #guard_msgs in -shallow_reflect loopNestedPgm +boole_reflect loopNestedPgm example : Core.Procedure := sum_to_ast -/-- Every procedure of the type-checked program is among the reflected literals, and -conversely. -/ +/-- Every procedure of the type-checked program, with the locations of its expressions erased, +is among the reflected literals, and conversely. -/ def reflectedFaithfully (pgm : StrataDDM.Program) (asts : List Core.Procedure) : Bool := match Strata.Reflect.typeCheckStr pgm with | .ok cp => - let procs := cp.decls.filterMap fun | .proc p _ => some p | _ => none + let procs := cp.decls.filterMap fun + | .proc p _ => some (Core.Procedure.mapExprs Core.eraseLocs p) + | _ => none procs.length == asts.length && procs.all fun p => asts.any fun a => decide (p = a) | .error _ => false @@ -168,7 +171,7 @@ def reflectedFaithfully (pgm : StrataDDM.Program) (asts : List Core.Procedure) : example : Core.Program := findMaxPgm_ast def programFaithful (pgm : StrataDDM.Program) (ast : Core.Program) : Bool := - match Strata.Reflect.typeCheckStr pgm with + match Strata.Reflect.coreProgram pgm with | .ok cp => decide (cp = ast) | .error _ => false @@ -204,7 +207,7 @@ spec { ensures r == twice(x); } #end #guard_msgs in -shallow_reflect declsPgm +boole_reflect declsPgm /-- info: true -/ #guard_msgs in @@ -219,6 +222,15 @@ example : hasKind declsPgm_ast (fun | .func f _ => f.body.isSome | _ => false) = example : hasKind declsPgm_ast (fun | .func f _ => f.body.isNone | _ => false) = true := by decide example : hasKind declsPgm_ast (fun | .proc .. => true | _ => false) = true := by decide +/-! Every expression of a reflected procedure has the location `Core.valueLoc`: erasing the +locations again changes nothing. -/ + +/-- info: [true, true, true] -/ +#guard_msgs in +#eval [decide (Core.Procedure.mapExprs Core.eraseLocs sum_to_ast = sum_to_ast), + decide (Core.Procedure.mapExprs Core.eraseLocs findMax_ast = findMax_ast), + decide (Core.Procedure.mapExprs Core.eraseLocs loop_nested_ast = loop_nested_ast)] + /-! The literal computes by kernel reduction. -/ example : sum_to_ast.header.name.name = "sum_to" := rfl diff --git a/StrataBooleTest/HoareLogic/deep_count_up.lean b/StrataBooleTest/HoareLogic/deep_count_up.lean deleted file mode 100644 index 7f1e843..0000000 --- a/StrataBooleTest/HoareLogic/deep_count_up.lean +++ /dev/null @@ -1,72 +0,0 @@ -/- - Copyright Strata Contributors - - SPDX-License-Identifier: Apache-2.0 OR MIT --/ -import Strata.Languages.Core -import StrataDDM.Integration.Lean.HashCommands -import StrataBoole.HoareLogic.Reflect.Core -import StrataBoole.HoareLogic.Deep.Delab -import StrataBoole.HoareLogic.Deep.Tactic - -/-! # Example: a loop with invariants and a `decreases` clause - -The loop carries its own annotations, so `core_vcgen` needs no `invariants` clause: -the loop rule (`wp_loop`) reads them off the AST. After `core_lift`, five conditions are -left, named after the obligation and the clause (the invariants are unlabeled, so they are -`inv_1` and `inv_2`; `bound` is the lower bound of the measure at the head, `decreases` its -decrease over an iteration): -``` -case step.inv_1 -i : Int -hinv_1 : 0 ≤ i -n : Int -hcountUp_requires_0 : 0 ≤ n -hguard : i < n -hbound : i ≤ n -⊢ 0 ≤ i + 1 -``` -with `step.inv_2 : i + 1 ≤ n`, `step.bound : i + 1 ≤ n`, `step.decreases : i < i + 1` and -`exit.countUp_ensures_1 : i = n` (under `hguard : n ≤ i`). The entry conditions (`i := 0` -establishes the invariants and `n - i ≥ 0`) are closed by `core_lift`. In the VCs, `i` is the -value in an arbitrary loop-head state, while `n` is still the value in the initial state: the -body assigns only `i`, so the loop rule frames `n`. --/ - -open StrataDDM (Program) -open Strata.Deep - --- `countUp` below is defined by `#core_reflect`; if that failed, an auto-bound implicit --- would silently stand in for it. -set_option autoImplicit false - -namespace Strata.DeepExamples - -def countUpPgm := -#strata -program Core; - -procedure countUp(n : int, out i : int) -spec { - requires (int.ge(n, 0)); - ensures (i == n); -} -{ - i := 0; - while (int.lt(i, n)) - decreases int.sub(n, i) - invariant int.le(0, i) - invariant int.le(i, n) - { - i := int.add(i, 1); - } -}; -#end - -#core_reflect countUpPgm - -theorem countUp_correct : Procedure.Correct countUp := by - unfold countUp - core_vcgen <;> core_lift <;> omega - -end Strata.DeepExamples diff --git a/StrataBooleTest/HoareLogic/deep_max2.lean b/StrataBooleTest/HoareLogic/deep_max2.lean deleted file mode 100644 index c423faa..0000000 --- a/StrataBooleTest/HoareLogic/deep_max2.lean +++ /dev/null @@ -1,116 +0,0 @@ -/- - Copyright Strata Contributors - - SPDX-License-Identifier: Apache-2.0 OR MIT --/ -import Strata.Languages.Core -import StrataDDM.Integration.Lean.HashCommands -import StrataBoole.HoareLogic.Reflect.Core -import StrataBoole.HoareLogic.Deep.Delab -import StrataBoole.HoareLogic.Deep.Tactic - -/-! # Example: the maximum of two integers, through the deep embedding - -1. Write the procedure in Core syntax. -2. `#core_reflect` translates and type checks it with Strata's Core front end, and - defines `max2 : Core.Procedure`, the AST as a Lean term. -3. `Procedure.Correct max2` is the procedure's contract read as a Hoare triple: - `{requires} body {ensures}` over the big-step semantics `Exec`. -4. `core_vcgen` applies one rule per statement and leaves verification conditions; - `core_lift` names them and evaluates the embedding away; `omega` closes the arithmetic. - -`#print max2` shows the procedure in Core notation (`Deep/Delab.lean`). After -`core_vcgen`, the VC of the then branch reads -``` -case ifTrue.rest -σ : State -hguard : evalBool σ ⟪x >= y⟫ = some true -v : Val -hv : some v = eval σ ⟪x⟫ -⊢ Labeled "max2_ensures_0" (σ.update "m" v ⊨ ⟪m >= x⟫) ∧ - Labeled "max2_ensures_1" (σ.update "m" v ⊨ ⟪m >= y⟫) ∧ - Labeled "max2_ensures_2" (σ.update "m" v ⊨ ⟪m == x || m == y⟫) -``` -and `core_lift` closes all but one of the six conditions, leaving -``` -case else.max2_ensures_0 -x y : Int -hguard : x < y -⊢ x ≤ y -``` --/ - -open StrataDDM (Program) -open Strata.Deep - --- `max2` below is defined by `#core_reflect`; if that failed, an auto-bound implicit would --- silently stand in for it. -set_option autoImplicit false - -namespace Strata.DeepExamples - -def max2Pgm := -#strata -program Core; - -procedure max2(x : int, y : int, out m : int) -spec { - ensures (int.ge(m, x)); - ensures (int.ge(m, y)); - ensures (m == x || m == y); -} -{ - if (int.ge(x, y)) { - m := x; - } else { - m := y; - } -}; -#end - -#core_reflect max2Pgm - -theorem max2_correct : Procedure.Correct max2 := by - unfold max2 - simp only [Procedure.Correct] - core_vcgen <;> core_lift <;> omega - -/-! ## A wrong contract is refuted - -The triple is not vacuous: with `ensures (m == x)`, the VC of the else branch is false, -and a concrete run shows the contract itself is false. From `x = 0`, `y = 1` the guard -is false, the body sets `m := y = 1`, and `m == x` fails. -/ - -def max2WrongPgm := -#strata -program Core; - -procedure max2Wrong(x : int, y : int, out m : int) -spec { - ensures (m == x); -} -{ - if (int.ge(x, y)) { - m := x; - } else { - m := y; - } -}; -#end - -#core_reflect max2WrongPgm - -theorem max2Wrong_refuted : ¬ Procedure.Correct max2Wrong := by - unfold max2Wrong - simp only [Procedure.Correct, Procedure.pre, Procedure.post, Triple] - intro h - let σ : State := fun v => if v = "y" then .int 1 else .int 0 - -- The run `ite_false` → `m := y` → end, from `σ`. - have := h σ (by simp [σ, OldSnapshot, PresHold, Core.Procedure.Header.getInoutParams, - Core.getInoutParams, ListMap.keys]) _ - (.ite_false (by simp [σ, evalBool, eval, evalIn, binop]) - (.set (v := .int 1) (by simp [σ, eval, evalIn]) .nil) .nil) - simp [σ, Outcome.Sat, PostsHold, Labeled, Holds, SatT, evalBoolIn, evalIn, eqAt, typeOf, - State.update] at this - -end Strata.DeepExamples diff --git a/StrataBooleTest/HoareLogic/deep_nondet.lean b/StrataBooleTest/HoareLogic/deep_nondet.lean deleted file mode 100644 index 6ccd966..0000000 --- a/StrataBooleTest/HoareLogic/deep_nondet.lean +++ /dev/null @@ -1,77 +0,0 @@ -/- - Copyright Strata Contributors - - SPDX-License-Identifier: Apache-2.0 OR MIT --/ -import StrataBoole.HoareLogic.Reflect.Core -import StrataBoole.HoareLogic.Deep.Delab -import StrataBoole.HoareLogic.Deep.Tactic -import StrataDDM.Integration.Lean.HashCommands - -/-! # Nondeterministic control and `cover`, on the deep embedding - -`if (*)` proves both branches, `while (*)` is the loop rule with nothing learned from a -guard, and `cover` is a skip. -/ - -open StrataDDM (Program) -open Strata.Deep - -set_option autoImplicit false - -namespace Strata.DeepExamples - -def nondetPgm := -#strata -program Core; - -procedure pick(n : int, out r : int) -spec { - requires [nonneg]: int.ge(n, 0); - ensures [range]: int.le(0, r) && int.le(r, n); -} -{ - if * { - r := 0; - } else { - r := n; - } - cover [reach]: int.ge(r, 0); -}; - -procedure drift(n : int, out r : int) -spec { - requires [nonneg]: int.ge(n, 0); - ensures [bound]: int.le(0, r) && int.le(r, n); -} -{ - r := 0; - while * - invariant [inv]: int.le(0, r) && int.le(r, n) - { - if (int.lt(r, n)) { - r := int.add(r, 1); - } else { - } - } -}; -#end - -#core_reflect nondetPgm - -theorem pick_correct : Procedure.Correct pick := by - unfold pick - core_vcgen <;> core_lift <;> omega - -theorem drift_correct : Procedure.Correct drift := by - unfold drift - core_vcgen <;> core_lift <;> omega - -/-- info: 'Strata.DeepExamples.pick_correct' depends on axioms: [propext, Classical.choice, Quot.sound] -/ -#guard_msgs in -#print axioms pick_correct - -/-- info: 'Strata.DeepExamples.drift_correct' depends on axioms: [propext, Classical.choice, Quot.sound] -/ -#guard_msgs in -#print axioms drift_correct - -end Strata.DeepExamples diff --git a/StrataBooleTest/HoareLogic/deep_quant.lean b/StrataBooleTest/HoareLogic/deep_quant.lean deleted file mode 100644 index b9022a3..0000000 --- a/StrataBooleTest/HoareLogic/deep_quant.lean +++ /dev/null @@ -1,117 +0,0 @@ -/- - Copyright Strata Contributors - - SPDX-License-Identifier: Apache-2.0 OR MIT --/ -import StrataBoole.HoareLogic.Reflect.Core -import StrataBoole.HoareLogic.Deep.Delab -import StrataBoole.HoareLogic.Deep.Tactic -import StrataDDM.Integration.Lean.HashCommands - -/-! # Quantifiers in clauses, on the deep embedding - -A clause is read as a proposition (`SatT`), so `forall` and `exists` over integers lift to -the Lean quantifiers wherever a clause appears: a `requires` (a hypothesis to instantiate), an -`ensures` and an `assert` (goals), an `invariant` (both), nested binders included. The last -procedure is the shape a Boole `choose` lowers to: an `assert` of an `exists`, a `havoc`, an -`assume`; the deep embedding's values are canonical, so the havocked value lifts. -/ - -open StrataDDM (Program) -open Strata.Deep - -set_option autoImplicit false - -namespace Strata.DeepExamples - -def quantPgm := -#strata -program Core; - -procedure bounds(n : int, out r : int) -spec { - requires [nonneg]: int.ge(n, 0); - ensures [all]: forall i : int :: int.le(i, n) ==> int.lt(i, r); - ensures [witness]: exists i : int :: int.gt(i, n) && int.lt(i, r); - ensures [pairs]: forall i : int :: forall j : int :: - int.le(i, j) ==> int.le(int.add(i, r), int.add(j, r)); -} -{ - r := int.add(n, 2); -}; - -procedure fromForall(n : int, out r : int) -spec { - requires [lb]: forall i : int :: int.ge(i, n) ==> int.ge(i, 0); - ensures [nonneg]: int.ge(r, 0); -} -{ - r := n; -}; - -procedure fill(n : int, out r : int) -spec { - requires [nonneg]: int.ge(n, 0); - ensures [done]: forall i : int :: int.le(0, i) && int.lt(i, n) ==> int.lt(i, r); -} -{ - r := 0; - while (int.lt(r, n)) - invariant [range]: int.le(0, r) && int.le(r, n) - invariant [below]: forall i : int :: int.lt(i, r) ==> int.lt(i, n) - { - r := int.add(r, 1); - } -}; - -procedure chooseIt(n : int, out r : int) -spec { - requires [nonneg]: int.ge(n, 0); - ensures [ge]: int.ge(r, n); - ensures [lt]: int.lt(r, int.add(n, 2)); -} -{ - assert [some_pick]: exists i : int :: int.ge(i, n) && int.lt(i, int.add(n, 2)); - havoc r; - assume [pick]: int.ge(r, n) && int.lt(r, int.add(n, 2)); -}; -#end - -#core_reflect quantPgm - -theorem bounds_correct : Procedure.Correct bounds := by - unfold bounds - core_vcgen <;> core_lift - case witness => exact ⟨n + 1, by omega⟩ - all_goals (intros; omega) - -theorem fromForall_correct : Procedure.Correct fromForall := by - unfold fromForall - core_vcgen <;> core_lift - -theorem fill_correct : Procedure.Correct fill := by - unfold fill - core_vcgen <;> core_lift <;> (intros; omega) - -theorem chooseIt_correct : Procedure.Correct chooseIt := by - unfold chooseIt - core_vcgen <;> core_lift - case some_pick => exact ⟨n, by omega⟩ - all_goals omega - -/-- info: 'Strata.DeepExamples.bounds_correct' depends on axioms: [propext, Classical.choice, Quot.sound] -/ -#guard_msgs in -#print axioms bounds_correct - -/-- info: 'Strata.DeepExamples.fromForall_correct' depends on axioms: [propext, Classical.choice, Quot.sound] -/ -#guard_msgs in -#print axioms fromForall_correct - -/-- info: 'Strata.DeepExamples.fill_correct' depends on axioms: [propext, Classical.choice, Quot.sound] -/ -#guard_msgs in -#print axioms fill_correct - -/-- info: 'Strata.DeepExamples.chooseIt_correct' depends on axioms: [propext, Classical.choice, Quot.sound] -/ -#guard_msgs in -#print axioms chooseIt_correct - -end Strata.DeepExamples diff --git a/StrataBooleTest/HoareLogic/demo_pipeline.lean b/StrataBooleTest/HoareLogic/demo_pipeline.lean index 0d652b1..bbf147c 100644 --- a/StrataBooleTest/HoareLogic/demo_pipeline.lean +++ b/StrataBooleTest/HoareLogic/demo_pipeline.lean @@ -67,7 +67,7 @@ spec { }; #end -shallow_reflect demoPgm +boole_reflect demoPgm /-- info: def Strata.PipelineDemo.max2_ast : Core.Procedure := @@ -115,12 +115,6 @@ theorem max2_contract (params : Core.Logic.InitEnvWFParams) : all_goals hoare_lift all_goals omega -theorem max2_correct : Strata.Deep.Procedure.Correct max2_ast := by - unfold max2_ast - core_vcgen - all_goals core_lift - all_goals omega - theorem loopSimple_contract (params : Core.Logic.InitEnvWFParams) : Core.Logic.Hoare.Procedure.contractTriple demoPgm_ast params "loopSimple" := by hoare_contract @@ -128,12 +122,6 @@ theorem loopSimple_contract (params : Core.Logic.InitEnvWFParams) : all_goals hoare_lift all_goals first | omega | grind -theorem loopSimple_correct : Strata.Deep.Procedure.Correct loopSimple_ast := by - unfold loopSimple_ast - core_vcgen - all_goals core_lift - all_goals first | omega | grind - def morePgm : StrataDDM.Program := #strata program Boole; @@ -198,23 +186,12 @@ spec { count := count + 1; } }; - -procedure chooseIt (n: int) returns (r: int) -spec { - requires (n >= 0); - ensures [ge]: (r >= n); - ensures [lt]: (r < n + 2); -} -{ - r := ε z : int :: (z >= n && z < n + 2); -}; #end boole_prove morePgm sumTo boole_prove morePgm bounds boole_prove morePgm pick boole_prove morePgm addAll -boole_prove morePgm chooseIt deep with (first | omega | exact ⟨n, by omega⟩) /-- error: unsolved goals @@ -224,17 +201,7 @@ hguard : x ≥ y ⊢ x > x -/ #guard_msgs in -boole_prove demoPgm max2Wrong strata - -/-- -error: unsolved goals -case then.strict -y x : Int -hguard : y ≤ x -⊢ False --/ -#guard_msgs in -boole_prove demoPgm max2Wrong deep +boole_prove demoPgm max2Wrong /-- error: hoare: no rule for the statement @@ -242,50 +209,18 @@ error: hoare: no rule for the statement Supported: var, :=, havoc, assert, assume, cover, if, if *, { }, while, while *. -/ #guard_msgs in -boole_prove demoPgm caller strata - -/-- -error: core: no rule for the statement - ⟦call max2(x, x, out r)⟧ -Supported: var, :=, havoc, assert, assume, cover, if, if *, { }, while, while *. --/ -#guard_msgs in -boole_prove demoPgm caller deep +boole_prove demoPgm caller -/-- info: 'Strata.PipelineDemo.max2_contract' depends on axioms: [propext, - Classical.choice, - Quot.sound, - Core.WFFactory._native.native_decide.ax_1✝, - Core.WFFactoryArray_func_name_nodup._native.native_decide.ax_1_1✝] -/ +/-- info: 'Strata.PipelineDemo.max2_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ #guard_msgs in #print axioms max2_contract -/-- info: 'Strata.PipelineDemo.max2_correct' depends on axioms: [propext, Classical.choice, Quot.sound] -/ -#guard_msgs in -#print axioms max2_correct - -/-- info: 'Strata.PipelineDemo.loopSimple_contract' depends on axioms: [propext, - Classical.choice, - Quot.sound, - Core.WFFactory._native.native_decide.ax_1✝, - Core.WFFactoryArray_func_name_nodup._native.native_decide.ax_1_1✝] -/ +/-- info: 'Strata.PipelineDemo.loopSimple_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ #guard_msgs in #print axioms loopSimple_contract -/-- info: 'Strata.PipelineDemo.loopSimple_correct' depends on axioms: [propext, Classical.choice, Quot.sound] -/ -#guard_msgs in -#print axioms loopSimple_correct - -/-- info: 'Strata.PipelineDemo.sumTo_contract' depends on axioms: [propext, - Classical.choice, - Quot.sound, - Core.WFFactory._native.native_decide.ax_1✝, - Core.WFFactoryArray_func_name_nodup._native.native_decide.ax_1_1✝] -/ +/-- info: 'Strata.PipelineDemo.sumTo_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ #guard_msgs in #print axioms sumTo_contract -/-- info: 'Strata.PipelineDemo.chooseIt_correct' depends on axioms: [propext, Classical.choice, Quot.sound] -/ -#guard_msgs in -#print axioms chooseIt_correct - end Strata.PipelineDemo diff --git a/StrataBooleTest/HoareLogic/hoare_find_max_core.lean b/StrataBooleTest/HoareLogic/hoare_find_max_core.lean index 691d58b..5859147 100644 --- a/StrataBooleTest/HoareLogic/hoare_find_max_core.lean +++ b/StrataBooleTest/HoareLogic/hoare_find_max_core.lean @@ -4,18 +4,17 @@ SPDX-License-Identifier: Apache-2.0 OR MIT -/ import StrataBoole.HoareLogic.Reflect.Core -import StrataBoole.HoareLogic.Deep.Delab +import StrataBoole.HoareLogic.Delab import StrataBoole.HoareLogic.Hoare.Tactic import StrataDDM.Integration.Lean.HashCommands -/-! # The maximum of a map's first `n` entries: refused +/-! # The maximum of a map's first `n` entries: not read yet -The procedure reads `nums[0]` and `nums[i]`, applications of `select`, which `Core.Factory` has -no concrete evaluation for. `Expression.eval` then returns `none` on `var max : int := nums[0]`, -the statement has no execution, and every contract of the procedure holds vacuously of it. The -rules would prove any such contract, so `hoare_contract` refuses the procedure with an error -instead; the refusal is pinned below. The procedure becomes provable once `select` evaluates -over a map value form in Strata. -/ +The procedure reads `nums[0]` and `nums[i]`, applications of `select`. Every statement has an +execution, since the model of the runtime factory interprets `select`, so the rules apply and +the verification conditions are generated. The lifting has no lemma for `select`, though, so a +condition that reads the map stays an evaluation; the invariant `above` at the entry of the loop +is pinned below as it is left. The procedure becomes provable once the lifting reads maps. -/ open StrataDDM (Program) @@ -52,18 +51,37 @@ spec { }; #end -#core_reflect findMaxPgm +core_reflect findMaxPgm noncomputable def findMaxProg : Core.Program := { decls := [.proc findMax .empty] } example : findMaxProg.findProcByString? "findMax" = some findMax := rfl +open Lean Elab Tactic in +/-- Fail with the goal named `tag`, as it stands. -/ +elab "report_goal " tag:ident : tactic => do + for g in ← getGoals do + if (← g.getTag) == tag.getId then throwError "left unread:\n{g}" + throwError "no goal named `{tag.getId}`" + /-- -error: hoare: `var max := …` applies `select`, which `Core.Factory` does not evaluate: the statement has no execution, so its triple would hold vacuously +error: left unread: +case above +F : Core.Expression.Factory +n : Int +hnonempty : n > 0 +σ' : Core.CoreStore +⊢ Lambda.LExpr.denoteEval F (Imperative.dropVars [] σ') + ⟪forall __q0 : int :: 0 <= __q0 && __q0 < i ==> max >= select(nums, __q0)⟫ = + some (Imperative.HasBool.ttVal F) -/ #guard_msgs in example (params : Core.Logic.InitEnvWFParams) : Core.Logic.Hoare.Procedure.contractTriple findMaxProg params "findMax" := by hoare_contract + all_goals hoare_vcs + -- the entry of the loop: its three invariants + focus hoare_lift + report_goal above end Strata.HoareTest diff --git a/StrataBooleTest/HoareLogic/hoare_frame_core.lean b/StrataBooleTest/HoareLogic/hoare_frame_core.lean index 2209546..6e9b4bb 100644 --- a/StrataBooleTest/HoareLogic/hoare_frame_core.lean +++ b/StrataBooleTest/HoareLogic/hoare_frame_core.lean @@ -4,7 +4,7 @@ SPDX-License-Identifier: Apache-2.0 OR MIT -/ import StrataBoole.HoareLogic.Reflect.Core -import StrataBoole.HoareLogic.Deep.Delab +import StrataBoole.HoareLogic.Delab import StrataBoole.HoareLogic.Hoare.Tactic import StrataDDM.Integration.Lean.HashCommands @@ -84,7 +84,7 @@ spec { }; #end -#core_reflect framePgm +core_reflect framePgm noncomputable def frameProg : Core.Program := { decls := [.proc addK .empty, .proc keep .empty, .proc nested .empty] } @@ -111,27 +111,15 @@ theorem nested_contract (params : Core.Logic.InitEnvWFParams) : all_goals hoare_lift all_goals first | omega | grind -/-- info: 'Strata.HoareTest.addK_contract' depends on axioms: [propext, - Classical.choice, - Quot.sound, - Core.WFFactory._native.native_decide.ax_1✝, - Core.WFFactoryArray_func_name_nodup._native.native_decide.ax_1_1✝] -/ +/-- info: 'Strata.HoareTest.addK_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ #guard_msgs in #print axioms addK_contract -/-- info: 'Strata.HoareTest.keep_contract' depends on axioms: [propext, - Classical.choice, - Quot.sound, - Core.WFFactory._native.native_decide.ax_1✝, - Core.WFFactoryArray_func_name_nodup._native.native_decide.ax_1_1✝] -/ +/-- info: 'Strata.HoareTest.keep_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ #guard_msgs in #print axioms keep_contract -/-- info: 'Strata.HoareTest.nested_contract' depends on axioms: [propext, - Classical.choice, - Quot.sound, - Core.WFFactory._native.native_decide.ax_1✝, - Core.WFFactoryArray_func_name_nodup._native.native_decide.ax_1_1✝] -/ +/-- info: 'Strata.HoareTest.nested_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ #guard_msgs in #print axioms nested_contract diff --git a/StrataBooleTest/HoareLogic/hoare_havoc_core.lean b/StrataBooleTest/HoareLogic/hoare_havoc_core.lean new file mode 100644 index 0000000..f9cecbf --- /dev/null +++ b/StrataBooleTest/HoareLogic/hoare_havoc_core.lean @@ -0,0 +1,168 @@ +/- + Copyright Strata Contributors + + SPDX-License-Identifier: Apache-2.0 OR MIT +-/ +import StrataBoole.HoareLogic.Reflect.Core +import StrataBoole.HoareLogic.Delab +import StrataBoole.HoareLogic.Hoare.Tactic +import StrataDDM.Integration.Lean.HashCommands + +/-! # Values the program does not determine, against `Core.Logic.Hoare` + +`var x : int;` and `havoc x` give `x` a value about which the semantics says its type: a value +of the runtime factory whose sort is the declared one, or that of the value `x` held. The lifting +reads such a value as an `Int` or a `Bool` named like the variable, so what follows is read as +for any other value. `chosen` is the shape a Boole `choose` lowers to, into a local variable: an +`assert` of an `exists`, a `havoc`, an `assume`. A Boolean parameter is read like an integer one. + +`havoc` asks for the value the variable held, so its value is read only for a variable that was +declared or assigned. An output parameter that was never assigned has no type the entry knows; +`stale` pins what is left then. -/ + +open StrataDDM (Program) + +namespace Strata.HoareTest + +def havocPgm : Program := +#strata +program Core; + +procedure fresh(n : int, out r : int) +spec { + ensures [ge]: int.ge(r, n); +} +{ + var x : int; + assume [big]: int.ge(x, n); + r := x; +}; + +procedure again(n : int, b : bool, out r : int, out q : bool) +spec { + requires [pos]: int.gt(n, 0); + ensures [ge]: int.gt(r, 0); + ensures [flag]: q ==> b; +} +{ + r := n; + havoc r; + assume [up]: int.ge(r, n); + q := b; + havoc q; + assume [down]: !q || b; +}; + +procedure chosen(n : int, out r : int) +spec { + requires [nonneg]: int.ge(n, 0); + ensures [ge]: int.ge(r, n); + ensures [lt]: int.lt(r, int.add(n, 2)); +} +{ + var z : int; + assert [some_pick]: exists i : int :: int.ge(i, n) && int.lt(i, int.add(n, 2)); + havoc z; + assume [pick]: int.ge(z, n) && int.lt(z, int.add(n, 2)); + r := z; +}; + +procedure stale(n : int, out r : int) +spec { + ensures [ge]: int.ge(r, n); +} +{ + havoc r; + assume [up]: int.ge(r, n); +}; +#end + +core_reflect havocPgm + +noncomputable def havocProg : Core.Program := + { decls := [.proc fresh .empty, .proc again .empty, .proc chosen .empty, .proc stale .empty] } + +theorem fresh_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple havocProg params "fresh" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals first | omega | grind + +theorem again_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple havocProg params "again" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals first | omega | grind + +theorem chosen_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple havocProg params "chosen" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals first | omega | exact ⟨n, by omega⟩ + +/-! The conditions of `chosen` as the lifting leaves them: `z` is the value the declaration gave, +`z'` the one the `havoc` gave. -/ + +/-- +error: unsolved goals +case some_pick +n : Int +hnonneg : n ≥ 0 +z : Int +⊢ ∃ v, v ≥ n ∧ v < n + 2 + +case ge +n : Int +hnonneg : n ≥ 0 +z z' : Int +hpick : z' ≥ n ∧ z' < n + 2 +⊢ z' ≥ n + +case lt +n : Int +hnonneg : n ≥ 0 +z z' : Int +hpick : z' ≥ n ∧ z' < n + 2 +⊢ z' < n + 2 +-/ +#guard_msgs in +example (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple havocProg params "chosen" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + +/-! `r` was never assigned, so the value `havoc r` gives it is not read, and neither is the +condition that mentions it. -/ + +/-- +error: unsolved goals +case ge +F : Core.Expression.Factory +n : Int +σ' : Core.CoreStore +⊢ Lambda.LExpr.denoteEval F σ' ⟪r >= n⟫ = some (Imperative.HasBool.ttVal F) +-/ +#guard_msgs in +example (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple havocProg params "stale" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + +/-- info: 'Strata.HoareTest.fresh_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms fresh_contract + +/-- info: 'Strata.HoareTest.again_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms again_contract + +/-- info: 'Strata.HoareTest.chosen_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms chosen_contract + +end Strata.HoareTest diff --git a/StrataBooleTest/HoareLogic/hoare_havoc_gap.lean b/StrataBooleTest/HoareLogic/hoare_havoc_gap.lean deleted file mode 100644 index 9affbf1..0000000 --- a/StrataBooleTest/HoareLogic/hoare_havoc_gap.lean +++ /dev/null @@ -1,46 +0,0 @@ -/- - Copyright Strata Contributors - - SPDX-License-Identifier: Apache-2.0 OR MIT --/ -import StrataBoole.HoareLogic.Hoare.Tactic - -/-! # Why the value of a `havoc` is not lifted - -`havoc x` and `var x : int;` give `x` a value `v` about which the semantics says only -`HasVal.valueOfTy Core.Factory v int`: `v` is a value (`isValue`) and the syntactic type checker -assigns it `int`. Neither check looks at the type annotation an operator carries, so a partially -applied operator whose annotation lies is such a value, and it is not a numeral. The lifting -reads integer variables as numerals, so it cannot read `x` after a `havoc`; a `choose` lowers to -`assert ∃; havoc; assume` and stops there. Making `valueOfTy` canonical for the base types (as -`Procedure.valueHasType`, which types a procedure's inputs, already is) would close the gap; the -facts below are what such a change has to refute. -/ - -open Strata Core Lambda - -namespace Strata.HoareTest - -/-- `Int.Neg`, annotated as an integer: a value of type `int` that is not a numeral. -/ -def junk : Core.Expression.Expr := .op () ⟨"Int.Neg", ()⟩ (some .int) - -theorem junk_typeCheck : LExpr.typeCheck [] junk = some .int := rfl - -theorem junk_isValue : LExpr.isValue Core.Factory junk = true := by - rw [LExpr.isValue.eq_def] - simp only [junk, Lambda.Factory.callOfLFunc, Lambda.getLFuncCall, Lambda.getLFuncCall.go] - rw [Strata.Hoare.Eval.coreFactory_intNeg] - simp [Lambda.intNegFunc, Lambda.unaryOp] - -/-- The value a `havoc x` or an uninitialized `var x : int` may store. -/ -theorem junk_valueOfTy : - Imperative.HasVal.valueOfTy (P := Core.Expression) Core.Factory junk (.forAll [] .int) := - ⟨.int, junk_isValue, rfl, rfl⟩ - -/-- A clause reading `x` stays well typed, so its denotation is a real, model-dependent -proposition rather than a vacuous one. -/ -theorem junk_hasTypeA : LExpr.HasTypeA (T := Core.CoreLParams) [] junk .int := .op - -theorem junk_not_numeral (i : Int) : junk ≠ .const () (.intConst i) := by - simp [junk] - -end Strata.HoareTest diff --git a/StrataBooleTest/HoareLogic/hoare_locals_core.lean b/StrataBooleTest/HoareLogic/hoare_locals_core.lean index 39b7679..e169f16 100644 --- a/StrataBooleTest/HoareLogic/hoare_locals_core.lean +++ b/StrataBooleTest/HoareLogic/hoare_locals_core.lean @@ -4,7 +4,7 @@ SPDX-License-Identifier: Apache-2.0 OR MIT -/ import StrataBoole.HoareLogic.Reflect.Core -import StrataBoole.HoareLogic.Deep.Delab +import StrataBoole.HoareLogic.Delab import StrataBoole.HoareLogic.Hoare.Tactic import StrataDDM.Integration.Lean.HashCommands @@ -68,7 +68,7 @@ spec { }; #end -#core_reflect localsPgm +core_reflect localsPgm noncomputable def localsProg : Core.Program := { decls := [.proc sumTo .empty, .proc count .empty] } diff --git a/StrataBooleTest/HoareLogic/hoare_nondet_core.lean b/StrataBooleTest/HoareLogic/hoare_nondet_core.lean index 3d21233..e3c4904 100644 --- a/StrataBooleTest/HoareLogic/hoare_nondet_core.lean +++ b/StrataBooleTest/HoareLogic/hoare_nondet_core.lean @@ -4,7 +4,7 @@ SPDX-License-Identifier: Apache-2.0 OR MIT -/ import StrataBoole.HoareLogic.Reflect.Core -import StrataBoole.HoareLogic.Deep.Delab +import StrataBoole.HoareLogic.Delab import StrataBoole.HoareLogic.Hoare.Tactic import StrataDDM.Integration.Lean.HashCommands @@ -53,7 +53,7 @@ spec { }; #end -#core_reflect nondetPgm +core_reflect nondetPgm noncomputable def nondetProg : Core.Program := { decls := [.proc pick .empty, .proc drift .empty] } @@ -72,19 +72,11 @@ theorem drift_contract (params : Core.Logic.InitEnvWFParams) : all_goals hoare_lift all_goals omega -/-- info: 'Strata.HoareTest.pick_contract' depends on axioms: [propext, - Classical.choice, - Quot.sound, - Core.WFFactory._native.native_decide.ax_1✝, - Core.WFFactoryArray_func_name_nodup._native.native_decide.ax_1_1✝] -/ +/-- info: 'Strata.HoareTest.pick_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ #guard_msgs in #print axioms pick_contract -/-- info: 'Strata.HoareTest.drift_contract' depends on axioms: [propext, - Classical.choice, - Quot.sound, - Core.WFFactory._native.native_decide.ax_1✝, - Core.WFFactoryArray_func_name_nodup._native.native_decide.ax_1_1✝] -/ +/-- info: 'Strata.HoareTest.drift_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ #guard_msgs in #print axioms drift_contract diff --git a/StrataBooleTest/HoareLogic/hoare_ops_core.lean b/StrataBooleTest/HoareLogic/hoare_ops_core.lean index 82283bc..5ad60b7 100644 --- a/StrataBooleTest/HoareLogic/hoare_ops_core.lean +++ b/StrataBooleTest/HoareLogic/hoare_ops_core.lean @@ -4,16 +4,17 @@ SPDX-License-Identifier: Apache-2.0 OR MIT -/ import StrataBoole.HoareLogic.Reflect.Core -import StrataBoole.HoareLogic.Deep.Delab +import StrataBoole.HoareLogic.Delab import StrataBoole.HoareLogic.Hoare.Tactic import StrataDDM.Integration.Lean.HashCommands /-! # The remaining integer and boolean operators, against `Core.Logic.Hoare` Unary negation and `!`, the connectives `==>` and `<==>`, `==` on booleans, conditional -expressions, and guards built from `&&`, `||` and `!`. Each is read in two places: by the -evaluator when it sits in a guard or on the right of an assignment, and by the denotation when -it sits in a clause. -/ +expressions, guards built from `&&`, `||` and `!`, and division. Each is read in two places: by +the evaluation lemmas when it sits in a guard, on the right of an assignment or in a clause +without a quantifier, and by the denotation lemmas when it sits under a quantifier. A division is +read where its divisor is known to be non-zero. -/ open StrataDDM (Program) @@ -53,6 +54,24 @@ spec { } }; +procedure ratio(x : int, y : int, out r : int) +spec { + requires [pos]: int.gt(y, 0); + ensures [half]: int.le(int.mul(2, int.div(r, 2)), r); + ensures [same]: r == int.div(x, y); +} +{ + r := int.div(x, y); +}; + +procedure unguarded(x : int, y : int, out r : int) +spec { + ensures [same]: r == int.div(x, y); +} +{ + r := int.div(x, y); +}; + procedure countDown(n : int, out r : int) spec { requires [nonneg]: int.ge(n, 0); @@ -68,10 +87,11 @@ spec { }; #end -#core_reflect opsPgm +core_reflect opsPgm noncomputable def opsProg : Core.Program := - { decls := [.proc absVal .empty, .proc clamp .empty, .proc countDown .empty] } + { decls := [.proc absVal .empty, .proc clamp .empty, .proc ratio .empty, .proc unguarded .empty, + .proc countDown .empty] } theorem absVal_contract (params : Core.Logic.InitEnvWFParams) : Core.Logic.Hoare.Procedure.contractTriple opsProg params "absVal" := by @@ -87,6 +107,30 @@ theorem clamp_contract (params : Core.Logic.InitEnvWFParams) : all_goals hoare_lift all_goals first | omega | grind +theorem ratio_contract (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple opsProg params "ratio" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + all_goals first | omega | grind + +/-! Without a non-zero divisor the division is not read: `Int.Div` is interpreted only there. -/ + +/-- +error: unsolved goals +case same +F : Core.Expression.Factory +x y : Int +σ' : Core.CoreStore +⊢ Lambda.LExpr.denoteEval F σ' ⟪r == x / y⟫ = some (Imperative.HasBool.ttVal F) +-/ +#guard_msgs in +example (params : Core.Logic.InitEnvWFParams) : + Core.Logic.Hoare.Procedure.contractTriple opsProg params "unguarded" := by + hoare_contract + all_goals hoare_vcs + all_goals hoare_lift + theorem countDown_contract (params : Core.Logic.InitEnvWFParams) : Core.Logic.Hoare.Procedure.contractTriple opsProg params "countDown" := by hoare_contract @@ -94,27 +138,19 @@ theorem countDown_contract (params : Core.Logic.InitEnvWFParams) : all_goals hoare_lift all_goals first | omega | grind -/-- info: 'Strata.HoareTest.absVal_contract' depends on axioms: [propext, - Classical.choice, - Quot.sound, - Core.WFFactory._native.native_decide.ax_1✝, - Core.WFFactoryArray_func_name_nodup._native.native_decide.ax_1_1✝] -/ +/-- info: 'Strata.HoareTest.absVal_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ #guard_msgs in #print axioms absVal_contract -/-- info: 'Strata.HoareTest.clamp_contract' depends on axioms: [propext, - Classical.choice, - Quot.sound, - Core.WFFactory._native.native_decide.ax_1✝, - Core.WFFactoryArray_func_name_nodup._native.native_decide.ax_1_1✝] -/ +/-- info: 'Strata.HoareTest.clamp_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ #guard_msgs in #print axioms clamp_contract -/-- info: 'Strata.HoareTest.countDown_contract' depends on axioms: [propext, - Classical.choice, - Quot.sound, - Core.WFFactory._native.native_decide.ax_1✝, - Core.WFFactoryArray_func_name_nodup._native.native_decide.ax_1_1✝] -/ +/-- info: 'Strata.HoareTest.ratio_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ +#guard_msgs in +#print axioms ratio_contract + +/-- info: 'Strata.HoareTest.countDown_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ #guard_msgs in #print axioms countDown_contract diff --git a/StrataBooleTest/HoareLogic/hoare_quant_core.lean b/StrataBooleTest/HoareLogic/hoare_quant_core.lean index 75235f5..f8860e8 100644 --- a/StrataBooleTest/HoareLogic/hoare_quant_core.lean +++ b/StrataBooleTest/HoareLogic/hoare_quant_core.lean @@ -4,7 +4,7 @@ SPDX-License-Identifier: Apache-2.0 OR MIT -/ import StrataBoole.HoareLogic.Reflect.Core -import StrataBoole.HoareLogic.Deep.Delab +import StrataBoole.HoareLogic.Delab import StrataBoole.HoareLogic.Hoare.Tactic import StrataDDM.Integration.Lean.HashCommands @@ -71,7 +71,7 @@ spec { }; #end -#core_reflect quantPgm +core_reflect quantPgm noncomputable def quantProg : Core.Program := { decls := [.proc bounds .empty, .proc fromForall .empty, .proc fill .empty, .proc assumed .empty] } @@ -106,35 +106,19 @@ theorem assumed_contract (params : Core.Logic.InitEnvWFParams) : case gap => exact ⟨n, by omega⟩ all_goals omega -/-- info: 'Strata.HoareTest.bounds_contract' depends on axioms: [propext, - Classical.choice, - Quot.sound, - Core.WFFactory._native.native_decide.ax_1✝, - Core.WFFactoryArray_func_name_nodup._native.native_decide.ax_1_1✝] -/ +/-- info: 'Strata.HoareTest.bounds_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ #guard_msgs in #print axioms bounds_contract -/-- info: 'Strata.HoareTest.fromForall_contract' depends on axioms: [propext, - Classical.choice, - Quot.sound, - Core.WFFactory._native.native_decide.ax_1✝, - Core.WFFactoryArray_func_name_nodup._native.native_decide.ax_1_1✝] -/ +/-- info: 'Strata.HoareTest.fromForall_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ #guard_msgs in #print axioms fromForall_contract -/-- info: 'Strata.HoareTest.fill_contract' depends on axioms: [propext, - Classical.choice, - Quot.sound, - Core.WFFactory._native.native_decide.ax_1✝, - Core.WFFactoryArray_func_name_nodup._native.native_decide.ax_1_1✝] -/ +/-- info: 'Strata.HoareTest.fill_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ #guard_msgs in #print axioms fill_contract -/-- info: 'Strata.HoareTest.assumed_contract' depends on axioms: [propext, - Classical.choice, - Quot.sound, - Core.WFFactory._native.native_decide.ax_1✝, - Core.WFFactoryArray_func_name_nodup._native.native_decide.ax_1_1✝] -/ +/-- info: 'Strata.HoareTest.assumed_contract' depends on axioms: [propext, Classical.choice, Quot.sound] -/ #guard_msgs in #print axioms assumed_contract diff --git a/docs/HoareLogic.md b/docs/HoareLogic.md index be9a317..6378df7 100644 --- a/docs/HoareLogic.md +++ b/docs/HoareLogic.md @@ -192,8 +192,6 @@ kernel checks that proof for each program. - `hoare_lift` (`StrataBoole/HoareLogic/Hoare/Lift/`) lifts the `int` and `bool` built-ins, `==`, `if … then … else` and `∀`/`∃` over `int` to Lean propositions. - Not covered yet: `call`, `exit`, loop measures, `bv`, `choose`, `bool` parameters. -- `StrataBoole/HoareLogic/Deep/` proves the same programs against its own semantics, with - `core_vcgen` and `core_lift`, and also proves `choose`. - `max2` is proved against Strata's triple by hand (`StrataBooleTest/HoareLogic/hoare_max2.lean`): `contractTriple_of_core_typed`, then `block`, `block`, `ite` and `set`, side conditions by `native_decide`, operators lifted with Strata's lemmas and From f7245234e7cf9ddbb7c6c217c891d01c0783f560 Mon Sep 17 00:00:00 2001 From: Stephanie Ma Date: Mon, 30 Nov 2026 07:18:59 -0800 Subject: [PATCH 51/64] Port the Hoare route to Lean 4.35 and Strata 53a3ff3c - Proj.lean: the triple now also asks every assertion to hold on every finite execution, and the template rules no longer take the argument types. The four rules are proved again after Strata's `block`, `ite` and `while_rule`; the nondeterministic loop is split into `while_nondet_iterE`, `while_nondet_genE` and `while_nondet_prefixE`. - WP.lean, Rules.lean, Contract.lean, Tactic.lean: the new shapes of the triple, of `InitEnvWF` (`runtimeFactoryDeclared`), of a body (`opaque`, monotonicity at the entry) and of `contractPre` (five parts). - Reflect, Delab: `call` carries type arguments, a body is `structured` with an `opaque` flag or `abstract`, a program carries `usedIdentPrefixes`. - Lift: `Bool.And` and `Bool.Or` are read with Strata's lemmas, which HoareLift no longer has. --- StrataBoole/HoareLogic/Delab.lean | 6 +- StrataBoole/HoareLogic/Hoare/Contract.lean | 10 +- StrataBoole/HoareLogic/Hoare/Lift/Denote.lean | 4 +- StrataBoole/HoareLogic/Hoare/Lift/Eval.lean | 4 +- StrataBoole/HoareLogic/Hoare/Proj.lean | 365 +++++++++++------- StrataBoole/HoareLogic/Hoare/Rules.lean | 8 +- StrataBoole/HoareLogic/Hoare/Tactic.lean | 2 +- StrataBoole/HoareLogic/Hoare/WP.lean | 12 +- StrataBoole/HoareLogic/Reflect/Core.lean | 23 +- StrataBoole/HoareLogic/Reflect/ToExpr.lean | 14 +- StrataBooleTest/HoareLogic/boole_reflect.lean | 2 +- 11 files changed, 280 insertions(+), 170 deletions(-) diff --git a/StrataBoole/HoareLogic/Delab.lean b/StrataBoole/HoareLogic/Delab.lean index 6382ab6..cbe9995 100644 --- a/StrataBoole/HoareLogic/Delab.lean +++ b/StrataBoole/HoareLogic/Delab.lean @@ -439,9 +439,9 @@ partial def coreCommand : DelabM (TSyntax `core_stmt) := do let embed : DelabM (TSyntax `core_stmt) := do `(core_stmt| ⦃$(← withOptionAtCurrPos `pp.core false delab)⦄) if e.isAppOfArity ``Imperative.CmdExt.cmd 2 then withNaryArg 1 coreCmd - else if e.isAppOfArity ``Imperative.CmdExt.call 4 then + else if e.isAppOfArity ``Imperative.CmdExt.call 5 then let some p := strLit? (e.getArg! 1) | embed - let some args ← withNaryArg 2 (listLit? callArg) | embed + let some args ← withNaryArg 3 (listLit? callArg) | embed annot (← `(core_stmt| call $(nameIdent p)($args,*))) else embed where @@ -539,7 +539,7 @@ def coreProc : DelabM (TSyntax `core_proc) := do let some posts ← withNaryArg 6 (withNaryArg 2 (listLit? (clause true))) | failure let some clauses := (pres ++ posts).mapM id | failure let body := (e.getArg! 7).consumeMData - guard (body.isAppOfArity ``Imperative.Body.structured 3) + guard (body.isAppOfArity ``Imperative.Body.structured 4) let some ss ← withNaryArg 7 (withNaryArg 2 (listLit? coreStmt)) | failure `(core_proc| procedure $(nameIdent name)($params,*) spec { $[$clauses;]* } { $ss;* }) diff --git a/StrataBoole/HoareLogic/Hoare/Contract.lean b/StrataBoole/HoareLogic/Hoare/Contract.lean index ef5ff25..5be3643 100644 --- a/StrataBoole/HoareLogic/Hoare/Contract.lean +++ b/StrataBoole/HoareLogic/Hoare/Contract.lean @@ -57,20 +57,22 @@ Every admitted entry has a store of values of its runtime factory (`of_storeWF_p runtime factory may be fixed because the triple quantifies over the entries (`of_forall_entryFactory`). -/ theorem contract_intro (p : Core.Program) (params : InitEnvWFParams) (procName : String) - (proc : Core.Procedure) (bss : Core.Statements) + (proc : Core.Procedure) (bss : Core.Statements) {opq : Bool} (hproc : p.findProcByString? procName = some proc) - (hbody : proc.body = .structured bss) + (hbody : proc.body = .structured bss opq) (hchecksTyped : Procedure.contractChecksTyped proc) (hfuns : (p.declsBeforeProcedure procName).all fun d => match d with | .func _ _ | .recFuncBlock _ _ => false + | .type (.data _) _ => false | _ => true) (h : ∀ F : Core.Expression.Factory, Triple p.findProcByString? params (entryPre proc F) [Imperative.Stmt.block "" bss #[]] - (Procedure.contractPost Core.Factory proc)) : + (Procedure.contractPost Core.Factory proc)) + (hmono : proc.header.typeArgs = [] := by first | rfl | decide) : Procedure.contractTriple p params procName := by refine Procedure.contractTriple_of_core_typed p params procName proc bss hproc hbody - hchecksTyped ?_ + hchecksTyped ?_ hmono rw [Core.Program.factoryBeforeProcedure_eq_core_of_noFunctions hfuns] refine Core.Logic.Hoare.of_storeWF_pre _ params (Core.Logic.Hoare.of_forall_entryFactory _ params fun F => ?_) diff --git a/StrataBoole/HoareLogic/Hoare/Lift/Denote.lean b/StrataBoole/HoareLogic/Hoare/Lift/Denote.lean index a75aa03..79d65ff 100644 --- a/StrataBoole/HoareLogic/Hoare/Lift/Denote.lean +++ b/StrataBoole/HoareLogic/Hoare/Lift/Denote.lean @@ -448,7 +448,7 @@ theorem denote_and (hfac : f.factory = Core.Factory) = (toBool (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv e₁ tBool h₁) && toBool (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv e₂ tBool h₂)) := (denote_app2 (a := .bool) (b := .bool) (c := .bool) fv vt bv h₁ h₂ h).trans - (HoareLift.boolAnd_opInterp_of_lookup f.model (hfac ▸ HoareLift.coreFactory_boolAnd) _ _) + (Core.boolAnd_opInterp_of_lookup f.model (hfac ▸ Core.coreFactory_boolAnd) _ _) theorem denote_or (hfac : f.factory = Core.Factory) (h₁ : LExpr.HasTypeA Δ e₁ tBool) (h₂ : LExpr.HasTypeA Δ e₂ tBool) @@ -461,7 +461,7 @@ theorem denote_or (hfac : f.factory = Core.Factory) = (toBool (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv e₁ tBool h₁) || toBool (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv e₂ tBool h₂)) := (denote_app2 (a := .bool) (b := .bool) (c := .bool) fv vt bv h₁ h₂ h).trans - (HoareLift.boolOr_opInterp_of_lookup f.model (hfac ▸ HoareLift.coreFactory_boolOr) _ _) + (Core.boolOr_opInterp_of_lookup f.model (hfac ▸ Core.coreFactory_boolOr) _ _) theorem denote_implies (hfac : f.factory = Core.Factory) (h₁ : LExpr.HasTypeA Δ e₁ tBool) (h₂ : LExpr.HasTypeA Δ e₂ tBool) diff --git a/StrataBoole/HoareLogic/Hoare/Lift/Eval.lean b/StrataBoole/HoareLogic/Hoare/Lift/Eval.lean index 5bd0235..4bb93eb 100644 --- a/StrataBoole/HoareLogic/Hoare/Lift/Eval.lean +++ b/StrataBoole/HoareLogic/Hoare/Lift/Eval.lean @@ -379,7 +379,7 @@ theorem eval_and {p q : Bool} (hfac : f.factory = Core.Factory) (.app m (.app m' (.op m'' ⟨"Bool.And", ()⟩ (some (tArrow tBool (tArrow tBool tBool)))) x) y) = some (boolVal f (p && q)) := Core.eval_app2_op "Bool.And" (c := .bool) rfl rfl rfl hx hy - (HoareLift.boolAnd_opInterp_of_lookup f.model (hfac ▸ HoareLift.coreFactory_boolAnd) p q) + (Core.boolAnd_opInterp_of_lookup f.model (hfac ▸ Core.coreFactory_boolAnd) p q) theorem eval_or {p q : Bool} (hfac : f.factory = Core.Factory) (hx : LExpr.denoteEval f σ x = some (boolVal f p)) @@ -388,7 +388,7 @@ theorem eval_or {p q : Bool} (hfac : f.factory = Core.Factory) (.app m (.app m' (.op m'' ⟨"Bool.Or", ()⟩ (some (tArrow tBool (tArrow tBool tBool)))) x) y) = some (boolVal f (p || q)) := Core.eval_app2_op "Bool.Or" (c := .bool) rfl rfl rfl hx hy - (HoareLift.boolOr_opInterp_of_lookup f.model (hfac ▸ HoareLift.coreFactory_boolOr) p q) + (Core.boolOr_opInterp_of_lookup f.model (hfac ▸ Core.coreFactory_boolOr) p q) theorem eval_implies {p q : Bool} (hfac : f.factory = Core.Factory) (hx : LExpr.denoteEval f σ x = some (boolVal f p)) diff --git a/StrataBoole/HoareLogic/Hoare/Proj.lean b/StrataBoole/HoareLogic/Hoare/Proj.lean index 6eb4e41..2fedcd5 100644 --- a/StrataBoole/HoareLogic/Hoare/Proj.lean +++ b/StrataBoole/HoareLogic/Hoare/Proj.lean @@ -34,11 +34,9 @@ variable [HasFvar P] [HasFvars P] [HasBool P] [HasBoolOps P] [HasSubstFvar P] [HasInt P] [HasIntOps P] variable {CmdT : Type} variable (evalCmd : EvalCmdParamE P CmdT (Event P)) -variable {ParamsTy : Type} -variable (initEnvWF : ParamsTy → Stmt P CmdT → Env P → Prop) -variable {BParamsTy : Type} -variable (blockInitEnvWF : BParamsTy → List (Stmt P CmdT) → Env P → Prop) -variable (bparams : BParamsTy) +variable (initEnvWF : InitEnvWFParams P → Stmt P CmdT → Env P → Prop) +variable (blockInitEnvWF : InitEnvWFParams P → List (Stmt P CmdT) → Env P → Prop) +variable (bparams : InitEnvWFParams P) variable [HasIdent P] [DecidableEq P.Ident] [HasVarsImp P CmdT] /-- `Post` at the environment that leaves a block whose body declared the names `D`. -/ @@ -46,7 +44,7 @@ abbrev projected (D : List P.Ident) (Post : Env P → Prop) : Env P → Prop := fun ρ => Post { ρ with store := dropVars D ρ.store } /-- `block` with the projection in the body's postcondition instead of `PostWF`. -/ -theorem block_proj (params : ParamsTy) +theorem block_proj (params : InitEnvWFParams P) {ss : List (Stmt P CmdT)} {l : String} {md : MetaData P} {Pre Post : Env P → Prop} (h_cmd : ∀ {f : P.Factory} {σ σ' : SemanticStore P} {c : CmdT} {emitted : Trace P} {y : P.Ident}, @@ -55,28 +53,61 @@ theorem block_proj (params : ParamsTy) (hbodyWF : ∀ ρ, initEnvWF params (.block l ss md) ρ → blockInitEnvWF bparams ss ρ) (hbodyDefs : ∀ ρ, initEnvWF params (.block l ss md) ρ → ∀ x ∈ Block.definedVars (P := P) (C := CmdT) ss true, ρ.store x = none) - (h : TripleWith (EventLang.imperativeBlockE P CmdT evalCmd ⟨BParamsTy, blockInitEnvWF⟩) + (h : TripleWith (EventLang.imperativeBlockE P CmdT evalCmd blockInitEnvWF) conditionInterp bparams Pre ss (projected (Block.definedVars (P := P) (C := CmdT) ss true) Post)) : - TripleWith (EventLang.imperativeE P CmdT evalCmd ParamsTy initEnvWF) conditionInterp params + TripleWith (EventLang.imperativeE P CmdT evalCmd initEnvWF) conditionInterp params Pre (.block l ss md) Post := by - intro ρ₀ ρ' trace hpre hinit hrun + intro ρ₀ hpre hinit + obtain ⟨hvalid, hruns⟩ := h ρ₀ hpre (hbodyWF ρ₀ hinit) + refine ⟨fun cfg trace hrun => ?_, fun ρ' trace hrun hf => ?_⟩ + · obtain ⟨inner', h'⟩ := stmt_block_prefixE (EvalCmd := evalCmd) hrun + exact hvalid inner' trace h' obtain ⟨ρ_inner, hrun_inner, heq⟩ := stmt_block_reaches_doneE hrun - have ⟨hvalid, hpost⟩ := h ρ₀ ρ_inner trace hpre (hbodyWF ρ₀ hinit) hrun_inner have hproj : projectStore ρ₀.store ρ_inner.store = dropVars (Block.definedVars (P := P) (C := CmdT) ss true) ρ_inner.store := projectStore_eq_dropVarsE h_cmd (hbodyDefs ρ₀ hinit) hrun_inner subst heq - refine ⟨hvalid, fun hf => ?_⟩ have hrec : ({ ρ_inner with store := projectStore ρ₀.store ρ_inner.store } : Env P) = { ρ_inner with store := dropVars (Block.definedVars (P := P) (C := CmdT) ss true) ρ_inner.store } := by rw [hproj] rw [hrec] - exact hpost hf + exact hruns ρ_inner trace hrun_inner hf + +/-- The taken branch of an `ite` ran inside its block to a terminal or exiting configuration: +the postcondition holds at the environment that leaves the block. -/ +theorem branch_projE + {ρ₀ ρ' : Env P} {Post : Env P → Prop} + (h_cmd : ∀ {f : P.Factory} {σ σ' : SemanticStore P} {c : CmdT} {emitted : Trace P} {y : P.Ident}, + evalCmd f σ c σ' emitted → σ y = none → + y ∉ HasVarsImp.definedVars (P := P) c true → σ' y = none) + (bss : List (Stmt P CmdT)) (Pre' : Env P → Prop) (tr : Trace P) + (hpre' : Pre' ρ₀) (hbwf : blockInitEnvWF bparams bss ρ₀) + (hbdefs : ∀ x ∈ Block.definedVars (P := P) (C := CmdT) bss true, ρ₀.store x = none) + (hb : TripleWith (EventLang.imperativeBlockE P CmdT evalCmd blockInitEnvWF) + conditionInterp bparams Pre' bss + (projected (Block.definedVars (P := P) (C := CmdT) bss true) Post)) + (hdone_b : StepStmtStarE P evalCmd + (.block .none ρ₀.store (.stmts bss ρ₀)) tr (.terminal ρ') ∨ + ∃ lbl, StepStmtStarE P evalCmd + (.block .none ρ₀.store (.stmts bss ρ₀)) tr (.exiting lbl ρ')) + (hf : Trace.Reachable P conditionInterp tr) : Post ρ' := by + obtain ⟨ρ_inner, hrun_inner, heq⟩ := block_reaches_doneE hdone_b + have hpost := (hb ρ₀ hpre' hbwf).2 ρ_inner tr hrun_inner hf + have hproj : projectStore ρ₀.store ρ_inner.store + = dropVars (Block.definedVars (P := P) (C := CmdT) bss true) ρ_inner.store := + projectStore_eq_dropVarsE h_cmd hbdefs hrun_inner + subst heq + have hrec : ({ ρ_inner with store := projectStore ρ₀.store ρ_inner.store } : Env P) + = { ρ_inner with + store := dropVars (Block.definedVars (P := P) (C := CmdT) bss true) ρ_inner.store } := by + rw [hproj] + rw [hrec] + exact hpost /-- `ite` with the projection in each branch's postcondition instead of `PostWF`. -/ -theorem ite_proj (params : ParamsTy) +theorem ite_proj (params : InitEnvWFParams P) {cond : P.Expr} {tss ess : List (Stmt P CmdT)} {md : MetaData P} {Pre Post : Env P → Prop} (h_cmd : ∀ {f : P.Factory} {σ σ' : SemanticStore P} {c : CmdT} {emitted : Trace P} {y : P.Ident}, @@ -90,62 +121,51 @@ theorem ite_proj (params : ParamsTy) ∀ x ∈ Block.definedVars (P := P) (C := CmdT) tss true, ρ.store x = none) (helseDefs : ∀ ρ, initEnvWF params (.ite (.det cond) tss ess md) ρ → ∀ x ∈ Block.definedVars (P := P) (C := CmdT) ess true, ρ.store x = none) - (ht : TripleWith (EventLang.imperativeBlockE P CmdT evalCmd ⟨BParamsTy, blockInitEnvWF⟩) + (ht : TripleWith (EventLang.imperativeBlockE P CmdT evalCmd blockInitEnvWF) conditionInterp bparams (fun ρ => Pre ρ ∧ P.eval ρ.factory ρ.store cond = some (HasBool.ttVal ρ.factory)) tss (projected (Block.definedVars (P := P) (C := CmdT) tss true) Post)) - (he : TripleWith (EventLang.imperativeBlockE P CmdT evalCmd ⟨BParamsTy, blockInitEnvWF⟩) + (he : TripleWith (EventLang.imperativeBlockE P CmdT evalCmd blockInitEnvWF) conditionInterp bparams (fun ρ => Pre ρ ∧ P.eval ρ.factory ρ.store cond = some (HasBool.ffVal ρ.factory)) ess (projected (Block.definedVars (P := P) (C := CmdT) ess true) Post)) : - TripleWith (EventLang.imperativeE P CmdT evalCmd ParamsTy initEnvWF) conditionInterp params + TripleWith (EventLang.imperativeE P CmdT evalCmd initEnvWF) conditionInterp params Pre (.ite (.det cond) tss ess md) Post := by - intro ρ₀ ρ' trace hpre hinit hrun - have hbranch : ∀ (bss : List (Stmt P CmdT)) (Pre' : Env P → Prop) (tr : Trace P), - Pre' ρ₀ → blockInitEnvWF bparams bss ρ₀ → - (∀ x ∈ Block.definedVars (P := P) (C := CmdT) bss true, ρ₀.store x = none) → - TripleWith (EventLang.imperativeBlockE P CmdT evalCmd ⟨BParamsTy, blockInitEnvWF⟩) - conditionInterp bparams Pre' bss - (projected (Block.definedVars (P := P) (C := CmdT) bss true) Post) → - (StepStmtStarE P evalCmd - (.block .none ρ₀.store (.stmts bss ρ₀)) tr (.terminal ρ') ∨ - ∃ lbl, StepStmtStarE P evalCmd - (.block .none ρ₀.store (.stmts bss ρ₀)) tr (.exiting lbl ρ')) → - Trace.AssertionsValid P conditionInterp tr ∧ - (Trace.Reachable P conditionInterp tr → Post ρ') := by - intro bss Pre' tr hpre' hbwf hbdefs hb hdone_b - obtain ⟨ρ_inner, hrun_inner, heq⟩ := block_reaches_doneE hdone_b - have ⟨hvalid, hpost⟩ := hb ρ₀ ρ_inner tr hpre' hbwf hrun_inner - have hproj : projectStore ρ₀.store ρ_inner.store - = dropVars (Block.definedVars (P := P) (C := CmdT) bss true) ρ_inner.store := - projectStore_eq_dropVarsE h_cmd hbdefs hrun_inner - subst heq - refine ⟨hvalid, fun hf => ?_⟩ - have hrec : ({ ρ_inner with store := projectStore ρ₀.store ρ_inner.store } : Env P) - = { ρ_inner with - store := dropVars (Block.definedVars (P := P) (C := CmdT) bss true) ρ_inner.store } := by - rw [hproj] - rw [hrec] - exact hpost hf + intro ρ₀ hpre hinit + refine ⟨fun cfg trace hrun => ?_, fun ρ' trace hrun hf => ?_⟩ + · cases hrun with + | refl => exact True.intro + | step _ _ _ rest _ hstep hrest => + cases hstep with + | step_ite_true hc => + obtain ⟨inner', h'⟩ := block_run_inner_prefixE hrest + simpa using (ht ρ₀ ⟨hpre, hc⟩ (hthenWF ρ₀ hinit)).1 inner' rest h' + | step_ite_false hc => + obtain ⟨inner', h'⟩ := block_run_inner_prefixE hrest + simpa using (he ρ₀ ⟨hpre, hc⟩ (helseWF ρ₀ hinit)).1 inner' rest h' rcases hrun with hterm | ⟨lbl, hexit⟩ · cases hterm with | step _ _ _ _ _ hstep hrest => cases hstep with | step_ite_true hc => - exact hbranch tss _ _ ⟨hpre, hc⟩ (hthenWF ρ₀ hinit) - (hthenDefs ρ₀ hinit) ht (.inl (by simpa using hrest)) + exact branch_projE evalCmd blockInitEnvWF bparams h_cmd tss _ _ ⟨hpre, hc⟩ + (hthenWF ρ₀ hinit) (hthenDefs ρ₀ hinit) ht (.inl (by simpa using hrest)) + (by simpa using hf) | step_ite_false hc => - exact hbranch ess _ _ ⟨hpre, hc⟩ (helseWF ρ₀ hinit) - (helseDefs ρ₀ hinit) he (.inl (by simpa using hrest)) + exact branch_projE evalCmd blockInitEnvWF bparams h_cmd ess _ _ ⟨hpre, hc⟩ + (helseWF ρ₀ hinit) (helseDefs ρ₀ hinit) he (.inl (by simpa using hrest)) + (by simpa using hf) · cases hexit with | step _ _ _ _ _ hstep hrest => cases hstep with | step_ite_true hc => - exact hbranch tss _ _ ⟨hpre, hc⟩ (hthenWF ρ₀ hinit) - (hthenDefs ρ₀ hinit) ht (.inr ⟨lbl, by simpa using hrest⟩) + exact branch_projE evalCmd blockInitEnvWF bparams h_cmd tss _ _ ⟨hpre, hc⟩ + (hthenWF ρ₀ hinit) (hthenDefs ρ₀ hinit) ht (.inr ⟨lbl, by simpa using hrest⟩) + (by simpa using hf) | step_ite_false hc => - exact hbranch ess _ _ ⟨hpre, hc⟩ (helseWF ρ₀ hinit) - (helseDefs ρ₀ hinit) he (.inr ⟨lbl, by simpa using hrest⟩) + exact branch_projE evalCmd blockInitEnvWF bparams h_cmd ess _ _ ⟨hpre, hc⟩ + (helseWF ρ₀ hinit) (helseDefs ρ₀ hinit) he (.inr ⟨lbl, by simpa using hrest⟩) + (by simpa using hf) /-! ## Nondeterministic branches and loops @@ -153,7 +173,7 @@ theorem ite_proj (params : ParamsTy) to learn from. The rules are `ite_proj` and `Imperative.Logic.Hoare.while_rule` with the guard hypotheses removed, following the nondeterministic steps of the semantics. -/ -theorem ite_nondet_proj (params : ParamsTy) +theorem ite_nondet_proj (params : InitEnvWFParams P) {tss ess : List (Stmt P CmdT)} {md : MetaData P} {Pre Post : Env P → Prop} (h_cmd : ∀ {f : P.Factory} {σ σ' : SemanticStore P} {c : CmdT} {emitted : Trace P} {y : P.Ident}, @@ -167,67 +187,97 @@ theorem ite_nondet_proj (params : ParamsTy) ∀ x ∈ Block.definedVars (P := P) (C := CmdT) tss true, ρ.store x = none) (helseDefs : ∀ ρ, initEnvWF params (.ite .nondet tss ess md) ρ → ∀ x ∈ Block.definedVars (P := P) (C := CmdT) ess true, ρ.store x = none) - (ht : TripleWith (EventLang.imperativeBlockE P CmdT evalCmd ⟨BParamsTy, blockInitEnvWF⟩) + (ht : TripleWith (EventLang.imperativeBlockE P CmdT evalCmd blockInitEnvWF) conditionInterp bparams Pre tss (projected (Block.definedVars (P := P) (C := CmdT) tss true) Post)) - (he : TripleWith (EventLang.imperativeBlockE P CmdT evalCmd ⟨BParamsTy, blockInitEnvWF⟩) + (he : TripleWith (EventLang.imperativeBlockE P CmdT evalCmd blockInitEnvWF) conditionInterp bparams Pre ess (projected (Block.definedVars (P := P) (C := CmdT) ess true) Post)) : - TripleWith (EventLang.imperativeE P CmdT evalCmd ParamsTy initEnvWF) conditionInterp params + TripleWith (EventLang.imperativeE P CmdT evalCmd initEnvWF) conditionInterp params Pre (.ite .nondet tss ess md) Post := by - intro ρ₀ ρ' trace hpre hinit hrun - have hbranch : ∀ (bss : List (Stmt P CmdT)) (Pre' : Env P → Prop) (tr : Trace P), - Pre' ρ₀ → blockInitEnvWF bparams bss ρ₀ → - (∀ x ∈ Block.definedVars (P := P) (C := CmdT) bss true, ρ₀.store x = none) → - TripleWith (EventLang.imperativeBlockE P CmdT evalCmd ⟨BParamsTy, blockInitEnvWF⟩) - conditionInterp bparams Pre' bss - (projected (Block.definedVars (P := P) (C := CmdT) bss true) Post) → - (StepStmtStarE P evalCmd - (.block .none ρ₀.store (.stmts bss ρ₀)) tr (.terminal ρ') ∨ - ∃ lbl, StepStmtStarE P evalCmd - (.block .none ρ₀.store (.stmts bss ρ₀)) tr (.exiting lbl ρ')) → - Trace.AssertionsValid P conditionInterp tr ∧ - (Trace.Reachable P conditionInterp tr → Post ρ') := by - intro bss Pre' tr hpre' hbwf hbdefs hb hdone_b - obtain ⟨ρ_inner, hrun_inner, heq⟩ := block_reaches_doneE hdone_b - have ⟨hvalid, hpost⟩ := hb ρ₀ ρ_inner tr hpre' hbwf hrun_inner - have hproj : projectStore ρ₀.store ρ_inner.store - = dropVars (Block.definedVars (P := P) (C := CmdT) bss true) ρ_inner.store := - projectStore_eq_dropVarsE h_cmd hbdefs hrun_inner - subst heq - refine ⟨hvalid, fun hf => ?_⟩ - have hrec : ({ ρ_inner with store := projectStore ρ₀.store ρ_inner.store } : Env P) - = { ρ_inner with - store := dropVars (Block.definedVars (P := P) (C := CmdT) bss true) ρ_inner.store } := by - rw [hproj] - rw [hrec] - exact hpost hf + intro ρ₀ hpre hinit + refine ⟨fun cfg trace hrun => ?_, fun ρ' trace hrun hf => ?_⟩ + · cases hrun with + | refl => exact True.intro + | step _ _ _ rest _ hstep hrest => + cases hstep with + | step_ite_nondet_true => + obtain ⟨inner', h'⟩ := block_run_inner_prefixE hrest + simpa using (ht ρ₀ hpre (hthenWF ρ₀ hinit)).1 inner' rest h' + | step_ite_nondet_false => + obtain ⟨inner', h'⟩ := block_run_inner_prefixE hrest + simpa using (he ρ₀ hpre (helseWF ρ₀ hinit)).1 inner' rest h' rcases hrun with hterm | ⟨lbl, hexit⟩ · cases hterm with | step _ _ _ _ _ hstep hrest => cases hstep with | step_ite_nondet_true => - exact hbranch tss _ _ hpre (hthenWF ρ₀ hinit) - (hthenDefs ρ₀ hinit) ht (.inl (by simpa using hrest)) + exact branch_projE evalCmd blockInitEnvWF bparams h_cmd tss _ _ hpre + (hthenWF ρ₀ hinit) (hthenDefs ρ₀ hinit) ht (.inl (by simpa using hrest)) + (by simpa using hf) | step_ite_nondet_false => - exact hbranch ess _ _ hpre (helseWF ρ₀ hinit) - (helseDefs ρ₀ hinit) he (.inl (by simpa using hrest)) + exact branch_projE evalCmd blockInitEnvWF bparams h_cmd ess _ _ hpre + (helseWF ρ₀ hinit) (helseDefs ρ₀ hinit) he (.inl (by simpa using hrest)) + (by simpa using hf) · cases hexit with | step _ _ _ _ _ hstep hrest => cases hstep with | step_ite_nondet_true => - exact hbranch tss _ _ hpre (hthenWF ρ₀ hinit) - (hthenDefs ρ₀ hinit) ht (.inr ⟨lbl, by simpa using hrest⟩) + exact branch_projE evalCmd blockInitEnvWF bparams h_cmd tss _ _ hpre + (hthenWF ρ₀ hinit) (hthenDefs ρ₀ hinit) ht (.inr ⟨lbl, by simpa using hrest⟩) + (by simpa using hf) | step_ite_nondet_false => - exact hbranch ess _ _ hpre (helseWF ρ₀ hinit) - (helseDefs ρ₀ hinit) he (.inr ⟨lbl, by simpa using hrest⟩) + exact branch_projE evalCmd blockInitEnvWF bparams h_cmd ess _ _ hpre + (helseWF ρ₀ hinit) (helseDefs ρ₀ hinit) he (.inr ⟨lbl, by simpa using hrest⟩) + (by simpa using hf) + +/-- Helper for `while_nondet`: an iteration that terminates along a reachable trace, from an +entry satisfying the invariant that the loop's gate admits, ends at such an entry. -/ +theorem while_nondet_iterE + {measure : Option P.Expr} {inv : List (String × P.Expr)} + {body : List (Stmt P CmdT)} {md : MetaData P} + {Inv : Env P → Prop} (params : InitEnvWFParams P) + (h_cmd : ∀ {f : P.Factory} {σ σ' : SemanticStore P} {c : CmdT} {emitted : Trace P} {y : P.Ident}, + evalCmd f σ c σ' emitted → σ y = none → + y ∉ HasVarsImp.definedVars (P := P) c true → σ' y = none) + (hbodyDefs : ∀ ρ, initEnvWF params (.loop .nondet measure inv body md) ρ → + ∀ x ∈ Block.definedVars (P := P) (C := CmdT) body true, ρ.store x = none) + (hloopBodyWF : ∀ ρ, initEnvWF params (.loop .nondet measure inv body md) ρ → + blockInitEnvWF bparams body ρ) + (hloopWF : ∀ ρ ρ_inner tr, initEnvWF params (.loop .nondet measure inv body md) ρ → + StepStmtStarE P evalCmd (.stmts body ρ) tr (.terminal ρ_inner) → + initEnvWF params (.loop .nondet measure inv body md) + { ρ_inner with store := projectStore ρ.store ρ_inner.store }) + (hbody : TripleWith (EventLang.imperativeBlockE P CmdT evalCmd blockInitEnvWF) + conditionInterp bparams Inv body Inv) + (hcov : Block.exitsCoveredByBlocks (P := P) (CmdT := CmdT) [] body) + (hInv_proj : PostWF body Inv) + {ρ ρ₁ : Env P} {tr : Trace P} (hInv : Inv ρ) + (hwf : initEnvWF params (.loop .nondet measure inv body md) ρ) + (hrun : StepStmtStarE P evalCmd (.block .none ρ.store (.stmts body ρ)) tr (.terminal ρ₁)) + (hreach : Trace.Reachable P conditionInterp tr) : + Inv ρ₁ ∧ initEnvWF params (.loop .nondet measure inv body md) ρ₁ := by + obtain ⟨ρ_inner, hdisj, hρ₁⟩ := block_reaches_doneE (.inl hrun) + have hbrun : StepStmtStarE P evalCmd (.stmts body ρ) tr (.terminal ρ_inner) := by + rcases hdisj with hterm | ⟨lbl, hexit⟩ + · exact hterm + · exact absurd hexit (stmts_exitsCoveredByBlocks_noEscapeE evalCmd body hcov ρ lbl ρ_inner) + have hproj : projectStore ρ.store ρ_inner.store + = dropVars (Block.definedVars (P := P) (C := CmdT) body true) ρ_inner.store := + projectStore_eq_dropVarsE h_cmd (hbodyDefs ρ hwf) (.inl hbrun) + refine ⟨?_, ?_⟩ + · rw [hρ₁, hproj] + exact hInv_proj ρ_inner ((hbody ρ hInv (hloopBodyWF ρ hwf)).2 ρ_inner tr + (.inl hbrun) hreach) + · rw [hρ₁] + exact hloopWF ρ ρ_inner tr hwf hbrun -/-- Helper for `while_nondet`: the invariant survives arbitrarily many iterations, and the -completed trace is assertion-valid. By strong induction on the length of the derivation. -/ +/-- Helper for `while_nondet`: the invariant survives arbitrarily many iterations of a run that +finishes. By strong induction on the length of the derivation. -/ theorem while_nondet_genE {measure : Option P.Expr} {inv : List (String × P.Expr)} {body : List (Stmt P CmdT)} {md : MetaData P} - {Inv : Env P → Prop} (params : ParamsTy) + {Inv : Env P → Prop} (params : InitEnvWFParams P) (h_cmd : ∀ {f : P.Factory} {σ σ' : SemanticStore P} {c : CmdT} {emitted : Trace P} {y : P.Ident}, evalCmd f σ c σ' emitted → σ y = none → y ∉ HasVarsImp.definedVars (P := P) c true → σ' y = none) @@ -239,7 +289,7 @@ theorem while_nondet_genE StepStmtStarE P evalCmd (.stmts body ρ) tr (.terminal ρ_inner) → initEnvWF params (.loop .nondet measure inv body md) { ρ_inner with store := projectStore ρ.store ρ_inner.store }) - (hbody : TripleWith (EventLang.imperativeBlockE P CmdT evalCmd ⟨BParamsTy, blockInitEnvWF⟩) + (hbody : TripleWith (EventLang.imperativeBlockE P CmdT evalCmd blockInitEnvWF) conditionInterp bparams Inv body Inv) (hcov : Block.exitsCoveredByBlocks (P := P) (CmdT := CmdT) [] body) (hInv_proj : PostWF body Inv) @@ -249,8 +299,7 @@ theorem while_nondet_genE (hrunT : ReflTransTraceT (StepStmtE P evalCmd) (.stmt (.loop .nondet measure inv body md) ρ₀) trace (.terminal ρ')) (hlen : hrunT.len ≤ n) : - Trace.AssertionsValid P conditionInterp trace ∧ - (Trace.Reachable P conditionInterp trace → Inv ρ') := by + Trace.Reachable P conditionInterp trace → Inv ρ' := by induction n generalizing ρ₀ ρ' trace with | zero => match hrunT, hlen with @@ -258,22 +307,14 @@ theorem while_nondet_genE | succ n ih => match hrunT, hlen with | .step _ _ _ restTr _ .step_loop_nondet_exit hrest, hlen => - obtain ⟨hc, hnil⟩ := Imperative.stepStmtStarE_from_terminal (reflTransTraceT_to_prop hrest) - subst hnil + obtain ⟨hc, _⟩ := Imperative.stepStmtStarE_from_terminal (reflTransTraceT_to_prop hrest) injection hc with hρ subst hρ - exact ⟨True.intro, fun _ => hInv⟩ + exact fun _ => hInv | .step _ _ _ restTr _ .step_loop_nondet_enter hrest, hlen => simp only [List.nil_append] obtain ⟨ρ_mid, tr₁, tr₂, htr, h_block_term, h_loop_rest, hlen_seq⟩ := seqT_reaches_terminalE hrest - obtain ⟨ρ_inner, hbody_disj, heq_ρ_mid⟩ := - block_reaches_doneE (.inl (reflTransTraceT_to_prop h_block_term)) - have hbody_run : StepStmtStarE P evalCmd (.stmts body ρ₀) tr₁ (.terminal ρ_inner) := by - rcases hbody_disj with hterm | ⟨lbl, hexit⟩ - · exact hterm - · exact absurd hexit (stmts_exitsCoveredByBlocks_noEscapeE evalCmd - body hcov ρ₀ lbl ρ_inner) obtain ⟨ρ_x, tr_l, tr_nil, htr2, h_loop_head, h_nil, hlen_cons⟩ := stmtsT_cons_terminalE h_loop_rest obtain ⟨htail_nil, htail_cfg⟩ := stmts_nil_runE evalCmd @@ -287,32 +328,88 @@ theorem while_nondet_genE simp only [List.append_nil] at htr2 rw [htr2] at htr rw [htr] - have hbodyTriple := hbody ρ₀ ρ_inner tr₁ hInv (hloopBodyWF ρ₀ hwf) (.inl hbody_run) - have hproj : projectStore ρ₀.store ρ_inner.store - = dropVars (Block.definedVars (P := P) (C := CmdT) body true) ρ_inner.store := - projectStore_eq_dropVarsE h_cmd (hbodyDefs ρ₀ hwf) (.inl hbody_run) - have hrec : ({ ρ_inner with store := projectStore ρ₀.store ρ_inner.store } : Env P) - = { ρ_inner with - store := dropVars (Block.definedVars (P := P) (C := CmdT) body true) ρ_inner.store } := by - rw [hproj] - have hwf_mid : initEnvWF params (.loop .nondet measure inv body md) ρ_mid := by - rw [heq_ρ_mid]; exact hloopWF ρ₀ ρ_inner tr₁ hwf hbody_run - have hIH : Trace.Reachable P conditionInterp tr₁ → - Trace.AssertionsValid P conditionInterp tr_l ∧ - (Trace.Reachable P conditionInterp tr_l → Inv ρ') := by - intro hs - have hInv_mid : Inv ρ_mid := by - rw [heq_ρ_mid, hrec]; exact hInv_proj ρ_inner (hbodyTriple.2 hs) - exact ih ρ_mid ρ' tr_l hInv_mid hwf_mid h_loop_head - (by simp only [ReflTransTraceT.len] at hlen; omega) - refine ⟨Trace.AssertionsValid.append_of_reachable_left conditionInterp hbodyTriple.1 - (fun hs => (hIH hs).1), fun hfull => ?_⟩ - exact (hIH (Trace.Reachable.left_of_append conditionInterp hfull)).2 + intro hfull + obtain ⟨hInv_mid, hwf_mid⟩ := while_nondet_iterE evalCmd initEnvWF blockInitEnvWF bparams + params h_cmd hbodyDefs hloopBodyWF hloopWF hbody hcov hInv_proj hInv hwf + (reflTransTraceT_to_prop h_block_term) (Trace.Reachable.left_of_append conditionInterp hfull) + exact ih ρ_mid ρ' tr_l hInv_mid hwf_mid h_loop_head + (by simp only [ReflTransTraceT.len] at hlen; omega) (Trace.Reachable.right_of_append conditionInterp hfull) +/-- Helper for `while_nondet`: every finite execution of the loop from an entry satisfying the +invariant that the loop's gate admits has valid assertions. By strong induction on the length +of the derivation. -/ +theorem while_nondet_prefixE + {measure : Option P.Expr} {inv : List (String × P.Expr)} + {body : List (Stmt P CmdT)} {md : MetaData P} + {Inv : Env P → Prop} (params : InitEnvWFParams P) + (h_cmd : ∀ {f : P.Factory} {σ σ' : SemanticStore P} {c : CmdT} {emitted : Trace P} {y : P.Ident}, + evalCmd f σ c σ' emitted → σ y = none → + y ∉ HasVarsImp.definedVars (P := P) c true → σ' y = none) + (hbodyDefs : ∀ ρ, initEnvWF params (.loop .nondet measure inv body md) ρ → + ∀ x ∈ Block.definedVars (P := P) (C := CmdT) body true, ρ.store x = none) + (hloopBodyWF : ∀ ρ, initEnvWF params (.loop .nondet measure inv body md) ρ → + blockInitEnvWF bparams body ρ) + (hloopWF : ∀ ρ ρ_inner tr, initEnvWF params (.loop .nondet measure inv body md) ρ → + StepStmtStarE P evalCmd (.stmts body ρ) tr (.terminal ρ_inner) → + initEnvWF params (.loop .nondet measure inv body md) + { ρ_inner with store := projectStore ρ.store ρ_inner.store }) + (hbody : TripleWith (EventLang.imperativeBlockE P CmdT evalCmd blockInitEnvWF) + conditionInterp bparams Inv body Inv) + (hcov : Block.exitsCoveredByBlocks (P := P) (CmdT := CmdT) [] body) + (hInv_proj : PostWF body Inv) (n : Nat) : + ∀ (ρ₀ : Env P) (cfg : Config P CmdT) (trace : Trace P) + (hrunT : ReflTransTraceT (StepStmtE P evalCmd) + (.stmt (.loop .nondet measure inv body md) ρ₀) trace cfg), + hrunT.len ≤ n → Inv ρ₀ → initEnvWF params (.loop .nondet measure inv body md) ρ₀ → + Trace.AssertionsValid P conditionInterp trace := by + induction n with + | zero => + intro ρ₀ cfg trace hrunT hlen _ _ + match hrunT, hlen with + | .refl _, _ => exact True.intro + | .step _ _ _ _ _ _ _, hlen => simp only [ReflTransTraceT.len] at hlen; omega + | succ n ih => + intro ρ₀ cfg trace hrunT hlen hInv hwf + match hrunT, hlen with + | .refl _, _ => exact True.intro + | .step _ _ _ restTr _ .step_loop_nondet_exit hrest, _ => + obtain ⟨_, hnil⟩ := Imperative.stepStmtStarE_from_terminal (reflTransTraceT_to_prop hrest) + subst hnil + exact True.intro + | .step _ _ _ restTr _ .step_loop_nondet_enter hrest, hlen => + simp only [List.nil_append] + simp only [ReflTransTraceT.len] at hlen + have hblock : ∀ tr c, StepStmtStarE P evalCmd + (.block .none ρ₀.store (.stmts body ρ₀)) tr c → + Trace.AssertionsValid P conditionInterp tr := by + intro tr c h + obtain ⟨inner', h'⟩ := block_run_inner_prefixE h + exact (hbody ρ₀ hInv (hloopBodyWF ρ₀ hwf)).1 inner' tr h' + rcases seqT_run_decomposeE hrest with + ⟨_, _, h1, _⟩ | ⟨ρ₁, tr₁, tr₂, rfl, h1, h2, hlen2⟩ | ⟨_, _, _, h1, _⟩ + · exact hblock _ _ (reflTransTraceT_to_prop h1) + · refine Trace.AssertionsValid.append_of_reachable_left conditionInterp + (hblock _ _ (reflTransTraceT_to_prop h1)) fun hreach => ?_ + obtain ⟨hInv₁, hwf₁⟩ := while_nondet_iterE evalCmd initEnvWF blockInitEnvWF bparams + params h_cmd hbodyDefs hloopBodyWF hloopWF hbody hcov hInv_proj hInv hwf + (reflTransTraceT_to_prop h1) hreach + match h2, hlen2 with + | .refl _, _ => exact True.intro + | .step _ _ _ _ _ .step_stmts_cons hrest2, hlen2 => + simp only [List.nil_append] + simp only [ReflTransTraceT.len] at hlen2 + rcases seqT_run_decomposeE hrest2 with + ⟨_, _, h1', hl'⟩ | ⟨ρ₂, tr₂₁, tr₂₂, rfl, h1', h2', hl'⟩ | ⟨_, _, _, h1', hl'⟩ + · exact ih ρ₁ _ _ h1' (by omega) hInv₁ hwf₁ + · obtain ⟨rfl, _⟩ := stmts_nil_runE evalCmd (reflTransTraceT_to_prop h2') + simpa using ih ρ₁ _ _ h1' (by omega) hInv₁ hwf₁ + · exact ih ρ₁ _ _ h1' (by omega) hInv₁ hwf₁ + · exact hblock _ _ (reflTransTraceT_to_prop h1) + /-- `while (*)`: an invariant the body re-establishes holds when the loop finishes, after any number of iterations, with nothing learned from a guard. -/ -theorem while_nondet (params : ParamsTy) +theorem while_nondet (params : InitEnvWFParams P) {measure : Option P.Expr} {inv : List (String × P.Expr)} {body : List (Stmt P CmdT)} {md : MetaData P} {Inv : Env P → Prop} (h_cmd : ∀ {f : P.Factory} {σ σ' : SemanticStore P} {c : CmdT} {emitted : Trace P} {y : P.Ident}, @@ -326,17 +423,21 @@ theorem while_nondet (params : ParamsTy) StepStmtStarE P evalCmd (.stmts body ρ) tr (.terminal ρ_inner) → initEnvWF params (.loop .nondet measure inv body md) { ρ_inner with store := projectStore ρ.store ρ_inner.store }) - (hbody : TripleWith (EventLang.imperativeBlockE P CmdT evalCmd ⟨BParamsTy, blockInitEnvWF⟩) + (hbody : TripleWith (EventLang.imperativeBlockE P CmdT evalCmd blockInitEnvWF) conditionInterp bparams Inv body Inv) (hcov : Block.exitsCoveredByBlocks (P := P) (CmdT := CmdT) [] body) (hInv_proj : PostWF body Inv) : - TripleWith (EventLang.imperativeE P CmdT evalCmd ParamsTy initEnvWF) conditionInterp params + TripleWith (EventLang.imperativeE P CmdT evalCmd initEnvWF) conditionInterp params Inv (.loop .nondet measure inv body md) Inv := by - intro ρ₀ ρ' trace hInv hinit hrun + intro ρ₀ hInv hinit + refine ⟨fun cfg trace hrun => ?_, fun ρ' trace hrun hreach => ?_⟩ + · exact while_nondet_prefixE evalCmd initEnvWF blockInitEnvWF bparams params + h_cmd hbodyDefs hloopBodyWF hloopWF hbody hcov hInv_proj _ ρ₀ cfg trace + (reflTransTrace_to_T hrun) (Nat.le_refl _) hInv hinit rcases hrun with hterm | ⟨lbl, hexit⟩ · exact while_nondet_genE evalCmd initEnvWF blockInitEnvWF bparams params h_cmd hbodyDefs hloopBodyWF hloopWF hbody hcov hInv_proj - ρ₀ ρ' trace _ hInv hinit (reflTransTrace_to_T hterm) (Nat.le_refl _) + ρ₀ ρ' trace _ hInv hinit (reflTransTrace_to_T hterm) (Nat.le_refl _) hreach · exact absurd hexit (exitsCoveredByBlocks_noEscapeE evalCmd (.loop .nondet measure inv body md) hcov ρ₀ lbl ρ') diff --git a/StrataBoole/HoareLogic/Hoare/Rules.lean b/StrataBoole/HoareLogic/Hoare/Rules.lean index 4bc7cd3..ef8c51e 100644 --- a/StrataBoole/HoareLogic/Hoare/Rules.lean +++ b/StrataBoole/HoareLogic/Hoare/Rules.lean @@ -105,7 +105,7 @@ theorem blockInitEnvWF_of_ite_then_nondet {params : InitEnvWFParams} h.reservedFresh (fun l hl => h.exitsNotReserved l (by rw [Imperative.Stmt.labels]; exact List.mem_append.mpr (Or.inl hl))) - hdu.1.2 h.factoryDeclared + hdu.1.2 h.factoryDeclared h.runtimeFactoryDeclared (fun ty hty => h.initTypesInhabited ty (by simp only [Imperative.Stmt.initTypes]; exact List.mem_append.mpr (Or.inl hty))) (by @@ -130,7 +130,7 @@ theorem blockInitEnvWF_of_ite_else_nondet {params : InitEnvWFParams} h.reservedFresh (fun l hl => h.exitsNotReserved l (by rw [Imperative.Stmt.labels]; exact List.mem_append.mpr (Or.inr hl))) - hdu.2 h.factoryDeclared + hdu.2 h.factoryDeclared h.runtimeFactoryDeclared (fun ty hty => h.initTypesInhabited ty (by simp only [Imperative.Stmt.initTypes]; exact List.mem_append.mpr (Or.inr hty))) (by @@ -153,7 +153,7 @@ theorem blockInitEnvWF_of_loop_body_nondet {params : InitEnvWFParams} exact BlockInitEnvWF.of_defUseOk h.toWellFormedSemanticEval h.storeWellDefined hdefs hdnr h.reservedFresh (fun l hl => h.exitsNotReserved l (by rw [Imperative.Stmt.labels]; exact hl)) - hdu.2 h.factoryDeclared + hdu.2 h.factoryDeclared h.runtimeFactoryDeclared (fun ty hty => h.initTypesInhabited ty (by simp only [Imperative.Stmt.initTypes]; exact hty)) (by obtain ⟨Γ, hσ, hw⟩ := h.fvarTypesOk @@ -202,7 +202,7 @@ theorem initEnvWF_loop_iterateE_nondet {params : InitEnvWFParams} · exact absurd hx (by simp) refine InitEnvWF.of_defUseOk (hfac ▸ h.toWellFormedSemanticEval) hproj (fun n hn => ?_) h.definedVarsNotReserved (fun n hn => ?_) h.exitsNotReserved ?_ h.factoryDeclared - (hfac ▸ h.initTypesInhabited) ?_ h.measuresTyped + (hfac ▸ h.runtimeFactoryDeclared) (hfac ▸ h.initTypesInhabited) ?_ h.measuresTyped · have hdef := h.defsUndefined n hn show (Imperative.projectStore ρ.store ρ_inner.store n).isNone rw [Option.isNone_iff_eq_none] at hdef ⊢ diff --git a/StrataBoole/HoareLogic/Hoare/Tactic.lean b/StrataBoole/HoareLogic/Hoare/Tactic.lean index 20f675b..95e4627 100644 --- a/StrataBoole/HoareLogic/Hoare/Tactic.lean +++ b/StrataBoole/HoareLogic/Hoare/Tactic.lean @@ -666,7 +666,7 @@ elab "hoare_open_pre" : tactic => withMainContext do let hin := mkIdent `hin let hΓ := mkIdent `hΓ evalTactic (← `(tactic| ( - obtain ⟨⟨$hreq:ident, $hfac:ident, $hold:ident, $hin:ident⟩, $hwf:ident, $hF:ident⟩ := $hpre:ident + obtain ⟨⟨$hreq:ident, $hfac:ident, $hold:ident, $hin:ident, -⟩, $hwf:ident, $hF:ident⟩ := $hpre:ident have $hΓ:ident := Strata.Hoare.inputs_typed $hwf:ident $hin:ident rcases $ρ:ident with ⟨$σ₀:ident, $f:ident⟩ dsimp only at $hF:ident diff --git a/StrataBoole/HoareLogic/Hoare/WP.lean b/StrataBoole/HoareLogic/Hoare/WP.lean index 9d23861..38645a9 100644 --- a/StrataBoole/HoareLogic/Hoare/WP.lean +++ b/StrataBoole/HoareLogic/Hoare/WP.lean @@ -56,9 +56,9 @@ theorem vc_entry {P Pre Q : Pred} {ss : Core.Statements} theorem exists_pre {α : Sort _} {P : α → Pred} {ss : Core.Statements} {Q : Pred} (h : ∀ a, Triple π params (P a) ss Q (factory := factory)) : Triple π params (fun ρ => ∃ a, P a ρ) ss Q (factory := factory) := by - intro ρ₀ ρ' trace hpre hinit hrun + intro ρ₀ hpre hinit obtain ⟨a, ha⟩ := hpre - exact h a ρ₀ ρ' trace ha hinit hrun + exact h a ρ₀ ha hinit /-- A closed fact survives any statement list. -/ theorem frame_const {Pre Post : Pred} {ss : Core.Statements} (C : Prop) @@ -373,7 +373,7 @@ theorem while_wp_frame (I : Pred) {guard : Core.Expression.Expr} (P := Core.Expression) (CmdT := Core.Command) [] body) : Triple π params (wpLoop D M I guard B Q) [.loop (.det guard) measure inv body md] Q (factory := factory) := by - intro ρ₀ ρ' trace hpre hinit hrun + intro ρ₀ hpre hinit obtain ⟨hI, hstep, hexit⟩ := hpre have hJ : ∀ ρ : Imperative.Env Core.Expression, wpProj D (fun ρ => I ρ ∧ agreeExcept M ρ.store ρ₀.store) ρ → @@ -385,7 +385,7 @@ theorem while_wp_frame (I : Pred) {guard : Core.Expression.Expr} (fun ρ => I ρ ∧ agreeExcept M ρ.store ρ₀.store) D hD (hbody ρ₀.store) (fun ρ hρ hg => hstep ρ (hJ ρ hρ).2 (hJ ρ hρ).1 hg) (fun ρ hρ hg => hexit ρ (hJ ρ hρ).2 (hJ ρ hρ).1 hg) hcov - exact h ρ₀ ρ' trace (And.intro hI (agreeExcept_dropVars hDM ρ₀.store)) hinit hrun + exact h ρ₀ (And.intro hI (agreeExcept_dropVars hDM ρ₀.store)) hinit /-! ## Nondeterministic branches and loops, and `cover` @@ -458,7 +458,7 @@ theorem while_nondet_wp_frame (I : Pred) {measure : Option Core.Expression.Expr} (P := Core.Expression) (CmdT := Core.Command) [] body) : Triple π params (wpLoopN D M I B Q) [.loop .nondet measure inv body md] Q (factory := factory) := by - intro ρ₀ ρ' trace hpre hinit hrun + intro ρ₀ hpre hinit obtain ⟨hI, hstep, hexit⟩ := hpre have hJ : ∀ ρ : Imperative.Env Core.Expression, wpProj D (fun ρ => I ρ ∧ agreeExcept M ρ.store ρ₀.store) ρ → @@ -471,7 +471,7 @@ theorem while_nondet_wp_frame (I : Pred) {measure : Option Core.Expression.Expr} (wpProj D (fun ρ => I ρ ∧ agreeExcept M ρ.store ρ₀.store)) (hbody ρ₀.store) (fun ρ hρ => hstep ρ (hJ ρ hρ).2 (hJ ρ hρ).1) (fun ρ hρ => hexit ρ (hJ ρ hρ).2 (hJ ρ hρ).1) hcov (postWF_proj hD _) - exact h ρ₀ ρ' trace (And.intro hI (agreeExcept_dropVars hDM ρ₀.store)) hinit hrun + exact h ρ₀ (And.intro hI (agreeExcept_dropVars hDM ρ₀.store)) hinit end Strata.Hoare diff --git a/StrataBoole/HoareLogic/Reflect/Core.lean b/StrataBoole/HoareLogic/Reflect/Core.lean index c4f52eb..ee64b7b 100644 --- a/StrataBoole/HoareLogic/Reflect/Core.lean +++ b/StrataBoole/HoareLogic/Reflect/Core.lean @@ -88,6 +88,8 @@ partial def monoTyE : Lambda.LMonoTy → Lean.Expr mkApp2 (mkConst ``Lambda.LMonoTy.tcons) (toExpr n) (mkList monoTyTy (args.map monoTyE)) | .bitvec n => mkApp (mkConst ``Lambda.LMonoTy.bitvec) (toExpr n) +def lTyTy : Lean.Expr := mkConst ``Lambda.LTy + def lTyE : Lambda.LTy → Lean.Expr | .forAll vs ty => mkApp2 (mkConst ``Lambda.LTy.forAll) (mkList stringTy (vs.map toExpr)) (monoTyE ty) @@ -163,8 +165,9 @@ def callArgE (c : Ctx) : Imperative.CallArg Core.Expression → Lean.Expr def commandE (c : Ctx) : Core.Command → Lean.Expr | .cmd k => mkApp2 (mkConst ``Imperative.CmdExt.cmd [Level.one]) c.P (cmdE c k) - | .call p args _ => - mkApp4 (mkConst ``Imperative.CmdExt.call [Level.one]) c.P (toExpr p) + | .call p tys args _ => + mkApp5 (mkConst ``Imperative.CmdExt.call [Level.one]) c.P (toExpr p) + (mkOption (mkApp (mkConst ``List [Level.zero]) lTyTy) (tys.map fun ts => mkList lTyTy (ts.map lTyE))) (mkList (mkApp (mkConst ``Imperative.CallArg [Level.one]) c.P) (args.map (callArgE c))) (mdE c) mutual @@ -210,14 +213,14 @@ def headerE (h : Core.Procedure.Header) : Lean.Expr := (mkList stringTy (h.lemmas.map toExpr)) def procedureE (c : Ctx) (p : Core.Procedure) : MetaM Lean.Expr := do - let ss ← match p.body with - | .structured ss => pure ss - | .cfg _ => throwError "core_reflect: procedure {p.header.name.name} has a CFG body" - let body ← match stmtsE c ss with - | .ok e => pure e - | .error msg => throwError "core_reflect: procedure {p.header.name.name}: {msg}" - mkAppM ``Imperative.Procedure.mk - #[headerE p.header, specE c p.spec, mkApp3 (mkConst ``Imperative.Body.structured [Level.one]) c.P c.C body] + let body ← match p.body with + | .structured ss opq => + match stmtsE c ss with + | .ok e => pure (mkApp4 (mkConst ``Imperative.Body.structured [Level.one]) c.P c.C e (toExpr opq)) + | .error msg => throwError "core_reflect: procedure {p.header.name.name}: {msg}" + | .cfg _ _ => throwError "core_reflect: procedure {p.header.name.name} has a CFG body" + | .abstract => pure (mkApp2 (mkConst ``Imperative.Body.abstract [Level.one]) c.P c.C) + mkAppM ``Imperative.Procedure.mk #[headerE p.header, specE c p.spec, body] /-! ## The command -/ diff --git a/StrataBoole/HoareLogic/Reflect/ToExpr.lean b/StrataBoole/HoareLogic/Reflect/ToExpr.lean index 78558f2..65e5cef 100644 --- a/StrataBoole/HoareLogic/Reflect/ToExpr.lean +++ b/StrataBoole/HoareLogic/Reflect/ToExpr.lean @@ -133,7 +133,8 @@ instance : ToExpr (CallArg Core.Expression) where instance : ToExpr Core.Command where toExpr | .cmd c => mkApp2 (mkConst ``CmdExt.cmd [Level.one]) pureExprE (toExpr c) - | .call n args md => mkApp4 (mkConst ``CmdExt.call [Level.one]) pureExprE (toExpr n) (toExpr args) (mdE md) + | .call n tys args md => + mkApp5 (mkConst ``CmdExt.call [Level.one]) pureExprE (toExpr n) (toExpr tys) (toExpr args) (mdE md) toTypeExpr := cmdE mutual @@ -172,10 +173,12 @@ instance : ToExpr (Spec Core.Expression) where /-! ## Procedures -/ -/-- A procedure body. Only structured bodies are supported; the lowering never produces a CFG. -/ +/-- A procedure body: structured, or absent. The lowering never produces a CFG. -/ def bodyE : Core.Procedure.Body → MetaM Expr - | .structured ss => pure (mkApp3 (mkConst ``Body.structured [Level.one]) pureExprE cmdE (stmtsE ss)) - | .cfg _ => throwError "boole_reflect: a procedure body given as a CFG cannot be reflected" + | .structured ss opq => + pure (mkApp4 (mkConst ``Body.structured [Level.one]) pureExprE cmdE (stmtsE ss) (toExpr opq)) + | .cfg _ _ => throwError "boole_reflect: a procedure body given as a CFG cannot be reflected" + | .abstract => pure (mkApp2 (mkConst ``Body.abstract [Level.one]) pureExprE cmdE) /-- The procedure `p` as a closed term of type `Core.Procedure`. -/ def procedureE (p : Core.Procedure) : MetaM Expr := do @@ -234,7 +237,8 @@ def declE : Core.Decl → MetaM Expr /-- The program `p` as a closed term of type `Core.Program`. -/ def programE (p : Core.Program) : MetaM Expr := do let ds ← p.decls.mapM declE - return mkApp (mkConst ``Core.Program.mk) (← mkListLit (mkConst ``Core.Decl) ds) + return mkApp2 (mkConst ``Core.Program.mk) (← mkListLit (mkConst ``Core.Decl) ds) + (toExpr p.usedIdentPrefixes) /-- Add `name : Core.Program := p` to the environment. -/ def addProgramAst (name : Name) (p : Core.Program) : MetaM Unit := do diff --git a/StrataBooleTest/HoareLogic/boole_reflect.lean b/StrataBooleTest/HoareLogic/boole_reflect.lean index d7a060d..765e9a8 100644 --- a/StrataBooleTest/HoareLogic/boole_reflect.lean +++ b/StrataBooleTest/HoareLogic/boole_reflect.lean @@ -239,7 +239,7 @@ example : sum_to_ast.spec.postconditions.toList.length = 1 := rfl /-- The lowering wraps the body in a block named after the procedure. -/ example : (match sum_to_ast.body with - | .structured [.block "sum_to" _ _] => true + | .structured [.block "sum_to" _ _] _ => true | _ => false) = true := by decide From 2898b5eab4d6285fe7b0e16c0bc1ee4100b6622b Mon Sep 17 00:00:00 2001 From: Stephanie Ma Date: Mon, 30 Nov 2026 07:19:00 -0800 Subject: [PATCH 52/64] Entry over any visible factory; outputs typed at the entry - `Eval.OverCore factory`: the factory resolves every name `Core.Factory` knows to the same function. It holds for the factory any procedure of any program sees (`OverCore.factoryBeforeProcedure`), so a contract no longer needs the program to declare nothing. The operator lemmas take `OverCore` in place of `factory = Core.Factory`. - `entryPre` states the precondition over `p.factoryBeforeProcedure procName`, with the axioms before the procedure. - An `out` parameter has a typed value at the entry, `x_entry` (`hoare_typed_outputs`): a `havoc` of an output never assigned is now proved (`unassigned_contract` in hoare_havoc_core). - A condition the lifting cannot read stays in the context as it is, and `hoare_lift` tries it by assumption. --- StrataBoole/HoareLogic/Hoare/Contract.lean | 57 +++++---- StrataBoole/HoareLogic/Hoare/Lift/Denote.lean | 60 ++++----- StrataBoole/HoareLogic/Hoare/Lift/Eval.lean | 117 +++++++++++++----- StrataBoole/HoareLogic/Hoare/Tactic.lean | 71 ++++++++--- .../HoareLogic/hoare_havoc_core.lean | 36 ++++-- 5 files changed, 228 insertions(+), 113 deletions(-) diff --git a/StrataBoole/HoareLogic/Hoare/Contract.lean b/StrataBoole/HoareLogic/Hoare/Contract.lean index 5be3643..e13521d 100644 --- a/StrataBoole/HoareLogic/Hoare/Contract.lean +++ b/StrataBoole/HoareLogic/Hoare/Contract.lean @@ -18,12 +18,12 @@ public import Strata.Languages.Core.ProgramProps around the procedure body wrapped in a block, with conditions read over the factory visible at the procedure. The lemmas here read both ends: -* `contract_intro` states that triple over `Core.Factory`, for a program that declares no - function before the procedure, from `entryPre`: the contract's precondition, a store that - holds values of the runtime factory, and the runtime factory itself as a variable `F`, which - no statement changes; -* `entryPre` then gives a typed binding for every input (`inputs_typed`) and the `requires` - clauses (`requires_eval`); +* `contract_intro` states that triple from `entryPre`: the contract's precondition, the axioms + declared before the procedure, a store that holds values of the runtime factory, and the + runtime factory itself as a variable `F`, which no statement changes and which resolves the + built-in names as `Core.Factory` does (`overCore_of_entry`); +* `entryPre` then gives a typed binding for every input (`inputs_typed`) and every output + (`output_typed`), and the `requires` clauses (`requires_eval`); * `contractPost` is one `checkAsPredicate` per non-free `ensures` (`contractPost_intro`). Conditions go through `holds_iff`, the reading of `DenoteBasedInterp` under a runtime factory @@ -45,14 +45,16 @@ variable {factory : Lambda.Factory Core.CoreLParams} /-! ## Entry -/ -/-- What the rules know at the entry of a procedure: the contract's precondition, a store that -holds values of the runtime factory, and the runtime factory, named `F`. -/ -@[expose] def entryPre (proc : Core.Procedure) (F : Core.Expression.Factory) : Pred := - fun ρ => Procedure.contractPre Core.Factory proc ρ ∧ +/-- What the rules know at the entry of the procedure `procName` of `p`: the contract's +precondition over the factory visible at the procedure, the axioms declared before it, a store +that holds values of the runtime factory, and the runtime factory, named `F`. -/ +@[expose] def entryPre (p : Core.Program) (procName : String) (proc : Core.Procedure) + (F : Core.Expression.Factory) : Pred := + fun ρ => Procedure.contractPre (p.factoryBeforeProcedure procName) proc ρ ∧ + Core.Specification.AxiomsBeforeProcedureDecl procName p ρ ∧ Imperative.WellFormedStore ρ.store ρ.factory ∧ ρ.factory = F -/-- A contract from the triple the rules prove: over `Core.Factory`, which is the factory visible -at a procedure no function declaration precedes, and from `entryPre` at every runtime factory. +/-- A contract from the triple the rules prove, from `entryPre` at every runtime factory. Every admitted entry has a store of values of its runtime factory (`of_storeWF_pre`), and the runtime factory may be fixed because the triple quantifies over the entries (`of_forall_entryFactory`). -/ @@ -61,23 +63,24 @@ theorem contract_intro (p : Core.Program) (params : InitEnvWFParams) (procName : (hproc : p.findProcByString? procName = some proc) (hbody : proc.body = .structured bss opq) (hchecksTyped : Procedure.contractChecksTyped proc) - (hfuns : (p.declsBeforeProcedure procName).all fun d => - match d with - | .func _ _ | .recFuncBlock _ _ => false - | .type (.data _) _ => false - | _ => true) (h : ∀ F : Core.Expression.Factory, Triple p.findProcByString? params - (entryPre proc F) [Imperative.Stmt.block "" bss #[]] - (Procedure.contractPost Core.Factory proc)) + (entryPre p procName proc F) [Imperative.Stmt.block "" bss #[]] + (Procedure.contractPost (p.factoryBeforeProcedure procName) proc) + (factory := p.factoryBeforeProcedure procName)) (hmono : proc.header.typeArgs = [] := by first | rfl | decide) : Procedure.contractTriple p params procName := by - refine Procedure.contractTriple_of_core_typed p params procName proc bss hproc hbody + refine Procedure.contractTriple_of_core_typed_axioms p params procName proc bss hproc hbody hchecksTyped ?_ hmono - rw [Core.Program.factoryBeforeProcedure_eq_core_of_noFunctions hfuns] refine Core.Logic.Hoare.of_storeWF_pre _ params (Core.Logic.Hoare.of_forall_entryFactory _ params fun F => ?_) exact Core.Logic.Hoare.consequence _ params (h F) - (fun _ hρ => ⟨hρ.1.1, hρ.1.2, hρ.2⟩) (fun _ h => h) + (fun _ hρ => ⟨hρ.1.1.1, hρ.1.1.2, hρ.1.2, hρ.2⟩) (fun _ h => h) + +/-- The runtime factory of an entry is over `Core.Factory`. -/ +theorem overCore_of_entry {p : Core.Program} {procName : String} + {F : Lambda.Factory Core.CoreLParams} (hfac : F = p.factoryBeforeProcedure procName) : + Eval.OverCore F := + Eval.OverCore.of_eq hfac (Eval.OverCore.factoryBeforeProcedure p procName) /-! ## Reading conditions -/ @@ -233,6 +236,16 @@ theorem inputs_typed {proc : Core.Procedure} {ρ : Imperative.Env Core.Expressio obtain ⟨v, hv, hty⟩ := hin id ty hmem exact ⟨v, hv, hwf id v hv, hty⟩ +/-- An output of a procedure is a typed binding of a well-formed entry store. -/ +theorem output_typed {proc : Core.Procedure} {ρ : Imperative.Env Core.Expression} + (hwf : Imperative.WellFormedStore ρ.store ρ.factory) + (hout : Procedure.outputAsPredicate proc ρ) + {id : Core.Expression.Ident} {ty : Lambda.LMonoTy} + (hmem : (id, ty) ∈ proc.header.outputs.toList) : + ∃ v, ρ.store id = some v ∧ v.tc = ρ.factory.model.tcInterp ∧ Procedure.valueHasType ty v := by + obtain ⟨v, hv, hty⟩ := hout id ty hmem + exact ⟨v, hv, hwf id v hv, hty⟩ + /-- A `requires` clause evaluates to `true` at the entry. -/ theorem requires_eval {proc : Core.Procedure} {ρ : Imperative.Env Core.Expression} (hpre : Procedure.preAsPredicate factory proc ρ) (hfac : ρ.factory.factory = factory) diff --git a/StrataBoole/HoareLogic/Hoare/Lift/Denote.lean b/StrataBoole/HoareLogic/Hoare/Lift/Denote.lean index 79d65ff..302bdea 100644 --- a/StrataBoole/HoareLogic/Hoare/Lift/Denote.lean +++ b/StrataBoole/HoareLogic/Hoare/Lift/Denote.lean @@ -305,7 +305,7 @@ variable {m m' m'' : ExpressionMetadata} {e₁ e₂ : Expression.Expr} /-! ### Integer arithmetic -/ -theorem denote_add (hfac : f.factory = Core.Factory) +theorem denote_add (hfac : Eval.OverCore f.factory) (h₁ : LExpr.HasTypeA Δ e₁ tInt) (h₂ : LExpr.HasTypeA Δ e₂ tInt) (h : LExpr.HasTypeA Δ (.app m (.app m' (.op m'' ⟨"Int.Add", ()⟩ (some (tArrow tInt (tArrow tInt tInt)))) e₁) e₂) @@ -316,9 +316,9 @@ theorem denote_add (hfac : f.factory = Core.Factory) = toInt (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv e₁ tInt h₁) + toInt (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv e₂ tInt h₂) := (denote_app2 (a := .int) (b := .int) (c := .int) fv vt bv h₁ h₂ h).trans - (Core.intAdd_opInterp_of_lookup f.model (hfac ▸ Core.coreFactory_intAdd) _ _) + (Core.intAdd_opInterp_of_lookup f.model (hfac _ _ Core.coreFactory_intAdd) _ _) -theorem denote_sub (hfac : f.factory = Core.Factory) +theorem denote_sub (hfac : Eval.OverCore f.factory) (h₁ : LExpr.HasTypeA Δ e₁ tInt) (h₂ : LExpr.HasTypeA Δ e₂ tInt) (h : LExpr.HasTypeA Δ (.app m (.app m' (.op m'' ⟨"Int.Sub", ()⟩ (some (tArrow tInt (tArrow tInt tInt)))) e₁) e₂) @@ -329,9 +329,9 @@ theorem denote_sub (hfac : f.factory = Core.Factory) = toInt (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv e₁ tInt h₁) - toInt (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv e₂ tInt h₂) := (denote_app2 (a := .int) (b := .int) (c := .int) fv vt bv h₁ h₂ h).trans - (Core.intSub_opInterp_of_lookup f.model (hfac ▸ Core.coreFactory_intSub) _ _) + (Core.intSub_opInterp_of_lookup f.model (hfac _ _ Core.coreFactory_intSub) _ _) -theorem denote_mul (hfac : f.factory = Core.Factory) +theorem denote_mul (hfac : Eval.OverCore f.factory) (h₁ : LExpr.HasTypeA Δ e₁ tInt) (h₂ : LExpr.HasTypeA Δ e₂ tInt) (h : LExpr.HasTypeA Δ (.app m (.app m' (.op m'' ⟨"Int.Mul", ()⟩ (some (tArrow tInt (tArrow tInt tInt)))) e₁) e₂) @@ -342,10 +342,10 @@ theorem denote_mul (hfac : f.factory = Core.Factory) = toInt (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv e₁ tInt h₁) * toInt (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv e₂ tInt h₂) := (denote_app2 (a := .int) (b := .int) (c := .int) fv vt bv h₁ h₂ h).trans - (Core.intMul_opInterp_of_lookup f.model (hfac ▸ Core.coreFactory_intMul) _ _) + (Core.intMul_opInterp_of_lookup f.model (hfac _ _ Core.coreFactory_intMul) _ _) /-- Division, at a divisor that denotes a non-zero integer. -/ -theorem denote_div (hfac : f.factory = Core.Factory) +theorem denote_div (hfac : Eval.OverCore f.factory) (h₁ : LExpr.HasTypeA Δ e₁ tInt) (h₂ : LExpr.HasTypeA Δ e₂ tInt) (h : LExpr.HasTypeA Δ (.app m (.app m' (.op m'' ⟨"Int.Div", ()⟩ (some (tArrow tInt (tArrow tInt tInt)))) e₁) e₂) @@ -357,9 +357,9 @@ theorem denote_div (hfac : f.factory = Core.Factory) = toInt (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv e₁ tInt h₁) / toInt (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv e₂ tInt h₂) := (denote_app2 (a := .int) (b := .int) (c := .int) fv vt bv h₁ h₂ h).trans - (Eval.intDiv_opInterp_of_lookup f.model (hfac ▸ Eval.coreFactory_intDiv) _ _ hb) + (Eval.intDiv_opInterp_of_lookup f.model (hfac _ _ Eval.coreFactory_intDiv) _ _ hb) -theorem denote_mod (hfac : f.factory = Core.Factory) +theorem denote_mod (hfac : Eval.OverCore f.factory) (h₁ : LExpr.HasTypeA Δ e₁ tInt) (h₂ : LExpr.HasTypeA Δ e₂ tInt) (h : LExpr.HasTypeA Δ (.app m (.app m' (.op m'' ⟨"Int.Mod", ()⟩ (some (tArrow tInt (tArrow tInt tInt)))) e₁) e₂) @@ -371,19 +371,19 @@ theorem denote_mod (hfac : f.factory = Core.Factory) = toInt (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv e₁ tInt h₁) % toInt (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv e₂ tInt h₂) := (denote_app2 (a := .int) (b := .int) (c := .int) fv vt bv h₁ h₂ h).trans - (Eval.intMod_opInterp_of_lookup f.model (hfac ▸ Eval.coreFactory_intMod) _ _ hb) + (Eval.intMod_opInterp_of_lookup f.model (hfac _ _ Eval.coreFactory_intMod) _ _ hb) -theorem denote_neg (hfac : f.factory = Core.Factory) (h₁ : LExpr.HasTypeA Δ e₁ tInt) +theorem denote_neg (hfac : Eval.OverCore f.factory) (h₁ : LExpr.HasTypeA Δ e₁ tInt) (h : LExpr.HasTypeA Δ (.app m (.op m' ⟨"Int.Neg", ()⟩ (some (tArrow tInt tInt))) e₁) tInt) : toInt (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv (.app m (.op m' ⟨"Int.Neg", ()⟩ (some (tArrow tInt tInt))) e₁) tInt h) = - toInt (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv e₁ tInt h₁) := (denote_app1 (a := .int) (c := .int) fv vt bv h₁ h).trans - (Eval.intNeg_opInterp_of_lookup f.model (hfac ▸ Eval.coreFactory_intNeg) _) + (Eval.intNeg_opInterp_of_lookup f.model (hfac _ _ Eval.coreFactory_intNeg) _) /-! ### Integer comparisons -/ -theorem denote_lt (hfac : f.factory = Core.Factory) +theorem denote_lt (hfac : Eval.OverCore f.factory) (h₁ : LExpr.HasTypeA Δ e₁ tInt) (h₂ : LExpr.HasTypeA Δ e₂ tInt) (h : LExpr.HasTypeA Δ (.app m (.app m' (.op m'' ⟨"Int.Lt", ()⟩ (some (tArrow tInt (tArrow tInt tBool)))) e₁) e₂) @@ -394,9 +394,9 @@ theorem denote_lt (hfac : f.factory = Core.Factory) = decide (toInt (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv e₁ tInt h₁) < toInt (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv e₂ tInt h₂)) := (denote_app2 (a := .int) (b := .int) (c := .bool) fv vt bv h₁ h₂ h).trans - (Core.intLt_opInterp_of_lookup f.model (hfac ▸ Core.coreFactory_intLt) _ _) + (Core.intLt_opInterp_of_lookup f.model (hfac _ _ Core.coreFactory_intLt) _ _) -theorem denote_le (hfac : f.factory = Core.Factory) +theorem denote_le (hfac : Eval.OverCore f.factory) (h₁ : LExpr.HasTypeA Δ e₁ tInt) (h₂ : LExpr.HasTypeA Δ e₂ tInt) (h : LExpr.HasTypeA Δ (.app m (.app m' (.op m'' ⟨"Int.Le", ()⟩ (some (tArrow tInt (tArrow tInt tBool)))) e₁) e₂) @@ -407,9 +407,9 @@ theorem denote_le (hfac : f.factory = Core.Factory) = decide (toInt (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv e₁ tInt h₁) ≤ toInt (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv e₂ tInt h₂)) := (denote_app2 (a := .int) (b := .int) (c := .bool) fv vt bv h₁ h₂ h).trans - (Core.intLe_opInterp_of_lookup f.model (hfac ▸ Core.coreFactory_intLe) _ _) + (Core.intLe_opInterp_of_lookup f.model (hfac _ _ Core.coreFactory_intLe) _ _) -theorem denote_gt (hfac : f.factory = Core.Factory) +theorem denote_gt (hfac : Eval.OverCore f.factory) (h₁ : LExpr.HasTypeA Δ e₁ tInt) (h₂ : LExpr.HasTypeA Δ e₂ tInt) (h : LExpr.HasTypeA Δ (.app m (.app m' (.op m'' ⟨"Int.Gt", ()⟩ (some (tArrow tInt (tArrow tInt tBool)))) e₁) e₂) @@ -420,9 +420,9 @@ theorem denote_gt (hfac : f.factory = Core.Factory) = decide (toInt (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv e₁ tInt h₁) > toInt (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv e₂ tInt h₂)) := (denote_app2 (a := .int) (b := .int) (c := .bool) fv vt bv h₁ h₂ h).trans - (Core.intGt_opInterp_of_lookup f.model (hfac ▸ Core.coreFactory_intGt) _ _) + (Core.intGt_opInterp_of_lookup f.model (hfac _ _ Core.coreFactory_intGt) _ _) -theorem denote_ge (hfac : f.factory = Core.Factory) +theorem denote_ge (hfac : Eval.OverCore f.factory) (h₁ : LExpr.HasTypeA Δ e₁ tInt) (h₂ : LExpr.HasTypeA Δ e₂ tInt) (h : LExpr.HasTypeA Δ (.app m (.app m' (.op m'' ⟨"Int.Ge", ()⟩ (some (tArrow tInt (tArrow tInt tBool)))) e₁) e₂) @@ -433,11 +433,11 @@ theorem denote_ge (hfac : f.factory = Core.Factory) = decide (toInt (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv e₁ tInt h₁) ≥ toInt (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv e₂ tInt h₂)) := (denote_app2 (a := .int) (b := .int) (c := .bool) fv vt bv h₁ h₂ h).trans - (Core.intGe_opInterp_of_lookup f.model (hfac ▸ Core.coreFactory_intGe) _ _) + (Core.intGe_opInterp_of_lookup f.model (hfac _ _ Core.coreFactory_intGe) _ _) /-! ### Boolean connectives -/ -theorem denote_and (hfac : f.factory = Core.Factory) +theorem denote_and (hfac : Eval.OverCore f.factory) (h₁ : LExpr.HasTypeA Δ e₁ tBool) (h₂ : LExpr.HasTypeA Δ e₂ tBool) (h : LExpr.HasTypeA Δ (.app m (.app m' (.op m'' ⟨"Bool.And", ()⟩ (some (tArrow tBool (tArrow tBool tBool)))) e₁) e₂) @@ -448,9 +448,9 @@ theorem denote_and (hfac : f.factory = Core.Factory) = (toBool (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv e₁ tBool h₁) && toBool (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv e₂ tBool h₂)) := (denote_app2 (a := .bool) (b := .bool) (c := .bool) fv vt bv h₁ h₂ h).trans - (Core.boolAnd_opInterp_of_lookup f.model (hfac ▸ Core.coreFactory_boolAnd) _ _) + (Core.boolAnd_opInterp_of_lookup f.model (hfac _ _ Core.coreFactory_boolAnd) _ _) -theorem denote_or (hfac : f.factory = Core.Factory) +theorem denote_or (hfac : Eval.OverCore f.factory) (h₁ : LExpr.HasTypeA Δ e₁ tBool) (h₂ : LExpr.HasTypeA Δ e₂ tBool) (h : LExpr.HasTypeA Δ (.app m (.app m' (.op m'' ⟨"Bool.Or", ()⟩ (some (tArrow tBool (tArrow tBool tBool)))) e₁) e₂) @@ -461,9 +461,9 @@ theorem denote_or (hfac : f.factory = Core.Factory) = (toBool (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv e₁ tBool h₁) || toBool (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv e₂ tBool h₂)) := (denote_app2 (a := .bool) (b := .bool) (c := .bool) fv vt bv h₁ h₂ h).trans - (Core.boolOr_opInterp_of_lookup f.model (hfac ▸ Core.coreFactory_boolOr) _ _) + (Core.boolOr_opInterp_of_lookup f.model (hfac _ _ Core.coreFactory_boolOr) _ _) -theorem denote_implies (hfac : f.factory = Core.Factory) +theorem denote_implies (hfac : Eval.OverCore f.factory) (h₁ : LExpr.HasTypeA Δ e₁ tBool) (h₂ : LExpr.HasTypeA Δ e₂ tBool) (h : LExpr.HasTypeA Δ (.app m (.app m' (.op m'' ⟨"Bool.Implies", ()⟩ (some (tArrow tBool (tArrow tBool tBool)))) e₁) e₂) @@ -474,9 +474,9 @@ theorem denote_implies (hfac : f.factory = Core.Factory) = (!toBool (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv e₁ tBool h₁) || toBool (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv e₂ tBool h₂)) := (denote_app2 (a := .bool) (b := .bool) (c := .bool) fv vt bv h₁ h₂ h).trans - (Eval.boolImplies_opInterp_of_lookup f.model (hfac ▸ Eval.coreFactory_boolImplies) _ _) + (Eval.boolImplies_opInterp_of_lookup f.model (hfac _ _ Eval.coreFactory_boolImplies) _ _) -theorem denote_equiv (hfac : f.factory = Core.Factory) +theorem denote_equiv (hfac : Eval.OverCore f.factory) (h₁ : LExpr.HasTypeA Δ e₁ tBool) (h₂ : LExpr.HasTypeA Δ e₂ tBool) (h : LExpr.HasTypeA Δ (.app m (.app m' (.op m'' ⟨"Bool.Equiv", ()⟩ (some (tArrow tBool (tArrow tBool tBool)))) e₁) e₂) @@ -487,15 +487,15 @@ theorem denote_equiv (hfac : f.factory = Core.Factory) = (toBool (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv e₁ tBool h₁) == toBool (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv e₂ tBool h₂)) := (denote_app2 (a := .bool) (b := .bool) (c := .bool) fv vt bv h₁ h₂ h).trans - (Eval.boolEquiv_opInterp_of_lookup f.model (hfac ▸ Eval.coreFactory_boolEquiv) _ _) + (Eval.boolEquiv_opInterp_of_lookup f.model (hfac _ _ Eval.coreFactory_boolEquiv) _ _) -theorem denote_not (hfac : f.factory = Core.Factory) (h₁ : LExpr.HasTypeA Δ e₁ tBool) +theorem denote_not (hfac : Eval.OverCore f.factory) (h₁ : LExpr.HasTypeA Δ e₁ tBool) (h : LExpr.HasTypeA Δ (.app m (.op m' ⟨"Bool.Not", ()⟩ (some (tArrow tBool tBool))) e₁) tBool) : toBool (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv (.app m (.op m' ⟨"Bool.Not", ()⟩ (some (tArrow tBool tBool))) e₁) tBool h) = !toBool (LExpr.denote f.model.tcInterp f.model.opInterp fv vt bv e₁ tBool h₁) := (denote_app1 (a := .bool) (c := .bool) fv vt bv h₁ h).trans - (Core.boolNot_opInterp_of_lookup f.model (hfac ▸ Core.coreFactory_boolNot) _) + (Core.boolNot_opInterp_of_lookup f.model (hfac _ _ Core.coreFactory_boolNot) _) end Operators diff --git a/StrataBoole/HoareLogic/Hoare/Lift/Eval.lean b/StrataBoole/HoareLogic/Hoare/Lift/Eval.lean index 4bb93eb..1d073a3 100644 --- a/StrataBoole/HoareLogic/Hoare/Lift/Eval.lean +++ b/StrataBoole/HoareLogic/Hoare/Lift/Eval.lean @@ -6,6 +6,7 @@ module public import Strata.Languages.Core.IntEvalProps +public import Strata.Languages.Core.ProgramProps public import StrataBoole.HoareLogic.HoareLift import all Strata.Languages.Core.Factory import all Strata.DL.Lambda.IntBoolFactory @@ -28,7 +29,7 @@ evaluate to integers or Booleans yields the integer or Boolean of the Lean opera Each operator lemma is Strata's `Core.eval_app2_op`, or its unary counterpart `eval_app1_op` here, at the operator's interpretation in the model, which is the Lean operation whenever the -runtime factory is over `Core.Factory` (`*_opInterp_of_lookup`). The lemmas are stated for any +runtime factory is over `Core.Factory` (`OverCore`, `*_opInterp_of_lookup`). The lemmas are stated for any source location on every node and with the types spelled as the lowering writes them (`tcons "int" []`), so that `simp` matches a reflected program without unfolding anything. @@ -233,6 +234,60 @@ theorem boolEquiv_opInterp_of_lookup {factory : Lambda.Factory CoreLParams} @default _ (@Lambda.SortDenote.instInhabited model.tcInterp model.allInhabited s)) (.cons (.const rfl) (.cons (.const rfl) .nil)) (.const rfl)).symm +/-! ## Factories over `Core.Factory` + +The factory visible at a procedure is `Core.Factory` extended with the functions and datatypes +declared before it. Declarations are added only under names not yet taken, so the built-in names +resolve as in `Core.Factory`, which is all the operator lemmas need. -/ + +/-- The factory resolves every name `Core.Factory` knows to the same function. -/ +@[expose] def OverCore (factory : Lambda.Factory CoreLParams) : Prop := + ∀ (x : String) (fn : Lambda.LFunc CoreLParams), + Core.Factory[x]? = some fn → factory[x]? = some fn + +theorem OverCore.core : OverCore Core.Factory := fun _ _ h => h + +theorem OverCore.of_eq {factory factory' : Lambda.Factory CoreLParams} + (h : factory = factory') (h' : OverCore factory') : OverCore factory := h ▸ h' + +/-- A declaration keeps the function a name resolves to. -/ +theorem addToRuntimeFactory_getElem?_of {F : Lambda.Factory CoreLParams} (d : Core.Decl) + {x : String} {fn : Lambda.LFunc CoreLParams} (h : F[x]? = some fn) : + (d.addToRuntimeFactory F)[x]? = some fn := by + unfold Core.Decl.addToRuntimeFactory + split + · split + · unfold Lambda.Factory.append + rw [← Array.foldl_toList] + exact Lambda.Factory.getElem?_foldl_pushIfNew_of _ h + · exact h + · unfold Core.Decl.addFunctionsToFactory + split + · exact Lambda.Factory.getElem?_foldl_pushIfNew_of [_] h + · have hmap : ∀ (l : List Core.Function) (G : Lambda.Factory CoreLParams), + l.foldl (fun factory f => factory.pushIfNew f.toLFunc) G = + (l.map (·.toLFunc)).foldl Lambda.Factory.pushIfNew G := by + intro l + induction l with + | nil => intro G; rfl + | cons a l ih => intro G; simp only [List.foldl_cons, List.map_cons, ih] + rw [hmap] + exact Lambda.Factory.getElem?_foldl_pushIfNew_of _ h + · exact h + +/-- The factory visible at a procedure is over `Core.Factory`. -/ +theorem OverCore.factoryBeforeProcedure (p : Core.Program) (procName : String) : + OverCore (p.factoryBeforeProcedure procName) := by + have hfold : ∀ (ds : List Core.Decl) {F : Lambda.Factory CoreLParams}, OverCore F → + OverCore (ds.foldl Core.Decl.addToRuntimeFactory F) := by + intro ds + induction ds with + | nil => intro F h; exact h + | cons d ds ih => + intro F h + exact ih fun x fn hx => addToRuntimeFactory_getElem?_of d (h x fn hx) + exact hfold _ OverCore.core + /-! ## Operators -/ /-- **Unary operator evaluation**, after `Core.eval_app2_op`. An operator annotated `a → c`, at @@ -280,117 +335,117 @@ variable {f : Expression.Factory} {σ : CoreStore} {m m' m'' : ExpressionMetadat /-! ### Integer arithmetic -/ -theorem eval_add {a b : Int} (hfac : f.factory = Core.Factory) +theorem eval_add {a b : Int} (hfac : OverCore f.factory) (hx : LExpr.denoteEval f σ x = some (intVal f a)) (hy : LExpr.denoteEval f σ y = some (intVal f b)) : LExpr.denoteEval f σ (.app m (.app m' (.op m'' ⟨"Int.Add", ()⟩ (some (tArrow tInt (tArrow tInt tInt)))) x) y) = some (intVal f (a + b)) := Core.eval_app2_op "Int.Add" (c := .int) rfl rfl rfl hx hy - (Core.intAdd_opInterp_of_lookup f.model (hfac ▸ Core.coreFactory_intAdd) a b) + (Core.intAdd_opInterp_of_lookup f.model (hfac _ _ Core.coreFactory_intAdd) a b) -theorem eval_sub {a b : Int} (hfac : f.factory = Core.Factory) +theorem eval_sub {a b : Int} (hfac : OverCore f.factory) (hx : LExpr.denoteEval f σ x = some (intVal f a)) (hy : LExpr.denoteEval f σ y = some (intVal f b)) : LExpr.denoteEval f σ (.app m (.app m' (.op m'' ⟨"Int.Sub", ()⟩ (some (tArrow tInt (tArrow tInt tInt)))) x) y) = some (intVal f (a - b)) := Core.eval_app2_op "Int.Sub" (c := .int) rfl rfl rfl hx hy - (Core.intSub_opInterp_of_lookup f.model (hfac ▸ Core.coreFactory_intSub) a b) + (Core.intSub_opInterp_of_lookup f.model (hfac _ _ Core.coreFactory_intSub) a b) -theorem eval_mul {a b : Int} (hfac : f.factory = Core.Factory) +theorem eval_mul {a b : Int} (hfac : OverCore f.factory) (hx : LExpr.denoteEval f σ x = some (intVal f a)) (hy : LExpr.denoteEval f σ y = some (intVal f b)) : LExpr.denoteEval f σ (.app m (.app m' (.op m'' ⟨"Int.Mul", ()⟩ (some (tArrow tInt (tArrow tInt tInt)))) x) y) = some (intVal f (a * b)) := Core.eval_app2_op "Int.Mul" (c := .int) rfl rfl rfl hx hy - (Core.intMul_opInterp_of_lookup f.model (hfac ▸ Core.coreFactory_intMul) a b) + (Core.intMul_opInterp_of_lookup f.model (hfac _ _ Core.coreFactory_intMul) a b) -theorem eval_div {a b : Int} (hfac : f.factory = Core.Factory) +theorem eval_div {a b : Int} (hfac : OverCore f.factory) (hx : LExpr.denoteEval f σ x = some (intVal f a)) (hy : LExpr.denoteEval f σ y = some (intVal f b)) (hb : b ≠ 0) : LExpr.denoteEval f σ (.app m (.app m' (.op m'' ⟨"Int.Div", ()⟩ (some (tArrow tInt (tArrow tInt tInt)))) x) y) = some (intVal f (a / b)) := Core.eval_app2_op "Int.Div" (c := .int) rfl rfl rfl hx hy - (intDiv_opInterp_of_lookup f.model (hfac ▸ coreFactory_intDiv) a b hb) + (intDiv_opInterp_of_lookup f.model (hfac _ _ coreFactory_intDiv) a b hb) -theorem eval_mod {a b : Int} (hfac : f.factory = Core.Factory) +theorem eval_mod {a b : Int} (hfac : OverCore f.factory) (hx : LExpr.denoteEval f σ x = some (intVal f a)) (hy : LExpr.denoteEval f σ y = some (intVal f b)) (hb : b ≠ 0) : LExpr.denoteEval f σ (.app m (.app m' (.op m'' ⟨"Int.Mod", ()⟩ (some (tArrow tInt (tArrow tInt tInt)))) x) y) = some (intVal f (a % b)) := Core.eval_app2_op "Int.Mod" (c := .int) rfl rfl rfl hx hy - (intMod_opInterp_of_lookup f.model (hfac ▸ coreFactory_intMod) a b hb) + (intMod_opInterp_of_lookup f.model (hfac _ _ coreFactory_intMod) a b hb) -theorem eval_neg {a : Int} (hfac : f.factory = Core.Factory) +theorem eval_neg {a : Int} (hfac : OverCore f.factory) (hx : LExpr.denoteEval f σ x = some (intVal f a)) : LExpr.denoteEval f σ (.app m (.op m' ⟨"Int.Neg", ()⟩ (some (tArrow tInt tInt))) x) = some (intVal f (-a)) := eval_app1_op "Int.Neg" (a := .int) (c := .int) rfl rfl hx - (intNeg_opInterp_of_lookup f.model (hfac ▸ coreFactory_intNeg) a) + (intNeg_opInterp_of_lookup f.model (hfac _ _ coreFactory_intNeg) a) /-! ### Integer comparisons -/ -theorem eval_lt {a b : Int} (hfac : f.factory = Core.Factory) +theorem eval_lt {a b : Int} (hfac : OverCore f.factory) (hx : LExpr.denoteEval f σ x = some (intVal f a)) (hy : LExpr.denoteEval f σ y = some (intVal f b)) : LExpr.denoteEval f σ (.app m (.app m' (.op m'' ⟨"Int.Lt", ()⟩ (some (tArrow tInt (tArrow tInt tBool)))) x) y) = some (boolVal f (decide (a < b))) := Core.eval_app2_op "Int.Lt" (c := .bool) rfl rfl rfl hx hy - (Core.intLt_opInterp_of_lookup f.model (hfac ▸ Core.coreFactory_intLt) a b) + (Core.intLt_opInterp_of_lookup f.model (hfac _ _ Core.coreFactory_intLt) a b) -theorem eval_le {a b : Int} (hfac : f.factory = Core.Factory) +theorem eval_le {a b : Int} (hfac : OverCore f.factory) (hx : LExpr.denoteEval f σ x = some (intVal f a)) (hy : LExpr.denoteEval f σ y = some (intVal f b)) : LExpr.denoteEval f σ (.app m (.app m' (.op m'' ⟨"Int.Le", ()⟩ (some (tArrow tInt (tArrow tInt tBool)))) x) y) = some (boolVal f (decide (a ≤ b))) := Core.eval_app2_op "Int.Le" (c := .bool) rfl rfl rfl hx hy - (Core.intLe_opInterp_of_lookup f.model (hfac ▸ Core.coreFactory_intLe) a b) + (Core.intLe_opInterp_of_lookup f.model (hfac _ _ Core.coreFactory_intLe) a b) -theorem eval_gt {a b : Int} (hfac : f.factory = Core.Factory) +theorem eval_gt {a b : Int} (hfac : OverCore f.factory) (hx : LExpr.denoteEval f σ x = some (intVal f a)) (hy : LExpr.denoteEval f σ y = some (intVal f b)) : LExpr.denoteEval f σ (.app m (.app m' (.op m'' ⟨"Int.Gt", ()⟩ (some (tArrow tInt (tArrow tInt tBool)))) x) y) = some (boolVal f (decide (a > b))) := Core.eval_app2_op "Int.Gt" (c := .bool) rfl rfl rfl hx hy - (Core.intGt_opInterp_of_lookup f.model (hfac ▸ Core.coreFactory_intGt) a b) + (Core.intGt_opInterp_of_lookup f.model (hfac _ _ Core.coreFactory_intGt) a b) -theorem eval_ge {a b : Int} (hfac : f.factory = Core.Factory) +theorem eval_ge {a b : Int} (hfac : OverCore f.factory) (hx : LExpr.denoteEval f σ x = some (intVal f a)) (hy : LExpr.denoteEval f σ y = some (intVal f b)) : LExpr.denoteEval f σ (.app m (.app m' (.op m'' ⟨"Int.Ge", ()⟩ (some (tArrow tInt (tArrow tInt tBool)))) x) y) = some (boolVal f (decide (a ≥ b))) := Core.eval_app2_op "Int.Ge" (c := .bool) rfl rfl rfl hx hy - (Core.intGe_opInterp_of_lookup f.model (hfac ▸ Core.coreFactory_intGe) a b) + (Core.intGe_opInterp_of_lookup f.model (hfac _ _ Core.coreFactory_intGe) a b) /-! ### Boolean connectives -/ -theorem eval_and {p q : Bool} (hfac : f.factory = Core.Factory) +theorem eval_and {p q : Bool} (hfac : OverCore f.factory) (hx : LExpr.denoteEval f σ x = some (boolVal f p)) (hy : LExpr.denoteEval f σ y = some (boolVal f q)) : LExpr.denoteEval f σ (.app m (.app m' (.op m'' ⟨"Bool.And", ()⟩ (some (tArrow tBool (tArrow tBool tBool)))) x) y) = some (boolVal f (p && q)) := Core.eval_app2_op "Bool.And" (c := .bool) rfl rfl rfl hx hy - (Core.boolAnd_opInterp_of_lookup f.model (hfac ▸ Core.coreFactory_boolAnd) p q) + (Core.boolAnd_opInterp_of_lookup f.model (hfac _ _ Core.coreFactory_boolAnd) p q) -theorem eval_or {p q : Bool} (hfac : f.factory = Core.Factory) +theorem eval_or {p q : Bool} (hfac : OverCore f.factory) (hx : LExpr.denoteEval f σ x = some (boolVal f p)) (hy : LExpr.denoteEval f σ y = some (boolVal f q)) : LExpr.denoteEval f σ (.app m (.app m' (.op m'' ⟨"Bool.Or", ()⟩ (some (tArrow tBool (tArrow tBool tBool)))) x) y) = some (boolVal f (p || q)) := Core.eval_app2_op "Bool.Or" (c := .bool) rfl rfl rfl hx hy - (Core.boolOr_opInterp_of_lookup f.model (hfac ▸ Core.coreFactory_boolOr) p q) + (Core.boolOr_opInterp_of_lookup f.model (hfac _ _ Core.coreFactory_boolOr) p q) -theorem eval_implies {p q : Bool} (hfac : f.factory = Core.Factory) +theorem eval_implies {p q : Bool} (hfac : OverCore f.factory) (hx : LExpr.denoteEval f σ x = some (boolVal f p)) (hy : LExpr.denoteEval f σ y = some (boolVal f q)) : LExpr.denoteEval f σ @@ -398,9 +453,9 @@ theorem eval_implies {p q : Bool} (hfac : f.factory = Core.Factory) y) = some (boolVal f (!p || q)) := Core.eval_app2_op "Bool.Implies" (c := .bool) rfl rfl rfl hx hy - (boolImplies_opInterp_of_lookup f.model (hfac ▸ coreFactory_boolImplies) p q) + (boolImplies_opInterp_of_lookup f.model (hfac _ _ coreFactory_boolImplies) p q) -theorem eval_equiv {p q : Bool} (hfac : f.factory = Core.Factory) +theorem eval_equiv {p q : Bool} (hfac : OverCore f.factory) (hx : LExpr.denoteEval f σ x = some (boolVal f p)) (hy : LExpr.denoteEval f σ y = some (boolVal f q)) : LExpr.denoteEval f σ @@ -408,14 +463,14 @@ theorem eval_equiv {p q : Bool} (hfac : f.factory = Core.Factory) y) = some (boolVal f (p == q)) := Core.eval_app2_op "Bool.Equiv" (c := .bool) rfl rfl rfl hx hy - (boolEquiv_opInterp_of_lookup f.model (hfac ▸ coreFactory_boolEquiv) p q) + (boolEquiv_opInterp_of_lookup f.model (hfac _ _ coreFactory_boolEquiv) p q) -theorem eval_not {p : Bool} (hfac : f.factory = Core.Factory) +theorem eval_not {p : Bool} (hfac : OverCore f.factory) (hx : LExpr.denoteEval f σ x = some (boolVal f p)) : LExpr.denoteEval f σ (.app m (.op m' ⟨"Bool.Not", ()⟩ (some (tArrow tBool tBool))) x) = some (boolVal f (!p)) := eval_app1_op "Bool.Not" (a := .bool) (c := .bool) rfl rfl hx - (Core.boolNot_opInterp_of_lookup f.model (hfac ▸ Core.coreFactory_boolNot) p) + (Core.boolNot_opInterp_of_lookup f.model (hfac _ _ Core.coreFactory_boolNot) p) /-! ### Equality and conditionals -/ diff --git a/StrataBoole/HoareLogic/Hoare/Tactic.lean b/StrataBoole/HoareLogic/Hoare/Tactic.lean index 95e4627..de03048 100644 --- a/StrataBoole/HoareLogic/Hoare/Tactic.lean +++ b/StrataBoole/HoareLogic/Hoare/Tactic.lean @@ -478,6 +478,34 @@ elab "hoare_typed" : tactic => withMainContext do at $hΓ:ident)) bindTyped hΓ elems +/-- Introduce the value each `out` parameter `x` holds at the entry as `x_entry`, typed like an +input, with the store fact `hx`. Works on `hout : outputAsPredicate proc ρ`, with `hwf` in +context; an `inout` parameter is among the inputs and is skipped. -/ +elab "hoare_typed_outputs" : tactic => withMainContext do + let hout := mkIdent `hout + let hwf := mkIdent `hwf + let proc ← argOf `hout 0 + let procStx ← Term.exprToSyntax proc + let ins ← listElems (← Term.elabTerm (← `(($procStx).header.inputs.toList)) none) + let inNames ← ins.mapM fun e => do identName (← pairElems e).1 + let outs ← listElems (← Term.elabTerm (← `(($procStx).header.outputs.toList)) none) + for e in outs, i in List.range outs.length do + let (x, ty) ← withMainContext (pairElems e) + let name ← identName x + if inNames.contains name then continue + let xId := mkIdent (Name.mkSimple (name ++ "_entry")) + let hId := mkIdent (Name.mkSimple ("h" ++ name)) + let mem ← memProof i + let cur ← `(Strata.Hoare.output_typed $hwf:ident $hout:ident $mem) + if ← isIntTy ty then + evalTactic (← `(tactic| obtain ⟨$xId:ident, $hId:ident⟩ := Strata.Hoare.typed_int_of $cur)) + else if ← isBoolTy ty then + evalTactic (← `(tactic| obtain ⟨$xId:ident, $hId:ident⟩ := Strata.Hoare.typed_bool_of $cur)) + else + evalTactic (← `(tactic| obtain ⟨$xId:ident, $hId:ident, -⟩ := $cur)) + evalTactic (← `(tactic| try dsimp only at $hId:ident)) + evalTactic (← `(tactic| try clear $hout:ident)) + /-- Introduce the entry snapshot of each `inout` parameter `x`: the store fact `hold_x` that the variable `old x`, which a contract's `old(x)` reads, holds the parameter's entry value. Works on `hold : oldInoutAsPredicate proc ρ` with the store facts of the inputs in context and the store @@ -500,7 +528,7 @@ elab "hoare_old" : tactic => withMainContext do evalTactic (← `(tactic| try clear $hold:ident)) /-- Lift each `requires` clause into a hypothesis `h